/* Minification failed. Returning unminified contents.
(1451,17-18): run-time error JS1003: Expected ':': }
(1490,21-22): run-time error JS1003: Expected ':': }
(1512,21-22): run-time error JS1003: Expected ':': }
(4657,25-39): run-time error JS1298: Assignment to constant: coverageAmount
 */
/*!
 * Modernizr v2.8.3
 * www.modernizr.com
 *
 * Copyright (c) Faruk Ates, Paul Irish, Alex Sexton
 * Available under the BSD and MIT licenses: www.modernizr.com/license/
 */

/*
 * Modernizr tests which native CSS3 and HTML5 features are available in
 * the current UA and makes the results available to you in two ways:
 * as properties on a global Modernizr object, and as classes on the
 * <html> element. This information allows you to progressively enhance
 * your pages with a granular level of control over the experience.
 *
 * Modernizr has an optional (not included) conditional resource loader
 * called Modernizr.load(), based on Yepnope.js (yepnopejs.com).
 * To get a build that includes Modernizr.load(), as well as choosing
 * which tests to include, go to www.modernizr.com/download/
 *
 * Authors        Faruk Ates, Paul Irish, Alex Sexton
 * Contributors   Ryan Seddon, Ben Alman
 */

window.Modernizr = (function( window, document, undefined ) {

    var version = '2.8.3',

    Modernizr = {},

    /*>>cssclasses*/
    // option for enabling the HTML classes to be added
    enableClasses = true,
    /*>>cssclasses*/

    docElement = document.documentElement,

    /**
     * Create our "modernizr" element that we do most feature tests on.
     */
    mod = 'modernizr',
    modElem = document.createElement(mod),
    mStyle = modElem.style,

    /**
     * Create the input element for various Web Forms feature tests.
     */
    inputElem /*>>inputelem*/ = document.createElement('input') /*>>inputelem*/ ,

    /*>>smile*/
    smile = ':)',
    /*>>smile*/

    toString = {}.toString,

    // TODO :: make the prefixes more granular
    /*>>prefixes*/
    // List of property values to set for css tests. See ticket #21
    prefixes = ' -webkit- -moz- -o- -ms- '.split(' '),
    /*>>prefixes*/

    /*>>domprefixes*/
    // Following spec is to expose vendor-specific style properties as:
    //   elem.style.WebkitBorderRadius
    // and the following would be incorrect:
    //   elem.style.webkitBorderRadius

    // Webkit ghosts their properties in lowercase but Opera & Moz do not.
    // Microsoft uses a lowercase `ms` instead of the correct `Ms` in IE8+
    //   erik.eae.net/archives/2008/03/10/21.48.10/

    // More here: github.com/Modernizr/Modernizr/issues/issue/21
    omPrefixes = 'Webkit Moz O ms',

    cssomPrefixes = omPrefixes.split(' '),

    domPrefixes = omPrefixes.toLowerCase().split(' '),
    /*>>domprefixes*/

    /*>>ns*/
    ns = {'svg': 'http://www.w3.org/2000/svg'},
    /*>>ns*/

    tests = {},
    inputs = {},
    attrs = {},

    classes = [],

    slice = classes.slice,

    featureName, // used in testing loop


    /*>>teststyles*/
    // Inject element with style element and some CSS rules
    injectElementWithStyles = function( rule, callback, nodes, testnames ) {

      var style, ret, node, docOverflow,
          div = document.createElement('div'),
          // After page load injecting a fake body doesn't work so check if body exists
          body = document.body,
          // IE6 and 7 won't return offsetWidth or offsetHeight unless it's in the body element, so we fake it.
          fakeBody = body || document.createElement('body');

      if ( parseInt(nodes, 10) ) {
          // In order not to give false positives we create a node for each test
          // This also allows the method to scale for unspecified uses
          while ( nodes-- ) {
              node = document.createElement('div');
              node.id = testnames ? testnames[nodes] : mod + (nodes + 1);
              div.appendChild(node);
          }
      }

      // <style> elements in IE6-9 are considered 'NoScope' elements and therefore will be removed
      // when injected with innerHTML. To get around this you need to prepend the 'NoScope' element
      // with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements.
      // msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx
      // Documents served as xml will throw if using &shy; so use xml friendly encoded version. See issue #277
      style = ['&#173;','<style id="s', mod, '">', rule, '</style>'].join('');
      div.id = mod;
      // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody.
      // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270
      (body ? div : fakeBody).innerHTML += style;
      fakeBody.appendChild(div);
      if ( !body ) {
          //avoid crashing IE8, if background image is used
          fakeBody.style.background = '';
          //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible
          fakeBody.style.overflow = 'hidden';
          docOverflow = docElement.style.overflow;
          docElement.style.overflow = 'hidden';
          docElement.appendChild(fakeBody);
      }

      ret = callback(div, rule);
      // If this is done after page load we don't want to remove the body so check if body exists
      if ( !body ) {
          fakeBody.parentNode.removeChild(fakeBody);
          docElement.style.overflow = docOverflow;
      } else {
          div.parentNode.removeChild(div);
      }

      return !!ret;

    },
    /*>>teststyles*/

    /*>>mq*/
    // adapted from matchMedia polyfill
    // by Scott Jehl and Paul Irish
    // gist.github.com/786768
    testMediaQuery = function( mq ) {

      var matchMedia = window.matchMedia || window.msMatchMedia;
      if ( matchMedia ) {
        return matchMedia(mq) && matchMedia(mq).matches || false;
      }

      var bool;

      injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) {
        bool = (window.getComputedStyle ?
                  getComputedStyle(node, null) :
                  node.currentStyle)['position'] == 'absolute';
      });

      return bool;

     },
     /*>>mq*/


    /*>>hasevent*/
    //
    // isEventSupported determines if a given element supports the given event
    // kangax.github.com/iseventsupported/
    //
    // The following results are known incorrects:
    //   Modernizr.hasEvent("webkitTransitionEnd", elem) // false negative
    //   Modernizr.hasEvent("textInput") // in Webkit. github.com/Modernizr/Modernizr/issues/333
    //   ...
    isEventSupported = (function() {

      var TAGNAMES = {
        'select': 'input', 'change': 'input',
        'submit': 'form', 'reset': 'form',
        'error': 'img', 'load': 'img', 'abort': 'img'
      };

      function isEventSupported( eventName, element ) {

        element = element || document.createElement(TAGNAMES[eventName] || 'div');
        eventName = 'on' + eventName;

        // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those
        var isSupported = eventName in element;

        if ( !isSupported ) {
          // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element
          if ( !element.setAttribute ) {
            element = document.createElement('div');
          }
          if ( element.setAttribute && element.removeAttribute ) {
            element.setAttribute(eventName, '');
            isSupported = is(element[eventName], 'function');

            // If property was created, "remove it" (by setting value to `undefined`)
            if ( !is(element[eventName], 'undefined') ) {
              element[eventName] = undefined;
            }
            element.removeAttribute(eventName);
          }
        }

        element = null;
        return isSupported;
      }
      return isEventSupported;
    })(),
    /*>>hasevent*/

    // TODO :: Add flag for hasownprop ? didn't last time

    // hasOwnProperty shim by kangax needed for Safari 2.0 support
    _hasOwnProperty = ({}).hasOwnProperty, hasOwnProp;

    if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) {
      hasOwnProp = function (object, property) {
        return _hasOwnProperty.call(object, property);
      };
    }
    else {
      hasOwnProp = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */
        return ((property in object) && is(object.constructor.prototype[property], 'undefined'));
      };
    }

    // Adapted from ES5-shim https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js
    // es5.github.com/#x15.3.4.5

    if (!Function.prototype.bind) {
      Function.prototype.bind = function bind(that) {

        var target = this;

        if (typeof target != "function") {
            throw new TypeError();
        }

        var args = slice.call(arguments, 1),
            bound = function () {

            if (this instanceof bound) {

              var F = function(){};
              F.prototype = target.prototype;
              var self = new F();

              var result = target.apply(
                  self,
                  args.concat(slice.call(arguments))
              );
              if (Object(result) === result) {
                  return result;
              }
              return self;

            } else {

              return target.apply(
                  that,
                  args.concat(slice.call(arguments))
              );

            }

        };

        return bound;
      };
    }

    /**
     * setCss applies given styles to the Modernizr DOM node.
     */
    function setCss( str ) {
        mStyle.cssText = str;
    }

    /**
     * setCssAll extrapolates all vendor-specific css strings.
     */
    function setCssAll( str1, str2 ) {
        return setCss(prefixes.join(str1 + ';') + ( str2 || '' ));
    }

    /**
     * is returns a boolean for if typeof obj is exactly type.
     */
    function is( obj, type ) {
        return typeof obj === type;
    }

    /**
     * contains returns a boolean for if substr is found within str.
     */
    function contains( str, substr ) {
        return !!~('' + str).indexOf(substr);
    }

    /*>>testprop*/

    // testProps is a generic CSS / DOM property test.

    // In testing support for a given CSS property, it's legit to test:
    //    `elem.style[styleName] !== undefined`
    // If the property is supported it will return an empty string,
    // if unsupported it will return undefined.

    // We'll take advantage of this quick test and skip setting a style
    // on our modernizr element, but instead just testing undefined vs
    // empty string.

    // Because the testing of the CSS property names (with "-", as
    // opposed to the camelCase DOM properties) is non-portable and
    // non-standard but works in WebKit and IE (but not Gecko or Opera),
    // we explicitly reject properties with dashes so that authors
    // developing in WebKit or IE first don't end up with
    // browser-specific content by accident.

    function testProps( props, prefixed ) {
        for ( var i in props ) {
            var prop = props[i];
            if ( !contains(prop, "-") && mStyle[prop] !== undefined ) {
                return prefixed == 'pfx' ? prop : true;
            }
        }
        return false;
    }
    /*>>testprop*/

    // TODO :: add testDOMProps
    /**
     * testDOMProps is a generic DOM property test; if a browser supports
     *   a certain property, it won't return undefined for it.
     */
    function testDOMProps( props, obj, elem ) {
        for ( var i in props ) {
            var item = obj[props[i]];
            if ( item !== undefined) {

                // return the property name as a string
                if (elem === false) return props[i];

                // let's bind a function
                if (is(item, 'function')){
                  // default to autobind unless override
                  return item.bind(elem || obj);
                }

                // return the unbound function or obj or value
                return item;
            }
        }
        return false;
    }

    /*>>testallprops*/
    /**
     * testPropsAll tests a list of DOM properties we want to check against.
     *   We specify literally ALL possible (known and/or likely) properties on
     *   the element including the non-vendor prefixed one, for forward-
     *   compatibility.
     */
    function testPropsAll( prop, prefixed, elem ) {

        var ucProp  = prop.charAt(0).toUpperCase() + prop.slice(1),
            props   = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' ');

        // did they call .prefixed('boxSizing') or are we just testing a prop?
        if(is(prefixed, "string") || is(prefixed, "undefined")) {
          return testProps(props, prefixed);

        // otherwise, they called .prefixed('requestAnimationFrame', window[, elem])
        } else {
          props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' ');
          return testDOMProps(props, prefixed, elem);
        }
    }
    /*>>testallprops*/


    /**
     * Tests
     * -----
     */

    // The *new* flexbox
    // dev.w3.org/csswg/css3-flexbox

    tests['flexbox'] = function() {
      return testPropsAll('flexWrap');
    };

    // The *old* flexbox
    // www.w3.org/TR/2009/WD-css3-flexbox-20090723/

    tests['flexboxlegacy'] = function() {
        return testPropsAll('boxDirection');
    };

    // On the S60 and BB Storm, getContext exists, but always returns undefined
    // so we actually have to call getContext() to verify
    // github.com/Modernizr/Modernizr/issues/issue/97/

    tests['canvas'] = function() {
        var elem = document.createElement('canvas');
        return !!(elem.getContext && elem.getContext('2d'));
    };

    tests['canvastext'] = function() {
        return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function'));
    };

    // webk.it/70117 is tracking a legit WebGL feature detect proposal

    // We do a soft detect which may false positive in order to avoid
    // an expensive context creation: bugzil.la/732441

    tests['webgl'] = function() {
        return !!window.WebGLRenderingContext;
    };

    /*
     * The Modernizr.touch test only indicates if the browser supports
     *    touch events, which does not necessarily reflect a touchscreen
     *    device, as evidenced by tablets running Windows 7 or, alas,
     *    the Palm Pre / WebOS (touch) phones.
     *
     * Additionally, Chrome (desktop) used to lie about its support on this,
     *    but that has since been rectified: crbug.com/36415
     *
     * We also test for Firefox 4 Multitouch Support.
     *
     * For more info, see: modernizr.github.com/Modernizr/touch.html
     */

    tests['touch'] = function() {
        var bool;

        if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
          bool = true;
        } else {
          injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function( node ) {
            bool = node.offsetTop === 9;
          });
        }

        return bool;
    };


    // geolocation is often considered a trivial feature detect...
    // Turns out, it's quite tricky to get right:
    //
    // Using !!navigator.geolocation does two things we don't want. It:
    //   1. Leaks memory in IE9: github.com/Modernizr/Modernizr/issues/513
    //   2. Disables page caching in WebKit: webk.it/43956
    //
    // Meanwhile, in Firefox < 8, an about:config setting could expose
    // a false positive that would throw an exception: bugzil.la/688158

    tests['geolocation'] = function() {
        return 'geolocation' in navigator;
    };


    tests['postmessage'] = function() {
      return !!window.postMessage;
    };


    // Chrome incognito mode used to throw an exception when using openDatabase
    // It doesn't anymore.
    tests['websqldatabase'] = function() {
      return !!window.openDatabase;
    };

    // Vendors had inconsistent prefixing with the experimental Indexed DB:
    // - Webkit's implementation is accessible through webkitIndexedDB
    // - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB
    // For speed, we don't test the legacy (and beta-only) indexedDB
    tests['indexedDB'] = function() {
      return !!testPropsAll("indexedDB", window);
    };

    // documentMode logic from YUI to filter out IE8 Compat Mode
    //   which false positives.
    tests['hashchange'] = function() {
      return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7);
    };

    // Per 1.6:
    // This used to be Modernizr.historymanagement but the longer
    // name has been deprecated in favor of a shorter and property-matching one.
    // The old API is still available in 1.6, but as of 2.0 will throw a warning,
    // and in the first release thereafter disappear entirely.
    tests['history'] = function() {
      return !!(window.history && history.pushState);
    };

    tests['draganddrop'] = function() {
        var div = document.createElement('div');
        return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
    };

    // FF3.6 was EOL'ed on 4/24/12, but the ESR version of FF10
    // will be supported until FF19 (2/12/13), at which time, ESR becomes FF17.
    // FF10 still uses prefixes, so check for it until then.
    // for more ESR info, see: mozilla.org/en-US/firefox/organizations/faq/
    tests['websockets'] = function() {
        return 'WebSocket' in window || 'MozWebSocket' in window;
    };


    // css-tricks.com/rgba-browser-support/
    tests['rgba'] = function() {
        // Set an rgba() color and check the returned value

        setCss('background-color:rgba(150,255,150,.5)');

        return contains(mStyle.backgroundColor, 'rgba');
    };

    tests['hsla'] = function() {
        // Same as rgba(), in fact, browsers re-map hsla() to rgba() internally,
        //   except IE9 who retains it as hsla

        setCss('background-color:hsla(120,40%,100%,.5)');

        return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla');
    };

    tests['multiplebgs'] = function() {
        // Setting multiple images AND a color on the background shorthand property
        //  and then querying the style.background property value for the number of
        //  occurrences of "url(" is a reliable method for detecting ACTUAL support for this!

        setCss('background:url(https://),url(https://),red url(https://)');

        // If the UA supports multiple backgrounds, there should be three occurrences
        //   of the string "url(" in the return value for elemStyle.background

        return (/(url\s*\(.*?){3}/).test(mStyle.background);
    };



    // this will false positive in Opera Mini
    //   github.com/Modernizr/Modernizr/issues/396

    tests['backgroundsize'] = function() {
        return testPropsAll('backgroundSize');
    };

    tests['borderimage'] = function() {
        return testPropsAll('borderImage');
    };


    // Super comprehensive table about all the unique implementations of
    // border-radius: muddledramblings.com/table-of-css3-border-radius-compliance

    tests['borderradius'] = function() {
        return testPropsAll('borderRadius');
    };

    // WebOS unfortunately false positives on this test.
    tests['boxshadow'] = function() {
        return testPropsAll('boxShadow');
    };

    // FF3.0 will false positive on this test
    tests['textshadow'] = function() {
        return document.createElement('div').style.textShadow === '';
    };


    tests['opacity'] = function() {
        // Browsers that actually have CSS Opacity implemented have done so
        //  according to spec, which means their return values are within the
        //  range of [0.0,1.0] - including the leading zero.

        setCssAll('opacity:.55');

        // The non-literal . in this regex is intentional:
        //   German Chrome returns this value as 0,55
        // github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632
        return (/^0.55$/).test(mStyle.opacity);
    };


    // Note, Android < 4 will pass this test, but can only animate
    //   a single property at a time
    //   goo.gl/v3V4Gp
    tests['cssanimations'] = function() {
        return testPropsAll('animationName');
    };


    tests['csscolumns'] = function() {
        return testPropsAll('columnCount');
    };


    tests['cssgradients'] = function() {
        /**
         * For CSS Gradients syntax, please see:
         * webkit.org/blog/175/introducing-css-gradients/
         * developer.mozilla.org/en/CSS/-moz-linear-gradient
         * developer.mozilla.org/en/CSS/-moz-radial-gradient
         * dev.w3.org/csswg/css3-images/#gradients-
         */

        var str1 = 'background-image:',
            str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));',
            str3 = 'linear-gradient(left top,#9f9, white);';

        setCss(
             // legacy webkit syntax (FIXME: remove when syntax not in use anymore)
              (str1 + '-webkit- '.split(' ').join(str2 + str1) +
             // standard syntax             // trailing 'background-image:'
              prefixes.join(str3 + str1)).slice(0, -str1.length)
        );

        return contains(mStyle.backgroundImage, 'gradient');
    };


    tests['cssreflections'] = function() {
        return testPropsAll('boxReflect');
    };


    tests['csstransforms'] = function() {
        return !!testPropsAll('transform');
    };


    tests['csstransforms3d'] = function() {

        var ret = !!testPropsAll('perspective');

        // Webkit's 3D transforms are passed off to the browser's own graphics renderer.
        //   It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in
        //   some conditions. As a result, Webkit typically recognizes the syntax but
        //   will sometimes throw a false positive, thus we must do a more thorough check:
        if ( ret && 'webkitPerspective' in docElement.style ) {

          // Webkit allows this media query to succeed only if the feature is enabled.
          // `@media (transform-3d),(-webkit-transform-3d){ ... }`
          injectElementWithStyles('@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}', function( node, rule ) {
            ret = node.offsetLeft === 9 && node.offsetHeight === 3;
          });
        }
        return ret;
    };


    tests['csstransitions'] = function() {
        return testPropsAll('transition');
    };


    /*>>fontface*/
    // @font-face detection routine by Diego Perini
    // javascript.nwbox.com/CSSSupport/

    // false positives:
    //   WebOS github.com/Modernizr/Modernizr/issues/342
    //   WP7   github.com/Modernizr/Modernizr/issues/538
    tests['fontface'] = function() {
        var bool;

        injectElementWithStyles('@font-face {font-family:"font";src:url("https://")}', function( node, rule ) {
          var style = document.getElementById('smodernizr'),
              sheet = style.sheet || style.styleSheet,
              cssText = sheet ? (sheet.cssRules && sheet.cssRules[0] ? sheet.cssRules[0].cssText : sheet.cssText || '') : '';

          bool = /src/i.test(cssText) && cssText.indexOf(rule.split(' ')[0]) === 0;
        });

        return bool;
    };
    /*>>fontface*/

    // CSS generated content detection
    tests['generatedcontent'] = function() {
        var bool;

        injectElementWithStyles(['#',mod,'{font:0/0 a}#',mod,':after{content:"',smile,'";visibility:hidden;font:3px/1 a}'].join(''), function( node ) {
          bool = node.offsetHeight >= 3;
        });

        return bool;
    };



    // These tests evaluate support of the video/audio elements, as well as
    // testing what types of content they support.
    //
    // We're using the Boolean constructor here, so that we can extend the value
    // e.g.  Modernizr.video     // true
    //       Modernizr.video.ogg // 'probably'
    //
    // Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845
    //                     thx to NielsLeenheer and zcorpan

    // Note: in some older browsers, "no" was a return value instead of empty string.
    //   It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2
    //   It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5

    tests['video'] = function() {
        var elem = document.createElement('video'),
            bool = false;

        // IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224
        try {
            if ( bool = !!elem.canPlayType ) {
                bool      = new Boolean(bool);
                bool.ogg  = elem.canPlayType('video/ogg; codecs="theora"')      .replace(/^no$/,'');

                // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546
                bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,'');

                bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,'');
            }

        } catch(e) { }

        return bool;
    };

    tests['audio'] = function() {
        var elem = document.createElement('audio'),
            bool = false;

        try {
            if ( bool = !!elem.canPlayType ) {
                bool      = new Boolean(bool);
                bool.ogg  = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,'');
                bool.mp3  = elem.canPlayType('audio/mpeg;')               .replace(/^no$/,'');

                // Mimetypes accepted:
                //   developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
                //   bit.ly/iphoneoscodecs
                bool.wav  = elem.canPlayType('audio/wav; codecs="1"')     .replace(/^no$/,'');
                bool.m4a  = ( elem.canPlayType('audio/x-m4a;')            ||
                              elem.canPlayType('audio/aac;'))             .replace(/^no$/,'');
            }
        } catch(e) { }

        return bool;
    };


    // In FF4, if disabled, window.localStorage should === null.

    // Normally, we could not test that directly and need to do a
    //   `('localStorage' in window) && ` test first because otherwise Firefox will
    //   throw bugzil.la/365772 if cookies are disabled

    // Also in iOS5 Private Browsing mode, attempting to use localStorage.setItem
    // will throw the exception:
    //   QUOTA_EXCEEDED_ERRROR DOM Exception 22.
    // Peculiarly, getItem and removeItem calls do not throw.

    // Because we are forced to try/catch this, we'll go aggressive.

    // Just FWIW: IE8 Compat mode supports these features completely:
    //   www.quirksmode.org/dom/html5.html
    // But IE8 doesn't support either with local files

    tests['localstorage'] = function() {
        try {
            localStorage.setItem(mod, mod);
            localStorage.removeItem(mod);
            return true;
        } catch(e) {
            return false;
        }
    };

    tests['sessionstorage'] = function() {
        try {
            sessionStorage.setItem(mod, mod);
            sessionStorage.removeItem(mod);
            return true;
        } catch(e) {
            return false;
        }
    };


    tests['webworkers'] = function() {
        return !!window.Worker;
    };


    tests['applicationcache'] = function() {
        return !!window.applicationCache;
    };


    // Thanks to Erik Dahlstrom
    tests['svg'] = function() {
        return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect;
    };

    // specifically for SVG inline in HTML, not within XHTML
    // test page: paulirish.com/demo/inline-svg
    tests['inlinesvg'] = function() {
      var div = document.createElement('div');
      div.innerHTML = '<svg/>';
      return (div.firstChild && div.firstChild.namespaceURI) == ns.svg;
    };

    // SVG SMIL animation
    tests['smil'] = function() {
        return !!document.createElementNS && /SVGAnimate/.test(toString.call(document.createElementNS(ns.svg, 'animate')));
    };

    // This test is only for clip paths in SVG proper, not clip paths on HTML content
    // demo: srufaculty.sru.edu/david.dailey/svg/newstuff/clipPath4.svg

    // However read the comments to dig into applying SVG clippaths to HTML content here:
    //   github.com/Modernizr/Modernizr/issues/213#issuecomment-1149491
    tests['svgclippaths'] = function() {
        return !!document.createElementNS && /SVGClipPath/.test(toString.call(document.createElementNS(ns.svg, 'clipPath')));
    };

    /*>>webforms*/
    // input features and input types go directly onto the ret object, bypassing the tests loop.
    // Hold this guy to execute in a moment.
    function webforms() {
        /*>>input*/
        // Run through HTML5's new input attributes to see if the UA understands any.
        // We're using f which is the <input> element created early on
        // Mike Taylr has created a comprehensive resource for testing these attributes
        //   when applied to all input types:
        //   miketaylr.com/code/input-type-attr.html
        // spec: www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary

        // Only input placeholder is tested while textarea's placeholder is not.
        // Currently Safari 4 and Opera 11 have support only for the input placeholder
        // Both tests are available in feature-detects/forms-placeholder.js
        Modernizr['input'] = (function( props ) {
            for ( var i = 0, len = props.length; i < len; i++ ) {
                attrs[ props[i] ] = !!(props[i] in inputElem);
            }
            if (attrs.list){
              // safari false positive's on datalist: webk.it/74252
              // see also github.com/Modernizr/Modernizr/issues/146
              attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement);
            }
            return attrs;
        })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' '));
        /*>>input*/

        /*>>inputtypes*/
        // Run through HTML5's new input types to see if the UA understands any.
        //   This is put behind the tests runloop because it doesn't return a
        //   true/false like all the other tests; instead, it returns an object
        //   containing each input type with its corresponding true/false value

        // Big thanks to @miketaylr for the html5 forms expertise. miketaylr.com/
        Modernizr['inputtypes'] = (function(props) {

            for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) {

                inputElem.setAttribute('type', inputElemType = props[i]);
                bool = inputElem.type !== 'text';

                // We first check to see if the type we give it sticks..
                // If the type does, we feed it a textual value, which shouldn't be valid.
                // If the value doesn't stick, we know there's input sanitization which infers a custom UI
                if ( bool ) {

                    inputElem.value         = smile;
                    inputElem.style.cssText = 'position:absolute;visibility:hidden;';

                    if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {

                      docElement.appendChild(inputElem);
                      defaultView = document.defaultView;

                      // Safari 2-4 allows the smiley as a value, despite making a slider
                      bool =  defaultView.getComputedStyle &&
                              defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' &&
                              // Mobile android web browser has false positive, so must
                              // check the height to see if the widget is actually there.
                              (inputElem.offsetHeight !== 0);

                      docElement.removeChild(inputElem);

                    } else if ( /^(search|tel)$/.test(inputElemType) ){
                      // Spec doesn't define any special parsing or detectable UI
                      //   behaviors so we pass these through as true

                      // Interestingly, opera fails the earlier test, so it doesn't
                      //  even make it here.

                    } else if ( /^(url|email)$/.test(inputElemType) ) {
                      // Real url and email support comes with prebaked validation.
                      bool = inputElem.checkValidity && inputElem.checkValidity() === false;

                    } else {
                      // If the upgraded input compontent rejects the :) text, we got a winner
                      bool = inputElem.value != smile;
                    }
                }

                inputs[ props[i] ] = !!bool;
            }
            return inputs;
        })('search tel url email datetime date month week time datetime-local number range color'.split(' '));
        /*>>inputtypes*/
    }
    /*>>webforms*/


    // End of test definitions
    // -----------------------



    // Run through all tests and detect their support in the current UA.
    // todo: hypothetically we could be doing an array of tests and use a basic loop here.
    for ( var feature in tests ) {
        if ( hasOwnProp(tests, feature) ) {
            // run the test, throw the return value into the Modernizr,
            //   then based on that boolean, define an appropriate className
            //   and push it into an array of classes we'll join later.
            featureName  = feature.toLowerCase();
            Modernizr[featureName] = tests[feature]();

            classes.push((Modernizr[featureName] ? '' : 'no-') + featureName);
        }
    }

    /*>>webforms*/
    // input tests need to run.
    Modernizr.input || webforms();
    /*>>webforms*/


    /**
     * addTest allows the user to define their own feature tests
     * the result will be added onto the Modernizr object,
     * as well as an appropriate className set on the html element
     *
     * @param feature - String naming the feature
     * @param test - Function returning true if feature is supported, false if not
     */
     Modernizr.addTest = function ( feature, test ) {
       if ( typeof feature == 'object' ) {
         for ( var key in feature ) {
           if ( hasOwnProp( feature, key ) ) {
             Modernizr.addTest( key, feature[ key ] );
           }
         }
       } else {

         feature = feature.toLowerCase();

         if ( Modernizr[feature] !== undefined ) {
           // we're going to quit if you're trying to overwrite an existing test
           // if we were to allow it, we'd do this:
           //   var re = new RegExp("\\b(no-)?" + feature + "\\b");
           //   docElement.className = docElement.className.replace( re, '' );
           // but, no rly, stuff 'em.
           return Modernizr;
         }

         test = typeof test == 'function' ? test() : test;

         if (typeof enableClasses !== "undefined" && enableClasses) {
           docElement.className += ' ' + (test ? '' : 'no-') + feature;
         }
         Modernizr[feature] = test;

       }

       return Modernizr; // allow chaining.
     };


    // Reset modElem.cssText to nothing to reduce memory footprint.
    setCss('');
    modElem = inputElem = null;

    /*>>shiv*/
    /**
     * @preserve HTML5 Shiv prev3.7.1 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
     */
    ;(function(window, document) {
        /*jshint evil:true */
        /** version */
        var version = '3.7.0';

        /** Preset options */
        var options = window.html5 || {};

        /** Used to skip problem elements */
        var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;

        /** Not all elements can be cloned in IE **/
        var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;

        /** Detect whether the browser supports default html5 styles */
        var supportsHtml5Styles;

        /** Name of the expando, to work with multiple documents or to re-shiv one document */
        var expando = '_html5shiv';

        /** The id for the the documents expando */
        var expanID = 0;

        /** Cached data for each document */
        var expandoData = {};

        /** Detect whether the browser supports unknown elements */
        var supportsUnknownElements;

        (function() {
          try {
            var a = document.createElement('a');
            a.innerHTML = '<xyz></xyz>';
            //if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles
            supportsHtml5Styles = ('hidden' in a);

            supportsUnknownElements = a.childNodes.length == 1 || (function() {
              // assign a false positive if unable to shiv
              (document.createElement)('a');
              var frag = document.createDocumentFragment();
              return (
                typeof frag.cloneNode == 'undefined' ||
                typeof frag.createDocumentFragment == 'undefined' ||
                typeof frag.createElement == 'undefined'
              );
            }());
          } catch(e) {
            // assign a false positive if detection fails => unable to shiv
            supportsHtml5Styles = true;
            supportsUnknownElements = true;
          }

        }());

        /*--------------------------------------------------------------------------*/

        /**
         * Creates a style sheet with the given CSS text and adds it to the document.
         * @private
         * @param {Document} ownerDocument The document.
         * @param {String} cssText The CSS text.
         * @returns {StyleSheet} The style element.
         */
        function addStyleSheet(ownerDocument, cssText) {
          var p = ownerDocument.createElement('p'),
          parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;

          p.innerHTML = 'x<style>' + cssText + '</style>';
          return parent.insertBefore(p.lastChild, parent.firstChild);
        }

        /**
         * Returns the value of `html5.elements` as an array.
         * @private
         * @returns {Array} An array of shived element node names.
         */
        function getElements() {
          var elements = html5.elements;
          return typeof elements == 'string' ? elements.split(' ') : elements;
        }

        /**
         * Returns the data associated to the given document
         * @private
         * @param {Document} ownerDocument The document.
         * @returns {Object} An object of data.
         */
        function getExpandoData(ownerDocument) {
          var data = expandoData[ownerDocument[expando]];
          if (!data) {
            data = {};
            expanID++;
            ownerDocument[expando] = expanID;
            expandoData[expanID] = data;
          }
          return data;
        }

        /**
         * returns a shived element for the given nodeName and document
         * @memberOf html5
         * @param {String} nodeName name of the element
         * @param {Document} ownerDocument The context document.
         * @returns {Object} The shived element.
         */
        function createElement(nodeName, ownerDocument, data){
          if (!ownerDocument) {
            ownerDocument = document;
          }
          if(supportsUnknownElements){
            return ownerDocument.createElement(nodeName);
          }
          if (!data) {
            data = getExpandoData(ownerDocument);
          }
          var node;

          if (data.cache[nodeName]) {
            node = data.cache[nodeName].cloneNode();
          } else if (saveClones.test(nodeName)) {
            node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
          } else {
            node = data.createElem(nodeName);
          }

          // Avoid adding some elements to fragments in IE < 9 because
          // * Attributes like `name` or `type` cannot be set/changed once an element
          //   is inserted into a document/fragment
          // * Link elements with `src` attributes that are inaccessible, as with
          //   a 403 response, will cause the tab/window to crash
          // * Script elements appended to fragments will execute when their `src`
          //   or `text` property is set
          return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node;
        }

        /**
         * returns a shived DocumentFragment for the given document
         * @memberOf html5
         * @param {Document} ownerDocument The context document.
         * @returns {Object} The shived DocumentFragment.
         */
        function createDocumentFragment(ownerDocument, data){
          if (!ownerDocument) {
            ownerDocument = document;
          }
          if(supportsUnknownElements){
            return ownerDocument.createDocumentFragment();
          }
          data = data || getExpandoData(ownerDocument);
          var clone = data.frag.cloneNode(),
          i = 0,
          elems = getElements(),
          l = elems.length;
          for(;i<l;i++){
            clone.createElement(elems[i]);
          }
          return clone;
        }

        /**
         * Shivs the `createElement` and `createDocumentFragment` methods of the document.
         * @private
         * @param {Document|DocumentFragment} ownerDocument The document.
         * @param {Object} data of the document.
         */
        function shivMethods(ownerDocument, data) {
          if (!data.cache) {
            data.cache = {};
            data.createElem = ownerDocument.createElement;
            data.createFrag = ownerDocument.createDocumentFragment;
            data.frag = data.createFrag();
          }


          ownerDocument.createElement = function(nodeName) {
            //abort shiv
            if (!html5.shivMethods) {
              return data.createElem(nodeName);
            }
            return createElement(nodeName, ownerDocument, data);
          };

          ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' +
                                                          'var n=f.cloneNode(),c=n.createElement;' +
                                                          'h.shivMethods&&(' +
                                                          // unroll the `createElement` calls
                                                          getElements().join().replace(/[\w\-]+/g, function(nodeName) {
            data.createElem(nodeName);
            data.frag.createElement(nodeName);
            return 'c("' + nodeName + '")';
          }) +
            ');return n}'
                                                         )(html5, data.frag);
        }

        /*--------------------------------------------------------------------------*/

        /**
         * Shivs the given document.
         * @memberOf html5
         * @param {Document} ownerDocument The document to shiv.
         * @returns {Document} The shived document.
         */
        function shivDocument(ownerDocument) {
          if (!ownerDocument) {
            ownerDocument = document;
          }
          var data = getExpandoData(ownerDocument);

          if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) {
            data.hasCSS = !!addStyleSheet(ownerDocument,
                                          // corrects block display not defined in IE6/7/8/9
                                          'article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}' +
                                            // adds styling not present in IE6/7/8/9
                                            'mark{background:#FF0;color:#000}' +
                                            // hides non-rendered elements
                                            'template{display:none}'
                                         );
          }
          if (!supportsUnknownElements) {
            shivMethods(ownerDocument, data);
          }
          return ownerDocument;
        }

        /*--------------------------------------------------------------------------*/

        /**
         * The `html5` object is exposed so that more elements can be shived and
         * existing shiving can be detected on iframes.
         * @type Object
         * @example
         *
         * // options can be changed before the script is included
         * html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false };
         */
        var html5 = {

          /**
           * An array or space separated string of node names of the elements to shiv.
           * @memberOf html5
           * @type Array|String
           */
          'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video',

          /**
           * current version of html5shiv
           */
          'version': version,

          /**
           * A flag to indicate that the HTML5 style sheet should be inserted.
           * @memberOf html5
           * @type Boolean
           */
          'shivCSS': (options.shivCSS !== false),

          /**
           * Is equal to true if a browser supports creating unknown/HTML5 elements
           * @memberOf html5
           * @type boolean
           */
          'supportsUnknownElements': supportsUnknownElements,

          /**
           * A flag to indicate that the document's `createElement` and `createDocumentFragment`
           * methods should be overwritten.
           * @memberOf html5
           * @type Boolean
           */
          'shivMethods': (options.shivMethods !== false),

          /**
           * A string to describe the type of `html5` object ("default" or "default print").
           * @memberOf html5
           * @type String
           */
          'type': 'default',

          // shivs the document according to the specified `html5` object options
          'shivDocument': shivDocument,

          //creates a shived element
          createElement: createElement,

          //creates a shived documentFragment
          createDocumentFragment: createDocumentFragment
        };

        /*--------------------------------------------------------------------------*/

        // expose html5
        window.html5 = html5;

        // shiv the document
        shivDocument(document);

    }(this, document));
    /*>>shiv*/

    // Assign private properties to the return object with prefix
    Modernizr._version      = version;

    // expose these for the plugin API. Look in the source for how to join() them against your input
    /*>>prefixes*/
    Modernizr._prefixes     = prefixes;
    /*>>prefixes*/
    /*>>domprefixes*/
    Modernizr._domPrefixes  = domPrefixes;
    Modernizr._cssomPrefixes  = cssomPrefixes;
    /*>>domprefixes*/

    /*>>mq*/
    // Modernizr.mq tests a given media query, live against the current state of the window
    // A few important notes:
    //   * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false
    //   * A max-width or orientation query will be evaluated against the current state, which may change later.
    //   * You must specify values. Eg. If you are testing support for the min-width media query use:
    //       Modernizr.mq('(min-width:0)')
    // usage:
    // Modernizr.mq('only screen and (max-width:768)')
    Modernizr.mq            = testMediaQuery;
    /*>>mq*/

    /*>>hasevent*/
    // Modernizr.hasEvent() detects support for a given event, with an optional element to test on
    // Modernizr.hasEvent('gesturestart', elem)
    Modernizr.hasEvent      = isEventSupported;
    /*>>hasevent*/

    /*>>testprop*/
    // Modernizr.testProp() investigates whether a given style property is recognized
    // Note that the property names must be provided in the camelCase variant.
    // Modernizr.testProp('pointerEvents')
    Modernizr.testProp      = function(prop){
        return testProps([prop]);
    };
    /*>>testprop*/

    /*>>testallprops*/
    // Modernizr.testAllProps() investigates whether a given style property,
    //   or any of its vendor-prefixed variants, is recognized
    // Note that the property names must be provided in the camelCase variant.
    // Modernizr.testAllProps('boxSizing')
    Modernizr.testAllProps  = testPropsAll;
    /*>>testallprops*/


    /*>>teststyles*/
    // Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards
    // Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... })
    Modernizr.testStyles    = injectElementWithStyles;
    /*>>teststyles*/


    /*>>prefixed*/
    // Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input
    // Modernizr.prefixed('boxSizing') // 'MozBoxSizing'

    // Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style.
    // Return values will also be the camelCase variant, if you need to translate that to hypenated style use:
    //
    //     str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-');

    // If you're trying to ascertain which transition end event to bind to, you might do something like...
    //
    //     var transEndEventNames = {
    //       'WebkitTransition' : 'webkitTransitionEnd',
    //       'MozTransition'    : 'transitionend',
    //       'OTransition'      : 'oTransitionEnd',
    //       'msTransition'     : 'MSTransitionEnd',
    //       'transition'       : 'transitionend'
    //     },
    //     transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];

    Modernizr.prefixed      = function(prop, obj, elem){
      if(!obj) {
        return testPropsAll(prop, 'pfx');
      } else {
        // Testing DOM property e.g. Modernizr.prefixed('requestAnimationFrame', window) // 'mozRequestAnimationFrame'
        return testPropsAll(prop, obj, elem);
      }
    };
    /*>>prefixed*/


    /*>>cssclasses*/
    // Remove "no-js" class from <html> element, if it exists:
    docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') +

                            // Add the new classes to the <html> element.
                            (enableClasses ? ' js ' + classes.join(' ') : '');
    /*>>cssclasses*/

    return Modernizr;

})(this, this.document);
;

/* Click analytics to be used in secure doc upload 
 * 
 * 
 */
var Site = window.Site || {};

$(document).ready(function () { 

    dataLayerPageLoad();

    $('a[href*="service.nylaarp"]').on('click', function (e) {
        e.preventDefault();
        dataLayerServiceClick();
        window.location = $(this).attr("href");
    });

    Site.Form.Analytics = (function () {
        var thisEventData;

        return {
            PushEvent: function (eventType) {
                for (var i = thisEventData.length - 1; i >= 0; i--) {
                    if (thisEventData[i].event === "State Completed")
                        return;
                }
                thisEventData.push({ event: eventType });
            },
            PushResult: function (eventType, name, step, getResult) {
                this.ClearFormInfoEvents();

                var result = getResult();
                var eventData =
                {
                    event: eventType,
                    form: {
                        progress: {
                            name: name,
                            step: step,
                            status: "form"
                        }
                    },
                    result
                };
                thisEventData.push(eventData);
                this.PushEvent("State Completed");
            },
            PushSuccess: function (eventType, name, step) {
                this.ClearFormInfoEvents();
               
                var eventData =
                {
                    event: eventType,
                    form: {
                        progress: {
                            name: name,
                            step: step,
                            status: "success"
                        }
                    }
                };
                thisEventData.push(eventData);
                this.PushEvent("State Completed");

            },
            TrackResult: function (obj, event, eventType, name, step, getResult) {
                var thisObj = this;

                obj.on(event, function () {
                    thisObj.ClearFormInfoEvents();
                    var result = getResult();
                    var eventData =
                    {
                        event: eventType,
                        form: {
                            progress: {
                                name: name,
                                step: step,
                                status: "form"
                            }
                        },
                        result
                    };
                    thisEventData.push(eventData);
                    thisObj.PushEvent("State Completed");
                });
            },
            TrackAttribute: function (obj, event, eventType, name, step, getAttributes) {
                var thisObj = this;

                obj.on(event, function () {
                    thisObj.ClearFormInfoEvents();
                    var attributes = getAttributes();
                    var eventData =
                    {
                        event: eventType,
                        form: {
                            progress: {
                                name: name,
                                step: step,
                                status: "form"
                            }
                        },
                        attributes
                    };
                    thisEventData.push(eventData);
                    thisObj.PushEvent("State Completed");

                });    
            },       
            ClearFormInfoEvents: function () {
                for (var i = thisEventData.length-1; i >= 0; i--) {
                    if (thisEventData[i].event === "Form Info" || thisEventData[i].event === "State Completed")
                        thisEventData.splice(i, 1);
                }
            },
            Initialize: function (appEventData) {
                thisEventData = appEventData;
                _log("Initialize Site.Form.Analytics ");
            }
        }
    })

});


function dataLayerPageLoad() {
    window.appEventData = window.appEventData || [];
    window.appEventData.push({
        "event": "State Initialized"
    });
    if (window.pageEventData) {
        if (window.userProductEventData) {
            window.pageEventData.userProduct = window.userProductEventData.userProduct;
        }
        window.appEventData.push(window.pageEventData);
    }
    if (window.formEventData) {
        if (Array.isArray(window.formEventData)) 
            for (var i = 0; i < window.formEventData.length; i++) 
                window.appEventData.push(window.formEventData[i]);
        else
            window.appEventData.push(window.formEventData);
    }

    if (event != null) {

        for (var i = window.appEventData.length - 1; i >= 0; i--) {
            if (window.appEventData[i].event === "Form Info" || window.appEventData[i].event === "State Completed")
                window.appEventData.splice(i, 1);
        }

        window.appEventData.push({
            "event": event.event,
            "form": event.form
        });

        window.appEventData.push({
           "event": "State Completed"
        });

    }
    else {
        window.appEventData.push({
            "event": "State Completed"
        });
    }

}


function dataLayerServiceClick() {    
    window.appEventData = window.appEventData || [];
    window.appEventData.push({
        "event": "Services Click"
    });
}






;
$(document).ready(function () {
	var header = document.getElementById("global_nav");

	if (header) {
		// Add slideDown animation to Bootstrap dropdown when expanding.
		$('.dropdown').on('show.bs.dropdown', function () {
			$(this).find('.dropdown-menu').first().stop(true, true).slideDown();
		});

		// Add slideUp animation to Bootstrap dropdown when collapsing.
		$('.dropdown').on('hide.bs.dropdown', function () {
			$(this).find('.dropdown-menu').first().stop(true, true).slideUp();
		});

		// When the user scrolls the page, execute myFunction
		window.onscroll = function () { myFunction() };

		// Get the offset position of the navbar
		var sticky = header.offsetTop;

		// Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
		function myFunction() {
			if (window.pageYOffset > sticky) {
				header.classList.add("sticky");
			} else {
				header.classList.remove("sticky");
			}
		}
	}
    // then add below javascript code 
    var menuButtonNav = document.getElementById("menu-button");
    if (menuButtonNav) {
        var iconNav = menuButtonNav.getElementsByClassName("fas")[0];
        var navbarTogglerIcon = menuButtonNav.getElementsByClassName("navbar-toggler-icon")[0];
        var observer = new MutationObserver(function (mutations) {
            mutations.forEach(function (mutation) {
                //console.log("mutation.type === 'attributes'", mutation.type === "attributes")
                if (mutation.type === "attributes") {
                    if (mutation.target.ariaExpanded === 'false') {
                        iconNav.classList.add('fa-bars');
                        iconNav.classList.remove('fa-times');
                        iconNav.classList.remove('sticky-button');
                        navbarTogglerIcon.classList.remove('relative-span');
                    } else {
                        iconNav.classList.add('sticky-button');
                        iconNav.classList.add('fa-times');
                        iconNav.classList.remove('fa-bars');
                        navbarTogglerIcon.classList.add('relative-span');
                    }
                }
            });
        });

        observer.observe(menuButtonNav, { attributes: true, attributeFilter: ['aria-expanded'] });
    }
   

});
;
$(document).ready(function () {
    if (typeof Cludo !== 'undefined') {
        var CludoSearch;
        (function () {
            var cludoSettings = {
                customerId: 10000873,
                engineId: 10001324,
                language: 'en',
                searchInputs: ['searchInputs'],
                type: 'standardOverlay'
            };
            CludoSearch = new Cludo(cludoSettings);
            CludoSearch.init();
        })();
    }

    var commonSearchesLink = document.querySelectorAll(".common-searches a");
    var i;
    for (i = 0; i < commonSearchesLink.length; i++) {
        var link = commonSearchesLink[i];
        link.addEventListener('click', function (event) {
            var searchText = this.innerHTML;
            document.getElementById("searchInputs").value = searchText;
            document.getElementById("searchInputs").dispatchEvent(new Event('input'));
            document.getElementById("search-button").click();
            event.preventDefault();
            event.stopPropagation();
            return false;
        });
    }
});;


function getCookie(cname) {
    const name = cname + "=";
    const decodedCookie = decodeURIComponent(document.cookie);
    const ca = decodedCookie.split(";");
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === " ") {
            c = c.substring(1);
        }
        if (c.indexOf(name) === 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}


function getUrlParameter(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    const regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
    const results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function updateUrlParameter(uri, key, value) {
    // remove the hash part before operating on the uri
    const i = uri.indexOf("#");
    const hash = i === -1 ? "" : uri.substr(i);
    uri = i === -1 ? uri : uri.substr(0, i);

    const re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
    const separator = uri.indexOf("?") !== -1 ? "&" : "?";
    if (uri.match(re)) {
        uri = uri.replace(re, "$1" + key + "=" + value + "$2");
    } else {
        uri = uri + separator + key + "=" + value;
    }
    return uri + hash;  // finally append the hash as well
};
$(document).ready(function () {
    $('a[href*="#"]')
        .not('[href="#"]')
        .not('[href="#0"]')
        .click(function (event) {
            if (
                location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') &&
                    location.hostname == this.hostname
            ) {
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                if (target.length) {
                    event.preventDefault();
                    $('html, body').animate({
                            scrollTop: target.offset().top - 100
                        },
                        1000,
                        function () {
                            var $target = $(target);
                            $target.focus();
                            if ($target.is(":focus")) {
                                return false;
                            } else {
                                $target.attr('tabindex', '-1');
                                $target.focus();
                            }
                            return false;
                        });
                }
            }
        });
});
;
var Site = window.Site || {};
(function ($) {
    Site.Session = (function () {
        return {
            SaveTreatmentCode: function (treatmentCode) {
                $.post('/webservices/Session.svc/SaveTreatmentCode?treatmentCode=' + treatmentCode);
                if (typeof console != 'undefined') {
                    console.log(treatmentCode);
                }
                $("#treatment-code").text($("#treatment-code").text() + "," + treatmentCode);
            },
            GetTreatmentCode: function () {
                $.get('/webservices/Session.svc/GetTreatmentCode', function (data) {
                    if (typeof console != 'undefined') {
                        console.log(data);
                    }
                    return data;
                });
            },
            SaveAdobeVisitorId: function () {
                var id = s.visitor.getMarketingCloudVisitorID();
                $.post('/webservices/Session.svc/SaveAdobeVisitorId?adobeVisitorId=' + id);
                if (typeof console != 'undefined') {
                    console.log(id);
                }
            },
            GetAdobeVisitorId: function () {
                $.get('/webservices/Session.svc/GetAdobeVisitorId', function (data) {
                    if (typeof console != 'undefined') {
                        console.log(data);
                    }
                    return data;
                });
            }

        };
    })();
})(jQuery);;
function cdnFallbackForCss(cdnPath, fallback, className, ruleName, ruleValue) {
    var len = document.styleSheets.length;
    for (var i = 0; i < len; i++) {
        var sheet = document.styleSheets[i];
        if (sheet && sheet.href && sheet.href.indexOf(cdnPath) !== -1) {
            var meta = document.createElement('meta');
            meta.className = className;
            document.head.appendChild(meta);
            var value = window.getComputedStyle(meta).getPropertyValue(ruleName);
            document.head.removeChild(meta);
            if (value !== ruleValue) {
                document.write('<link href="' + fallback + '" rel="stylesheet" type="text/css" />');
            }
        }
    }    
};;
var Site = window.Site || {};

function _log(s) {
    if (_debug && /chrom(e|ium)/.test(navigator.userAgent.toLowerCase()))
        console.log(s);
}

(function($) {
    Site.Customer = (function() {

        return {
            AutoLogout: function() {
                let keepAlive = 0;
                
                var interval = setInterval(function () {
                    keepAlive++;
                    _log("Keep alive @ " + keepAlive);
                    if (keepAlive >= SESSION_DURATION_MINS) {

                        // clear interval otherwise it keeps firing.
                        clearInterval(interval);

                        document.location.href = RELEXIVE_SESSION === 'True' ? REFLEXIVE_LOGIN  :
                            (SECUREDOC_SESSION === 'True' && $('#LightVerificationPathway').val() === 'True')
                                ? SECUREDOC_LIGHTVERIFICATION_LOGIN : '/Account/Logout';

                    }
                       
                    if (keepAlive >= (SESSION_DURATION_MINS - TIMEOUT_WARNING_MINS)) {
                        _log("Showing modal. Session=" + SESSION_DURATION_MINS + ", TimeoutWarning=" + TIMEOUT_WARNING_MINS);
                        $('#csAutoLogout').modal({ show: true });
                    }
                }, 60 * 1000);

                jQuery(document).on('mousemove keydown click scroll', function () { keepAlive = 0; });
            },

            PolicyLink: function (loc) {
                let cpol = getUrlParameter("cpol");
                if (cpol === "")
                    cpol = "0";

                document.location.href = loc + "?cpol=" + encodeURIComponent(cpol);
            }
        };

    })();
})(jQuery);
;
/*
	Watermark v3.2.0 (August 16, 2014) plugin for jQuery
	http://jquery-watermark.googlecode.com/
	Copyright (c) 2009-2014 Todd Northrop
	http://www.speednet.biz/
	Dual licensed under the MIT or GPL Version 2 licenses.
*/
(function (n, t, i) { var o = "watermark", e = "watermarkClass", v = "watermarkFocus", s = "watermarkSubmit", h = "watermarkMaxLength", f = "watermarkPassword", r = "watermarkText", u = /\r/g, p = /^(button|checkbox|hidden|image|radio|range|reset|submit)$/i, y = "input:data(" + o + "),textarea:data(" + o + ")", l = ":watermarkable", a = ["Page_ClientValidate"], c = !1, w = "placeholder" in document.createElement("input"); n.watermark = n.watermark || { version: "3.2.0", runOnce: !0, options: { className: "watermark", clearAllFormsOnSubmit: !1, hideBeforeUnload: !0, textAttr: "", useNative: !0 }, hide: function (t) { n(t).filter(y).each(function () { n.watermark._hide(n(this)) }) }, _hide: function (n, i) { var c = n[0], y = (c.value || "").replace(u, ""), l = n.data(r) || "", a = n.data(h) || 0, v = n.data(e), o, s; l.length && y == l && (c.value = "", n.data(f) && (n.attr("type") || "") === "text" && (o = n.data(f) || [], s = n.parent() || [], o.length && s.length && (s[0].removeChild(n[0]), s[0].appendChild(o[0]), n = o)), a && (n.attr("maxLength", a), n.removeData(h)), i && (n.attr("autocomplete", "off"), t.setTimeout(function () { n.select() }, 1))), v && n.removeClass(v) }, show: function (t) { n(t).filter(y).each(function () { n.watermark._show(n(this)) }) }, _show: function (t) { var a = t[0], p = (a.value || "").replace(u, ""), i = t.data(r) || "", y = t.attr("type") || "", w = t.data(e), o, s, l; p.length != 0 && p != i || t.data(v) ? n.watermark._hide(t) : (c = !0, t.data(f) && y === "password" && (o = t.data(f) || [], s = t.parent() || [], o.length && s.length && (s[0].removeChild(t[0]), s[0].appendChild(o[0]), t = o, t.attr("maxLength", i.length), a = t[0])), (y === "text" || y === "search") && (l = t.attr("maxLength") || 0, l > 0 && i.length > l && (t.data(h, l), t.attr("maxLength", i.length))), w && t.addClass(w), a.value = i) }, hideAll: function (t) { c && (n.watermark.hide(n(l, t)), c = !1) }, showAll: function () { n.watermark.show(l) } }, n.fn.watermark = n.fn.watermark || function (i, h) { if (!this.length) return this; var a = !1, c = typeof i == "string"; return c && (i = i.replace(u, "")), typeof h == "object" ? (a = typeof h.className == "string", h = n.extend({}, n.watermark.options, h)) : typeof h == "string" ? (a = !0, h = n.extend({}, n.watermark.options, { className: h })) : typeof i == "object" ? (h = n.extend({}, n.watermark.options, i), i = "") : h = n.watermark.options, typeof h.useNative != "function" && (h.useNative = h.useNative ? function () { return !0 } : function () { return !1 }), this.each(function () { var y = n(this), d, p, b, k; if (y.is(l)) { if (h.textAttr && (i = (y.attr(h.textAttr) || "").replace(u, ""), c = !!i), y.data(o)) (c || a) && (n.watermark._hide(y), c && y.data(r, i), a && y.data(e, h.className)); else { if (w && h.useNative.call(this, y) && (y.attr("tagName") || "") !== "TEXTAREA") { c && h.textAttr !== "placeholder" && y.attr("placeholder", i); return } y.data(r, c ? i : ""), y.data(e, h.className), y.data(o, 1), (y.attr("type") || "") === "password" ? (d = y.wrap("<span>").parent(), p = n(d.html().replace(/type=["']?password["']?/i, 'type="text"')), p.data(r, y.data(r)), p.data(e, y.data(e)), p.data(o, 1), p.attr("maxLength", i.length), p.focus(function () { n.watermark._hide(p, !0) }).bind("dragenter", function () { n.watermark._hide(p) }).bind("dragend", function () { t.setTimeout(function () { p.blur() }, 1) }), y.blur(function () { n.watermark._show(y) }).bind("dragleave", function () { n.watermark._show(y) }), p.data(f, y), y.data(f, p)) : y.focus(function () { y.data(v, 1), n.watermark._hide(y, !0) }).blur(function () { y.data(v, 0), n.watermark._show(y) }).bind("dragenter", function () { n.watermark._hide(y) }).bind("dragleave", function () { n.watermark._show(y) }).bind("dragend", function () { t.setTimeout(function () { n.watermark._show(y) }, 1) }).bind("drop", function (n) { var t = y[0], i = n.originalEvent.dataTransfer.getData("Text"); (t.value || "").replace(u, "").replace(i, "") === y.data(r) && (t.value = i), y.focus() }), this.form && (b = this.form, k = n(b), k.data(s) || (k.submit(function () { return n.watermark.hideAll.apply(this, h.clearAllFormsOnSubmit ? [] : [b]) }), b.submit ? (k.data(s, b.submit), b.submit = function (t, i) { return function () { var r = i.data(s); n.watermark.hideAll(h.clearAllFormsOnSubmit ? null : t), r.apply ? r.apply(t, Array.prototype.slice.call(arguments)) : r() } }(b, k)) : (k.data(s, 1), b.submit = function (t) { return function () { n.watermark.hideAll(h.clearAllFormsOnSubmit ? null : t), delete t.submit, t.submit() } }(b)))) } n.watermark._show(y) } }) }, n.watermark.runOnce && (n.watermark.runOnce = !1, n.extend(n.expr[":"], { data: n.expr.createPseudo ? n.expr.createPseudo(function (t) { return function (i) { return !!n.data(i, t) } }) : function (t, i, r) { return !!n.data(t, r[3]) }, watermarkable: function (n) { var t, i = n.nodeName; return i === "TEXTAREA" ? !0 : i !== "INPUT" ? !1 : (t = n.getAttribute("type"), !t || !p.test(t)) } }), function (t) { n.fn.val = function () { var f = Array.prototype.slice.call(arguments), e; return this.length ? f.length ? (t.apply(this, f), n.watermark.show(this), this) : this.data(o) ? (e = (this[0].value || "").replace(u, ""), e === (this.data(r) || "") ? "" : e) : t.apply(this) : f.length ? this : i } }(n.fn.val), a.length && n(function () { for (var r, u, i = a.length - 1; i >= 0; i--) r = a[i], u = t[r], typeof u == "function" && (t[r] = function (t) { return function () { return n.watermark.hideAll(), t.apply(null, Array.prototype.slice.call(arguments)) } }(u)) }), n(t).bind("beforeunload", function () { n.watermark.options.hideBeforeUnload && n.watermark.hideAll() })) })(jQuery, window);;
/**
 * Autotab - jQuery plugin 1.9.2
 * https://github.com/Mathachew/jquery-autotab
 * 
 * Copyright (c) 2008, 2015 Matthew Miller
 * 
 * Licensed under the MIT licensing:
 *   http://www.opensource.org/licenses/mit-license.php
 */

(function(d){var u=navigator.platform,g=null,r="iPad"===u||"iPhone"===u||"iPod"===u,w="undefined"!==typeof InstallTrigger,x=!window.ActiveXObject&&"ActiveXObject"in window,h=function(a,f){if(null!==f&&"undefined"!==typeof f)for(var b in f)d(a).data("autotab-"+b,f[b])},l=function(a){var f={arrowKey:!1,format:"all",loaded:!1,disabled:!1,pattern:null,uppercase:!1,lowercase:!1,nospace:!1,maxlength:2147483647,target:null,previous:null,trigger:null,originalValue:"",changed:!1,editable:"text"===a.type||
"password"===a.type||"textarea"===a.type||"tel"===a.type||"number"===a.type||"email"===a.type||"search"===a.type||"url"===a.type,filterable:"text"===a.type||"password"===a.type||"textarea"===a.type,tabOnSelect:!1};if(!0===d.autotab.selectFilterByClass&&"undefined"===typeof d(a).data("autotab-format")){var b="all text alpha number numeric alphanumeric hex hexadecimal custom".split(" "),e;for(e in b)if(d(a).hasClass(b[e])){f.format=b[e];break}}for(e in f)"undefined"!==typeof d(a).data("autotab-"+e)&&
(f[e]=d(a).data("autotab-"+e));f.loaded||(null!==f.trigger&&"string"===typeof f.trigger&&(f.trigger=f.trigger.toString()),h(a,f));return f},p=function(a){return"undefined"!==typeof a&&("string"===typeof a||!(a instanceof jQuery))},y=function(a){var d=0,b=0,e=0;if("text"===a.type||"password"===a.type||"textarea"===a.type)"number"===typeof a.selectionStart&&"number"===typeof a.selectionEnd?(d=a.selectionStart,b=a.selectionEnd,e=1):document.selection&&document.selection.createRange&&(b=document.selection.createRange(),
d=a.createTextRange(),a=a.createTextRange(),e=b.getBookmark(),d.moveToBookmark(e),a.setEndPoint("EndToStart",d),d=a.text.length,b=d+b.text.length,e=2);return{start:d,end:b,selectionType:e}};d.autotab=function(a){"object"!==typeof a&&(a={});d(":input").autotab(a)};d.autotab.selectFilterByClass=!1;d.autotab.next=function(){var a=d(document.activeElement);a.length&&a.trigger("autotab-next")};d.autotab.previous=function(){var a=d(document.activeElement);a.length&&a.trigger("autotab-previous")};d.autotab.remove=
function(a){p(a)?d(a).autotab("remove"):d(":input").autotab("remove")};d.autotab.restore=function(a){p(a)?d(a).autotab("restore"):d(":input").autotab("restore")};d.autotab.refresh=function(a){p(a)?d(a).autotab("refresh"):d(":input").autotab("refresh")};d.fn.autotab=function(a,f){if(!this.length)return this;var b=d.grep(this,function(a,c){return"hidden"!=a.type});if("filter"==a){if("string"===typeof f||"function"===typeof f)f={format:f};for(var e=0,m=b.length;e<m;e++){var c=l(b[e]),k=f;k.target=c.target;
k.previous=c.previous;d.extend(c,k);c.loaded?h(b[e],c):(c.disabled=!0,t(b[e],k))}}else if("remove"==a||"destroy"==a||"disable"==a)for(e=0,m=b.length;e<m;e++)c=l(b[e]),c.disabled=!0,h(b[e],c);else if("restore"==a||"enable"==a)for(e=0,m=b.length;e<m;e++)c=l(b[e]),c.disabled=!1,h(b[e],c);else if("refresh"==a)for(e=0,m=b.length;e<m;e++){var c=l(b[e]),n=e+1,q=e-1,k=function(){c.target=0<e&&n<m?b[n]:0<e?null:b[n]},g=function(){c.previous=0<e&&n<m?b[q]:0<e?b[q]:null};if(null===c.target||""===c.target.selector)k();
else if("string"===typeof c.target||c.target.selector)c.target=d("string"===typeof c.target?c.target:c.target.selector),0===c.target.length&&k();if(null===c.previous||""===c.previous.selector)g();else if("string"===typeof c.previous||c.previous.selector)c.previous=d("string"===typeof c.previous?c.previous:c.previous.selector),0===c.previous.length&&g();c.loaded?(p(c.target)&&(c.target=d(c.target)),p(c.previous)&&(c.previous=d(c.previous)),h(b[e],c)):t(b[e],c)}else if(null===a||"undefined"===typeof a?
f={}:"string"===typeof a||"function"===typeof a?f={format:a}:"object"===typeof a&&(f=a),1<b.length)for(e=0,m=b.length;e<m;e++)n=e+1,q=e-1,k=f,0<e&&n<m?(k.target=b[n],k.previous=b[q]):0<e?(k.target=null,k.previous=b[q]):(k.target=b[n],k.previous=null),t(b[e],k);else t(b[0],f);return this};var v=function(a,d,b){if("function"===typeof b.format)return b.format(d,a);a=null;switch(b.format){case "text":a=RegExp("[0-9]+","g");break;case "alpha":a=RegExp("[^a-zA-Z]+","g");break;case "number":case "numeric":a=
RegExp("[^0-9]+","g");break;case "alphanumeric":a=RegExp("[^0-9a-zA-Z]+","g");break;case "hex":case "hexadecimal":a=RegExp("[^0-9A-Fa-f]+","g");break;case "custom":a=new RegExp(b.pattern,"g")}null!==a&&(d=d.replace(a,""));b.nospace&&(a=RegExp("[ ]+","g"),d=d.replace(a,""));b.uppercase&&(d=d.toUpperCase());b.lowercase&&(d=d.toLowerCase());return d},t=function(a,f){var b=l(a);b.disabled&&(b.disabled=!1,b.target=null,b.previous=null);d.extend(b,f);p(b.target)&&(b.target=d(b.target));p(b.previous)&&(b.previous=
d(b.previous));var e=a.maxLength;"undefined"===typeof a.maxLength&&"textarea"==a.type&&(e=a.maxLength=a.getAttribute("maxlength"));2147483647==b.maxlength&&2147483647!=e&&-1!=e?b.maxlength=e:0<b.maxlength?a.maxLength=b.maxlength:b.target=null;if(b.loaded)h(a,b);else{b.loaded=!0;h(a,b);if("select-one"==a.type)d(a).on("change",function(a){l(this).tabOnSelect&&d(this).trigger("autotab-next")});d(a).on("autotab-next",function(a,c){var d=this;setTimeout(function(){c||(c=l(d));var a=c.target;c.disabled||
!a.length||r||(a.prop("disabled")||a.prop("readonly")?a.trigger("autotab-next"):c.arrowKey?a.focus():a.focus().select(),g=new Date)},1)}).on("autotab-previous",function(a,c){var d=this;setTimeout(function(){c||(c=l(d));var a=c.previous;if(!c.disabled&&a.length){var b=a.val();a.prop("disabled")||a.prop("readonly")?a.trigger("autotab-previous"):b.length&&a.data("autotab-editable")&&!c.arrowKey?(x?a.val(b.substring(0,b.length-1)).focus():a.focus().val(b.substring(0,b.length-1)),h(a,{changed:!0})):(c.arrowKey&&
h(this,{arrowKey:!1}),x?a.val(b).focus():a.focus().val(b));g=null}},1)}).on("focus",function(){h(this,{originalValue:this.value})}).on("blur",function(){var a=l(this);a.changed&&this.value!=a.originalValue&&(h(this,{changed:!1}),d(this).change())}).on("keydown.autotab",function(a){var c=l(this);if(!c||c.disabled)return!0;var b=y(this),e=a.which||a.charCode;if(8==e){c.arrowKey=!1;if(!c.editable)return d(this).trigger("autotab-previous",c),!1;h(this,{changed:this.value!==c.originalValue});0===this.value.length&&
d(this).trigger("autotab-previous",c)}else if(9==e&&null!==g)if(a.shiftKey)g=null;else{if(800>(new Date).getTime()-g.getTime())return g=null,!1}else"range"!==this.type&&"select-one"!==this.type&&"select-multiple"!==this.type&&("tel"!==this.type&&"number"!==this.type||("tel"===this.type||"number"===this.type)&&0==this.value.length)&&(37!=e||c.editable&&0!=b.start?39!=e||c.editable&&c.filterable&&b.end!=this.value.length&&0!=this.value.length||(c.arrowKey=!0,d(this).trigger("autotab-next",c)):(c.arrowKey=
!0,d(this).trigger("autotab-previous",c)))}).on("keypress.autotab",function(a){var c=l(this),b=a.which||a.keyCode;if(!c||c.disabled||w&&0===a.charCode||a.ctrlKey||a.altKey||13==b||this.disabled)return!0;a=String.fromCharCode(b);if("text"!=this.type&&"password"!=this.type&&"textarea"!=this.type)return this.value.length+1>=c.maxlength&&(c.arrowKey=!1,d(this).trigger("autotab-next",c)),this.value.length!=c.maxlength;if(null!==c.trigger&&0<=c.trigger.indexOf(a))return null!==g&&800>(new Date).getTime()-
g.getTime()?g=null:(c.arrowKey=!1,d(this).trigger("autotab-next",c)),!1;g=null;b=document.selection&&document.selection.createRange?!0:0<b;a=v(this,a,c);if(b&&(null===a||""===a))return!1;if(b&&this.value.length<=this.maxLength){b=y(this);if(0===b.start&&b.end==this.value.length)this.value=a;else{if(this.value.length==this.maxLength&&b.start===b.end)return c.arrowKey=!1,d(this).trigger("autotab-next",c),!1;this.value=this.value.slice(0,b.start)+a+this.value.slice(b.end)}h(this,{changed:this.value!=
c.originalValue});this.value.length!=c.maxlength&&(b.start++,1==b.selectionType?this.selectionStart=this.selectionEnd=b.start:2==b.selectionType&&(a=this.createTextRange(),a.collapse(!0),a.moveEnd("character",b.start),a.moveStart("character",b.start),a.select()))}this.value.length==c.maxlength&&(c.arrowKey=!1,d(this).trigger("autotab-next",c));return!1}).on("drop paste",function(a){var b=l(this);if(!b)return!0;this.maxLength=2147483647;(function(a,e){setTimeout(function(){var f=-1,g=document.createElement("input");
g.type="hidden";g.value=a.value.toLowerCase();g.originalValue=a.value;a.value=v(a,a.value,e).substr(0,e.maxlength);var h=function(a,b){if(a){var c=l(a);if(d(a).prop("disabled")||d(a).prop("readonly")||!c.editable)d(a).trigger("autotab-next"),r||h(c.target[0],b);else{for(var e=0,k=b.length;e<k;e++)f=g.value.indexOf(b.charAt(e).toLowerCase(),f)+1;e=g.originalValue.substr(f);if(e=v(a,e,c).substr(0,c.maxlength))a.value=e,e.length==c.maxlength&&(c.arrowKey=!1,d(a).trigger("autotab-next",c),w&&setTimeout(function(){a.selectionStart=
a.value.length},1),r||h(c.target[0],e))}}};a.value.length==e.maxlength&&(b.arrowKey=!1,d(a).trigger("autotab-next",b),r||h(e.target[0],a.value.toLowerCase()));a.maxLength=e.maxlength},1)})(this,b)})}};d.fn.autotab_magic=function(a){return d(this).autotab()};d.fn.autotab_filter=function(a){var f={};"string"===typeof a||"function"===typeof a?f.format=a:d.extend(f,a);return d(this).autotab("filter",f)}})(jQuery);
;
!function (t) { "use strict"; if ("function" == typeof define && define.amd) define(["jquery"], t); else if ("object" == typeof exports) t(require("jquery")); else { if ("undefined" == typeof jQuery) throw "jquery-numerator requires jQuery to be loaded first"; t(jQuery) } }(function (t) { var e = "numerator", i = { easing: "swing", duration: 500, delimiter: void 0, rounding: 0, toValue: void 0, fromValue: void 0, queue: !1, onStart: function () { }, onStep: function () { }, onProgress: function () { }, onComplete: function () { } }; function n(n, s) { this.element = n, this.settings = t.extend({}, i, s), this._defaults = i, this._name = e, this.init() } n.prototype = { init: function () { this.parseElement(), this.setValue() }, parseElement: function () { var e = t.trim(t(this.element).text()); this.settings.fromValue = this.settings.fromValue || this.format(e) }, setValue: function () { var e = this; t({ value: e.settings.fromValue }).animate({ value: e.settings.toValue }, { duration: parseInt(e.settings.duration, 10), easing: e.settings.easing, start: e.settings.onStart, step: function (i, n) { t(e.element).text(e.format(i)), e.settings.onStep(i, n) }, progress: e.settings.onProgress, complete: e.settings.onComplete }) }, format: function (t) { return t = parseInt(this.settings.rounding) < 1 ? parseInt(t, 10) : parseFloat(t).toFixed(parseInt(this.settings.rounding)), this.settings.delimiter ? this.delimit(t) : t }, delimit: function (t) { if (t = t.toString(), this.settings.rounding && parseInt(this.settings.rounding, 10) > 0) { var e = t.substring(t.length - (this.settings.rounding + 1), t.length), i = t.substring(0, t.length - (this.settings.rounding + 1)); return this.addDelimiter(i) + e } return this.addDelimiter(t) }, addDelimiter: function (t) { return t.toString().replace(/\B(?=(\d{3})+(?!\d))/g, this.settings.delimiter) } }, t.fn[e] = function (i) { return this.each(function () { t.data(this, "plugin_" + e) && t.data(this, "plugin_" + e, null), t.data(this, "plugin_" + e, new n(this, i)) }) } });;
var Site = window.Site || {};
var _debug = !/^www/.test($(location).attr('hostname'));

var inputSelector = '[data-val=true]';
var inputValidationErrorClass = 'input-validation-error';
var validationMessageSelector = 'span[class^="field-validation-"]';

function getValidationMessageElement($inputElement) {
    /// <summary>Gets the message element for the specified input element.</summary>
    /// <param name="$inputElement" type="">A jQuery object representing the input element,</param>
    /// <returns type=""></returns>
    var message = $inputElement.closest('form').find(validationMessageSelector + '[data-valmsg-for="' + $inputElement.attr('name') + '"]');
    return message;
};

function getAge(year, month, day) {
    var dob = new Date(year, month - 1, day);
    var currentTime = new Date().getTime();
    var ageDifMs = currentTime - dob.getTime();
    var ageDate = new Date(ageDifMs); // miliseconds from epoch
    return Math.abs(ageDate.getUTCFullYear() - 1970).toString();
}

function getProspectAge() {
    var month = $("[name='BirthMonth']").val();
    var day = $("[name='BirthDay']").val();
    var year = $("[name='BirthYear']").val();
    if (!(month && day && year))
        return 0;
    return getAge(year, month, day);
}




(function ($) {
    Site.Form = function () {
        var onSubmitFunction;
        var options;
        var thisObj;

        $.validator.setDefaults({
            highlight: function (element, errorClass, validClass) {
                if (element.type === "radio") {
                    this.findByName(element.name).addClass(errorClass).removeClass(validClass);
                } else {
                    $(element).addClass(errorClass).removeClass(validClass);
                }
                if ($(element).is("input[type='radio']") || $(element).is("input[type='checkbox']")) {

                    var parent = $(element).parent();

                    if (parent.hasClass("custom-control"))
                        parent = parent.parent();

                    // Account for responsive structure used on radios/checkboxes
                    if (parent.is("label")) {
                        parent.parent().addClass("error-container");
                    } else {
                        parent.addClass("error-container");
                    }
                }
            },
            unhighlight: function (element, errorClass, validClass) {
                $(element).parent().removeClass("error-container");
                $(element).parent().parent().removeClass("error-container");
                if (element.type === "radio") {
                    this.findByName(element.name).removeClass(errorClass).addClass(validClass);
                } else {
                    $(element).removeClass(errorClass).addClass(validClass);
                }
            }
        });

        $.validator.addMethod('requiredif', function (value, element, parameters) {
            var desiredvalues = parameters.desiredvalue.split("|");
            for (var i = 0, l = desiredvalues.length; i < l; i++) {
                desiredvalue = (desiredvalues[i] == null ? '' : desiredvalues[i]).toString();
                var controlType = $(":input[name$='" + parameters.dependentproperty + "']").attr("type");
                var actualvalue = {}
                if (controlType == "checkbox" || controlType == "radio") {
                    var control = $("input[name$='" + parameters.dependentproperty + "']:checked");
                    actualvalue = control.val();
                } else {
                    actualvalue = $("#" + parameters.dependentproperty).val();
                }
                if ($.trim(desiredvalue).toLowerCase() === $.trim(actualvalue).toLocaleLowerCase()) {
                    var isValid = $.validator.methods.required.call(this, value, element, parameters);
                    return isValid;
                }
            }
            return true;
        });
        $.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'desiredvalue'], function (options) {
            options.rules['requiredif'] = options.params;
            options.messages['requiredif'] = options.message;
        });

        jQuery.validator.addMethod("onecheckboxrequired", function (value, element) {
            _log(">> checkbox Required Field Validator");
            if ($('.multiChoice:checkbox:checked').length < 1) {
                //input-validation-error
                $('.multiChoice:checkbox').addClass('input-validation-error');
                $('.field-validation-error').show();
                return false;
            } else {
                $('.multiChoice:checkbox').removeClass('input-validation-error');
                $('.field-validation-error').hide();

            }
            return true;
        });
        jQuery.validator.unobtrusive.adapters.add("onecheckboxrequired", [], function (options) {
            options.rules["onecheckboxrequired"] = options.params;
            options.messages["onecheckboxrequired"] = options.message;
        });



        // aarp number validation
        jQuery.validator.addMethod("validateaarpnumber", function (value, element, params) {
            var aarpMember = $("input[name='AarpMember']:checked").val();
            if (!aarpMember || (aarpMember.length > 0 && aarpMember == 'N')) {
                return true;
            }
            return isValidAarpNumber(value);
        });
        jQuery.validator.unobtrusive.adapters.add("validateaarpnumber", [], function (options) {
            options.rules["validateaarpnumber"] = options.params;
            options.messages["validateaarpnumber"] = options.message;

        });
        jQuery.validator.addMethod("numericonly", function (value, element, params) {
            if (jQuery.trim(value).length > 0) {
                if (jQuery.trim(value) === "" || !jQuery.isNumeric(value) || (value % 1 != 0))
                    return false;
                else
                    return true;
            } else
                return true;

        });
        jQuery.validator.unobtrusive.adapters.add("numericonly", [], function (options) {
            options.rules["numericonly"] = options.params;
            options.messages["numericonly"] = options.message;

        });

        function isValidAarpNumber(input) {
            if (!input || input.length < 9)
                return false;
            const aarpNum = input.padStart(10, "0");
            const aarpNumArr = Array.from(aarpNum);
            const firstIndices = [0, 2, 4, 6, 8];
            const secondIndices = [1, 3, 5, 7];
            var firstHalf = "";
            for (i = 0; i < firstIndices.length; i++) {
                firstHalf += aarpNumArr[firstIndices[i]];
            }
            console.log('First Half:' + firstHalf);
            const sumDigits = Array.from((parseInt(firstHalf) * 2).toString());
            let checkSum = 0;
            // add the first digits
            for (i = 0; i < sumDigits.length; i++) {
                checkSum += parseInt(sumDigits[i]);
            }
            for (i = 0; i < secondIndices.length; i++) {
                checkSum += parseInt(aarpNumArr[secondIndices[i]]);
            }
            _log('Sumof digits:' + sumDigits);
            _log('Checksum:' + checkSum);
            const lastDigitOfCheckSum = Array.from(checkSum.toString())[1];
            _log('lastDigitOfCheckSum:' + lastDigitOfCheckSum);
            const minusFromTen = Array.from((10 - parseInt(lastDigitOfCheckSum)).toString().padStart(2, 0))[1];
            _log('minusFromTen:' + minusFromTen);
            _log("10th digit of aarp number:" + aarpNumArr[9]);
            return minusFromTen === aarpNumArr[9];
        }
        return {
            Initialize: function (formSelector) {
                _log(">> Base initialization on form: " + formSelector);
                if (typeof (formSelector) === "undefined") {
                    formSelector = 'form';
                }

                if (arguments.length > 1) {
                    options = arguments[1];
                }

                thisObj = this;

                $('input[data-val-mask]:not([type=hidden])', formSelector).each(function () {
                    $(this).mask($(this).attr('data-val-mask'));
                });
             
                $('input[data-val-watermark]', formSelector).each(function () {
                    $(this).watermark($(this).attr('data-val-watermark'));
                });
                $('select[data-val-watermark]', formSelector).each(function () {
                    var foundSelectedItem = false;
                    var emptyValueItemExists = false;

                    // looping through options to find selected attributes with 
                    // DOM js, because jquery creates a false positive
                    var selectItemId = $(this).attr('id');

                    var selectItemOpts = $(this)[0].options;
                    if (typeof (selectItemOpts) !== "undefined") {
                        for (var i = 0; i < selectItemOpts.length; i++) {
                            if (selectItemOpts[i].hasAttribute('selected')) {
                                foundSelectedItem = true;
                            }
                            if (selectItemOpts[i].value === "" || selectItemOpts[i].value === 'undefined') {
                                emptyValueItemExists = true;
                            }
                        }
                        if (!emptyValueItemExists) {
                            var opt = jQuery("<option value=''>");
                            var selectText = $(this).attr('data-val-watermark');
                            opt.text(selectText);
                            $(this).prepend(opt);
                        }
                        if (!foundSelectedItem) {
                            selectItemOpts.selectedIndex = 0;
                        }
                    }
                });

                $("input[data-val-togglepassword]").each(function () {

                    if ($(this).hasClass("toggle-password") || $(this).is("[type='hidden']")) {
                        return;
                    }

                    if ($(this).parent().hasClass("input-group")) {
                        $(this).parent(".input-group").addClass("toggle-password");
                    } else {
                        $(this).addClass("toggle-password");
                    }
                    $(this).togglePassword();
                });


                $("input[type='text'][data-val-autotab='1']", formSelector).autotab();

                $.validator.unobtrusive.parse(formSelector);
                $(formSelector).validate();

                if (options.onSubmitOverride) {
                    onSubmitFunction = options.onSubmitOverride(formSelector);
                } else {
                    onSubmitFunction = onSubmit(formSelector);
                }

                $('.format-currency').each(function (i, v) {
                    let _unformatted = $(this).html();
                    _log("Unformatted money: " + _unformatted);
                    let _formatted = _unformatted.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                    _log("Formatted money: " + _formatted);
                    $(this).html(_formatted);
                });

            },
            toggleSpinner: function (optionalDeactivate) {
                if (optionalDeactivate) {
                    $("div.element-overlay, div.element-overlay-img, span#multipleClickBlocker").hide();
                } else {
                    $("div.element-overlay, div.element-overlay-img, span#multipleClickBlocker").toggle();
                }
            },
            ToggleButtonProcessing: function (btn) {
                const spinner =
                    '<span class="spinner-border spinner-border-sm text-light ml-3 d-inline-block" role="status" aria-hidden="true"></span><span class="sr-only">Loading...</span>';
                if (btn.is(':enabled')) {
                    let _html = btn.html();
                    btn.html(_html + spinner);
                    //btn.removeClass("btn-primary").addClass("btn-secondary");
                    btn.attr("disabled", "disabled");
                } else {
                    btn.find('span').remove();
                    //btn.removeClass("btn-secondary").addClass("btn-primary");
                    btn.removeAttr("disabled");
                }
            },

        };

        function onSubmit(formSelector) {
            $(formSelector).submit(function (event) {
                $('span.field-validation-error').show();

                if ($(this).valid()) {
                    Site.Form().toggleSpinner();
                    Site.Form().ToggleButtonProcessing(jQuery('.btn[type=submit]'));
                    return true;
                }
            });
        }

        function _log(s) {
            if (_debug && /chrom(e|ium)/.test(navigator.userAgent.toLowerCase()))
                console.log(s);
        }
    };

})(jQuery);


;
(function ($) {
    $.fn.togglePassword = function (options) {
        const isIe = /MSIE|Trident/ig.test(window.navigator.userAgent);
        const ieIdentSuffix = "-npi";
        const ieIdentToggleClass = "-nyltp";
     
        
        let eyecon = undefined;
        let opts = $.extend(
            {
                showtext: "Show",
                hidetext: "Hide",
                linkclass: "nyl-tp"
            },
            options
        );

        function toggle(npi, show) {
            if (isIe) {
                console.log('Doing a ' + show + ' for ' + npi.attr('id'));
                if (show === 'show') {
                    let toggleElem = $('#' + npi.attr('id') + ieIdentSuffix);
                    toggleElem.val(npi.val());
                    toggleElem.val(npi.val());
                    let originalId = npi.attr('id');
                    let tmpId = npi.attr('id') + '-tmp';
                    npi.attr('id', tmpId);
                    toggleElem.attr('id', originalId);
                    npi.attr('id', originalId + ieIdentSuffix);
                    npi.hide();
                    toggleElem.show();
                } else {
                    var baseId = npi.attr('id').substring(0, npi.attr('id').length - ieIdentSuffix.length);
                    var toggleElem = $('#' + baseId);
                    npi.val(toggleElem.val());
                    let tmpId = baseId + '-tmp';
                    toggleElem.attr('id', tmpId);
                    npi.attr('id', baseId);
                    toggleElem.attr('id', baseId + ieIdentSuffix);
                    toggleElem.hide();
                    npi.show();
                }
            } else {
                npi.prop("type", show === 'show' ? "text" : "password");
            }
        }

        return this.each(function () {
            let npi = $(this);

            eyecon = $('<button class="btn btn-outline-steel ' + opts.linkclass + '" type="button">').append(opts.showtext);
            eyecon.click(function (evt) {
                evt.preventDefault();

                if ($(this).html() === opts.hidetext) {
                    $(this).html(opts.showtext);
                    toggle(npi, 'hide');
                } else {
                    $(this).html(opts.hidetext);
                    toggle(npi, 'show');
                }
            });
            
       
        if ($(this).parent().hasClass('input-group')) {
          if( $(this).parent('.input-group').children(".input-group-append").html().indexOf("button")<=0)
              $(this).parent('.input-group').children(".input-group-append").append(eyecon);

        } 
        if (isIe) {
                const clonedP = $(this).clone().prop("type", "text").prop("id", $(this).attr("id") + ieIdentSuffix).hide();
                clonedP.keyup(function (evt) {
                    let textValue = $(this).val();
                    npi.val(textValue);
                });
                clonedP.insertAfter($(this));
            }
        });
    };
})(jQuery);
;
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.AOS=t():e.AOS=t()}(this,function(){return function(e){function t(o){if(n[o])return n[o].exports;var i=n[o]={exports:{},id:o,loaded:!1};return e[o].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var n={};return t.m=e,t.c=n,t.p="dist/",t(0)}([function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},r=n(1),a=(o(r),n(6)),u=o(a),c=n(7),f=o(c),s=n(8),d=o(s),l=n(9),p=o(l),m=n(10),b=o(m),v=n(11),y=o(v),g=n(14),h=o(g),w=[],k=!1,x={offset:120,delay:0,easing:"ease",duration:400,disable:!1,once:!1,startEvent:"DOMContentLoaded",throttleDelay:99,debounceDelay:50,disableMutationObserver:!1},j=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(e&&(k=!0),k)return w=(0,y.default)(w,x),(0,b.default)(w,x.once),w},O=function(){w=(0,h.default)(),j()},_=function(){w.forEach(function(e,t){e.node.removeAttribute("data-aos"),e.node.removeAttribute("data-aos-easing"),e.node.removeAttribute("data-aos-duration"),e.node.removeAttribute("data-aos-delay")})},S=function(e){return e===!0||"mobile"===e&&p.default.mobile()||"phone"===e&&p.default.phone()||"tablet"===e&&p.default.tablet()||"function"==typeof e&&e()===!0},z=function(e){x=i(x,e),w=(0,h.default)();var t=document.all&&!window.atob;return S(x.disable)||t?_():(document.querySelector("body").setAttribute("data-aos-easing",x.easing),document.querySelector("body").setAttribute("data-aos-duration",x.duration),document.querySelector("body").setAttribute("data-aos-delay",x.delay),"DOMContentLoaded"===x.startEvent&&["complete","interactive"].indexOf(document.readyState)>-1?j(!0):"load"===x.startEvent?window.addEventListener(x.startEvent,function(){j(!0)}):document.addEventListener(x.startEvent,function(){j(!0)}),window.addEventListener("resize",(0,f.default)(j,x.debounceDelay,!0)),window.addEventListener("orientationchange",(0,f.default)(j,x.debounceDelay,!0)),window.addEventListener("scroll",(0,u.default)(function(){(0,b.default)(w,x.once)},x.throttleDelay)),x.disableMutationObserver||(0,d.default)("[data-aos]",O),w)};e.exports={init:z,refresh:j,refreshHard:O}},function(e,t){},,,,,function(e,t){(function(t){"use strict";function n(e,t,n){function o(t){var n=b,o=v;return b=v=void 0,k=t,g=e.apply(o,n)}function r(e){return k=e,h=setTimeout(s,t),_?o(e):g}function a(e){var n=e-w,o=e-k,i=t-n;return S?j(i,y-o):i}function c(e){var n=e-w,o=e-k;return void 0===w||n>=t||n<0||S&&o>=y}function s(){var e=O();return c(e)?d(e):void(h=setTimeout(s,a(e)))}function d(e){return h=void 0,z&&b?o(e):(b=v=void 0,g)}function l(){void 0!==h&&clearTimeout(h),k=0,b=w=v=h=void 0}function p(){return void 0===h?g:d(O())}function m(){var e=O(),n=c(e);if(b=arguments,v=this,w=e,n){if(void 0===h)return r(w);if(S)return h=setTimeout(s,t),o(w)}return void 0===h&&(h=setTimeout(s,t)),g}var b,v,y,g,h,w,k=0,_=!1,S=!1,z=!0;if("function"!=typeof e)throw new TypeError(f);return t=u(t)||0,i(n)&&(_=!!n.leading,S="maxWait"in n,y=S?x(u(n.maxWait)||0,t):y,z="trailing"in n?!!n.trailing:z),m.cancel=l,m.flush=p,m}function o(e,t,o){var r=!0,a=!0;if("function"!=typeof e)throw new TypeError(f);return i(o)&&(r="leading"in o?!!o.leading:r,a="trailing"in o?!!o.trailing:a),n(e,t,{leading:r,maxWait:t,trailing:a})}function i(e){var t="undefined"==typeof e?"undefined":c(e);return!!e&&("object"==t||"function"==t)}function r(e){return!!e&&"object"==("undefined"==typeof e?"undefined":c(e))}function a(e){return"symbol"==("undefined"==typeof e?"undefined":c(e))||r(e)&&k.call(e)==d}function u(e){if("number"==typeof e)return e;if(a(e))return s;if(i(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=i(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(l,"");var n=m.test(e);return n||b.test(e)?v(e.slice(2),n?2:8):p.test(e)?s:+e}var c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},f="Expected a function",s=NaN,d="[object Symbol]",l=/^\s+|\s+$/g,p=/^[-+]0x[0-9a-f]+$/i,m=/^0b[01]+$/i,b=/^0o[0-7]+$/i,v=parseInt,y="object"==("undefined"==typeof t?"undefined":c(t))&&t&&t.Object===Object&&t,g="object"==("undefined"==typeof self?"undefined":c(self))&&self&&self.Object===Object&&self,h=y||g||Function("return this")(),w=Object.prototype,k=w.toString,x=Math.max,j=Math.min,O=function(){return h.Date.now()};e.exports=o}).call(t,function(){return this}())},function(e,t){(function(t){"use strict";function n(e,t,n){function i(t){var n=b,o=v;return b=v=void 0,O=t,g=e.apply(o,n)}function r(e){return O=e,h=setTimeout(s,t),_?i(e):g}function u(e){var n=e-w,o=e-O,i=t-n;return S?x(i,y-o):i}function f(e){var n=e-w,o=e-O;return void 0===w||n>=t||n<0||S&&o>=y}function s(){var e=j();return f(e)?d(e):void(h=setTimeout(s,u(e)))}function d(e){return h=void 0,z&&b?i(e):(b=v=void 0,g)}function l(){void 0!==h&&clearTimeout(h),O=0,b=w=v=h=void 0}function p(){return void 0===h?g:d(j())}function m(){var e=j(),n=f(e);if(b=arguments,v=this,w=e,n){if(void 0===h)return r(w);if(S)return h=setTimeout(s,t),i(w)}return void 0===h&&(h=setTimeout(s,t)),g}var b,v,y,g,h,w,O=0,_=!1,S=!1,z=!0;if("function"!=typeof e)throw new TypeError(c);return t=a(t)||0,o(n)&&(_=!!n.leading,S="maxWait"in n,y=S?k(a(n.maxWait)||0,t):y,z="trailing"in n?!!n.trailing:z),m.cancel=l,m.flush=p,m}function o(e){var t="undefined"==typeof e?"undefined":u(e);return!!e&&("object"==t||"function"==t)}function i(e){return!!e&&"object"==("undefined"==typeof e?"undefined":u(e))}function r(e){return"symbol"==("undefined"==typeof e?"undefined":u(e))||i(e)&&w.call(e)==s}function a(e){if("number"==typeof e)return e;if(r(e))return f;if(o(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=o(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(d,"");var n=p.test(e);return n||m.test(e)?b(e.slice(2),n?2:8):l.test(e)?f:+e}var u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},c="Expected a function",f=NaN,s="[object Symbol]",d=/^\s+|\s+$/g,l=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,m=/^0o[0-7]+$/i,b=parseInt,v="object"==("undefined"==typeof t?"undefined":u(t))&&t&&t.Object===Object&&t,y="object"==("undefined"==typeof self?"undefined":u(self))&&self&&self.Object===Object&&self,g=v||y||Function("return this")(),h=Object.prototype,w=h.toString,k=Math.max,x=Math.min,j=function(){return g.Date.now()};e.exports=n}).call(t,function(){return this}())},function(e,t){"use strict";function n(e,t){var n=window.document,r=window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver,a=new r(o);i=t,a.observe(n.documentElement,{childList:!0,subtree:!0,removedNodes:!0})}function o(e){e&&e.forEach(function(e){var t=Array.prototype.slice.call(e.addedNodes),n=Array.prototype.slice.call(e.removedNodes),o=t.concat(n).filter(function(e){return e.hasAttribute&&e.hasAttribute("data-aos")}).length;o&&i()})}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){};t.default=n},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(){return navigator.userAgent||navigator.vendor||window.opera||""}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),r=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i,a=/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i,u=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i,c=/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i,f=function(){function e(){n(this,e)}return i(e,[{key:"phone",value:function(){var e=o();return!(!r.test(e)&&!a.test(e.substr(0,4)))}},{key:"mobile",value:function(){var e=o();return!(!u.test(e)&&!c.test(e.substr(0,4)))}},{key:"tablet",value:function(){return this.mobile()&&!this.phone()}}]),e}();t.default=new f},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(e,t,n){var o=e.node.getAttribute("data-aos-once");t>e.position?e.node.classList.add("aos-animate"):"undefined"!=typeof o&&("false"===o||!n&&"true"!==o)&&e.node.classList.remove("aos-animate")},o=function(e,t){var o=window.pageYOffset,i=window.innerHeight;e.forEach(function(e,r){n(e,i+o,t)})};t.default=o},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(12),r=o(i),a=function(e,t){return e.forEach(function(e,n){e.node.classList.add("aos-init"),e.position=(0,r.default)(e.node,t.offset)}),e};t.default=a},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(13),r=o(i),a=function(e,t){var n=0,o=0,i=window.innerHeight,a={offset:e.getAttribute("data-aos-offset"),anchor:e.getAttribute("data-aos-anchor"),anchorPlacement:e.getAttribute("data-aos-anchor-placement")};switch(a.offset&&!isNaN(a.offset)&&(o=parseInt(a.offset)),a.anchor&&document.querySelectorAll(a.anchor)&&(e=document.querySelectorAll(a.anchor)[0]),n=(0,r.default)(e).top,a.anchorPlacement){case"top-bottom":break;case"center-bottom":n+=e.offsetHeight/2;break;case"bottom-bottom":n+=e.offsetHeight;break;case"top-center":n+=i/2;break;case"bottom-center":n+=i/2+e.offsetHeight;break;case"center-center":n+=i/2+e.offsetHeight/2;break;case"top-top":n+=i;break;case"bottom-top":n+=e.offsetHeight+i;break;case"center-top":n+=e.offsetHeight/2+i}return a.anchorPlacement||a.offset||isNaN(t)||(o=t),n+o};t.default=a},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(e){for(var t=0,n=0;e&&!isNaN(e.offsetLeft)&&!isNaN(e.offsetTop);)t+=e.offsetLeft-("BODY"!=e.tagName?e.scrollLeft:0),n+=e.offsetTop-("BODY"!=e.tagName?e.scrollTop:0),e=e.offsetParent;return{top:n,left:t}};t.default=n},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(e){return e=e||document.querySelectorAll("[data-aos]"),Array.prototype.map.call(e,function(e){return{node:e}})};t.default=n}])});;
(function(){var a,b,c,d,e,f,g,h,i=[].slice,j={}.hasOwnProperty,k=function(a,b){function c(){this.constructor=a}for(var d in b)j.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a};g=function(){},b=function(){function a(){}return a.prototype.addEventListener=a.prototype.on,a.prototype.on=function(a,b){return this._callbacks=this._callbacks||{},this._callbacks[a]||(this._callbacks[a]=[]),this._callbacks[a].push(b),this},a.prototype.emit=function(){var a,b,c,d,e,f;if(d=arguments[0],a=2<=arguments.length?i.call(arguments,1):[],this._callbacks=this._callbacks||{},c=this._callbacks[d])for(e=0,f=c.length;f>e;e++)b=c[e],b.apply(this,a);return this},a.prototype.removeListener=a.prototype.off,a.prototype.removeAllListeners=a.prototype.off,a.prototype.removeEventListener=a.prototype.off,a.prototype.off=function(a,b){var c,d,e,f,g;if(!this._callbacks||0===arguments.length)return this._callbacks={},this;if(d=this._callbacks[a],!d)return this;if(1===arguments.length)return delete this._callbacks[a],this;for(e=f=0,g=d.length;g>f;e=++f)if(c=d[e],c===b){d.splice(e,1);break}return this},a}(),a=function(a){function c(a,b){var e,f,g;if(this.element=a,this.version=c.version,this.defaultOptions.previewTemplate=this.defaultOptions.previewTemplate.replace(/\n*/g,""),this.clickableElements=[],this.listeners=[],this.files=[],"string"==typeof this.element&&(this.element=document.querySelector(this.element)),!this.element||null==this.element.nodeType)throw new Error("Invalid dropzone element.");if(this.element.dropzone)throw new Error("Dropzone already attached.");if(c.instances.push(this),this.element.dropzone=this,e=null!=(g=c.optionsForElement(this.element))?g:{},this.options=d({},this.defaultOptions,e,null!=b?b:{}),this.options.forceFallback||!c.isBrowserSupported())return this.options.fallback.call(this);if(null==this.options.url&&(this.options.url=this.element.getAttribute("action")),!this.options.url)throw new Error("No URL provided.");if(this.options.acceptedFiles&&this.options.acceptedMimeTypes)throw new Error("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated.");this.options.acceptedMimeTypes&&(this.options.acceptedFiles=this.options.acceptedMimeTypes,delete this.options.acceptedMimeTypes),this.options.method=this.options.method.toUpperCase(),(f=this.getExistingFallback())&&f.parentNode&&f.parentNode.removeChild(f),this.options.previewsContainer!==!1&&(this.previewsContainer=this.options.previewsContainer?c.getElement(this.options.previewsContainer,"previewsContainer"):this.element),this.options.clickable&&(this.clickableElements=this.options.clickable===!0?[this.element]:c.getElements(this.options.clickable,"clickable")),this.init()}var d,e;return k(c,a),c.prototype.Emitter=b,c.prototype.events=["drop","dragstart","dragend","dragenter","dragover","dragleave","addedfile","addedfiles","removedfile","thumbnail","error","errormultiple","processing","processingmultiple","uploadprogress","totaluploadprogress","sending","sendingmultiple","success","successmultiple","canceled","canceledmultiple","complete","completemultiple","reset","maxfilesexceeded","maxfilesreached","queuecomplete"],c.prototype.defaultOptions={url:null,method:"post",withCredentials:!1,parallelUploads:2,uploadMultiple:!1,maxFilesize:256,paramName:"file",createImageThumbnails:!0,maxThumbnailFilesize:10,thumbnailWidth:120,thumbnailHeight:120,filesizeBase:1e3,maxFiles:null,params:{},clickable:!0,ignoreHiddenFiles:!0,acceptedFiles:null,acceptedMimeTypes:null,autoProcessQueue:!0,autoQueue:!0,addRemoveLinks:!1,previewsContainer:null,hiddenInputContainer:"body",capture:null,renameFilename:null,dictDefaultMessage:"Drop files here to upload",dictFallbackMessage:"Your browser does not support drag'n'drop file uploads.",dictFallbackText:"Please use the fallback form below to upload your files like in the olden days.",dictFileTooBig:"File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.",dictInvalidFileType:"You can't upload files of this type.",dictResponseError:"Server responded with {{statusCode}} code.",dictCancelUpload:"Cancel upload",dictCancelUploadConfirmation:"Are you sure you want to cancel this upload?",dictRemoveFile:"Remove file",dictRemoveFileConfirmation:null,dictMaxFilesExceeded:"You can not upload any more files.",accept:function(a,b){return b()},init:function(){return g},forceFallback:!1,fallback:function(){var a,b,d,e,f,g;for(this.element.className=""+this.element.className+" dz-browser-not-supported",g=this.element.getElementsByTagName("div"),e=0,f=g.length;f>e;e++)a=g[e],/(^| )dz-message($| )/.test(a.className)&&(b=a,a.className="dz-message");return b||(b=c.createElement('<div class="dz-message"><span></span></div>'),this.element.appendChild(b)),d=b.getElementsByTagName("span")[0],d&&(null!=d.textContent?d.textContent=this.options.dictFallbackMessage:null!=d.innerText&&(d.innerText=this.options.dictFallbackMessage)),this.element.appendChild(this.getFallbackForm())},resize:function(a){var b,c,d;return b={srcX:0,srcY:0,srcWidth:a.width,srcHeight:a.height},c=a.width/a.height,b.optWidth=this.options.thumbnailWidth,b.optHeight=this.options.thumbnailHeight,null==b.optWidth&&null==b.optHeight?(b.optWidth=b.srcWidth,b.optHeight=b.srcHeight):null==b.optWidth?b.optWidth=c*b.optHeight:null==b.optHeight&&(b.optHeight=1/c*b.optWidth),d=b.optWidth/b.optHeight,a.height<b.optHeight||a.width<b.optWidth?(b.trgHeight=b.srcHeight,b.trgWidth=b.srcWidth):c>d?(b.srcHeight=a.height,b.srcWidth=b.srcHeight*d):(b.srcWidth=a.width,b.srcHeight=b.srcWidth/d),b.srcX=(a.width-b.srcWidth)/2,b.srcY=(a.height-b.srcHeight)/2,b},drop:function(){return this.element.classList.remove("dz-drag-hover")},dragstart:g,dragend:function(){return this.element.classList.remove("dz-drag-hover")},dragenter:function(){return this.element.classList.add("dz-drag-hover")},dragover:function(){return this.element.classList.add("dz-drag-hover")},dragleave:function(){return this.element.classList.remove("dz-drag-hover")},paste:g,reset:function(){return this.element.classList.remove("dz-started")},addedfile:function(a){var b,d,e,f,g,h,i,j,k,l,m,n,o;if(this.element===this.previewsContainer&&this.element.classList.add("dz-started"),this.previewsContainer){for(a.previewElement=c.createElement(this.options.previewTemplate.trim()),a.previewTemplate=a.previewElement,this.previewsContainer.appendChild(a.previewElement),l=a.previewElement.querySelectorAll("[data-dz-name]"),f=0,i=l.length;i>f;f++)b=l[f],b.textContent=this._renameFilename(a.name);for(m=a.previewElement.querySelectorAll("[data-dz-size]"),g=0,j=m.length;j>g;g++)b=m[g],b.innerHTML=this.filesize(a.size);for(this.options.addRemoveLinks&&(a._removeLink=c.createElement('<a class="dz-remove" href="javascript:undefined;" data-dz-remove>'+this.options.dictRemoveFile+"</a>"),a.previewElement.appendChild(a._removeLink)),d=function(b){return function(d){return d.preventDefault(),d.stopPropagation(),a.status===c.UPLOADING?c.confirm(b.options.dictCancelUploadConfirmation,function(){return b.removeFile(a)}):b.options.dictRemoveFileConfirmation?c.confirm(b.options.dictRemoveFileConfirmation,function(){return b.removeFile(a)}):b.removeFile(a)}}(this),n=a.previewElement.querySelectorAll("[data-dz-remove]"),o=[],h=0,k=n.length;k>h;h++)e=n[h],o.push(e.addEventListener("click",d));return o}},removedfile:function(a){var b;return a.previewElement&&null!=(b=a.previewElement)&&b.parentNode.removeChild(a.previewElement),this._updateMaxFilesReachedClass()},thumbnail:function(a,b){var c,d,e,f;if(a.previewElement){for(a.previewElement.classList.remove("dz-file-preview"),f=a.previewElement.querySelectorAll("[data-dz-thumbnail]"),d=0,e=f.length;e>d;d++)c=f[d],c.alt=a.name,c.src=b;return setTimeout(function(){return function(){return a.previewElement.classList.add("dz-image-preview")}}(this),1)}},error:function(a,b){var c,d,e,f,g;if(a.previewElement){for(a.previewElement.classList.add("dz-error"),"String"!=typeof b&&b.error&&(b=b.error),f=a.previewElement.querySelectorAll("[data-dz-errormessage]"),g=[],d=0,e=f.length;e>d;d++)c=f[d],g.push(c.textContent=b);return g}},errormultiple:g,processing:function(a){return a.previewElement&&(a.previewElement.classList.add("dz-processing"),a._removeLink)?a._removeLink.textContent=this.options.dictCancelUpload:void 0},processingmultiple:g,uploadprogress:function(a,b){var c,d,e,f,g;if(a.previewElement){for(f=a.previewElement.querySelectorAll("[data-dz-uploadprogress]"),g=[],d=0,e=f.length;e>d;d++)c=f[d],g.push("PROGRESS"===c.nodeName?c.value=b:c.style.width=""+b+"%");return g}},totaluploadprogress:g,sending:g,sendingmultiple:g,success:function(a){return a.previewElement?a.previewElement.classList.add("dz-success"):void 0},successmultiple:g,canceled:function(a){return this.emit("error",a,"Upload canceled.")},canceledmultiple:g,complete:function(a){return a._removeLink&&(a._removeLink.textContent=this.options.dictRemoveFile),a.previewElement?a.previewElement.classList.add("dz-complete"):void 0},completemultiple:g,maxfilesexceeded:g,maxfilesreached:g,queuecomplete:g,addedfiles:g,previewTemplate:'<div class="dz-preview dz-file-preview">\n  <div class="dz-image"><img data-dz-thumbnail /></div>\n  <div class="dz-details">\n    <div class="dz-size"><span data-dz-size></span></div>\n    <div class="dz-filename"><span data-dz-name></span></div>\n  </div>\n  <div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>\n  <div class="dz-error-message"><span data-dz-errormessage></span></div>\n  <div class="dz-success-mark">\n    <svg width="54px" height="54px" viewBox="0 0 54 54" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">\n      <title>Check</title>\n      <defs></defs>\n      <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">\n        <path d="M23.5,31.8431458 L17.5852419,25.9283877 C16.0248253,24.3679711 13.4910294,24.366835 11.9289322,25.9289322 C10.3700136,27.4878508 10.3665912,30.0234455 11.9283877,31.5852419 L20.4147581,40.0716123 C20.5133999,40.1702541 20.6159315,40.2626649 20.7218615,40.3488435 C22.2835669,41.8725651 24.794234,41.8626202 26.3461564,40.3106978 L43.3106978,23.3461564 C44.8771021,21.7797521 44.8758057,19.2483887 43.3137085,17.6862915 C41.7547899,16.1273729 39.2176035,16.1255422 37.6538436,17.6893022 L23.5,31.8431458 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z" id="Oval-2" stroke-opacity="0.198794158" stroke="#747474" fill-opacity="0.816519475" fill="#FFFFFF" sketch:type="MSShapeGroup"></path>\n      </g>\n    </svg>\n  </div>\n  <div class="dz-error-mark">\n    <svg width="54px" height="54px" viewBox="0 0 54 54" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">\n      <title>Error</title>\n      <defs></defs>\n      <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">\n        <g id="Check-+-Oval-2" sketch:type="MSLayerGroup" stroke="#747474" stroke-opacity="0.198794158" fill="#FFFFFF" fill-opacity="0.816519475">\n          <path d="M32.6568542,29 L38.3106978,23.3461564 C39.8771021,21.7797521 39.8758057,19.2483887 38.3137085,17.6862915 C36.7547899,16.1273729 34.2176035,16.1255422 32.6538436,17.6893022 L27,23.3431458 L21.3461564,17.6893022 C19.7823965,16.1255422 17.2452101,16.1273729 15.6862915,17.6862915 C14.1241943,19.2483887 14.1228979,21.7797521 15.6893022,23.3461564 L21.3431458,29 L15.6893022,34.6538436 C14.1228979,36.2202479 14.1241943,38.7516113 15.6862915,40.3137085 C17.2452101,41.8726271 19.7823965,41.8744578 21.3461564,40.3106978 L27,34.6568542 L32.6538436,40.3106978 C34.2176035,41.8744578 36.7547899,41.8726271 38.3137085,40.3137085 C39.8758057,38.7516113 39.8771021,36.2202479 38.3106978,34.6538436 L32.6568542,29 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z" id="Oval-2" sketch:type="MSShapeGroup"></path>\n        </g>\n      </g>\n    </svg>\n  </div>\n</div>'},d=function(){var a,b,c,d,e,f,g;for(d=arguments[0],c=2<=arguments.length?i.call(arguments,1):[],f=0,g=c.length;g>f;f++){b=c[f];for(a in b)e=b[a],d[a]=e}return d},c.prototype.getAcceptedFiles=function(){var a,b,c,d,e;for(d=this.files,e=[],b=0,c=d.length;c>b;b++)a=d[b],a.accepted&&e.push(a);return e},c.prototype.getRejectedFiles=function(){var a,b,c,d,e;for(d=this.files,e=[],b=0,c=d.length;c>b;b++)a=d[b],a.accepted||e.push(a);return e},c.prototype.getFilesWithStatus=function(a){var b,c,d,e,f;for(e=this.files,f=[],c=0,d=e.length;d>c;c++)b=e[c],b.status===a&&f.push(b);return f},c.prototype.getQueuedFiles=function(){return this.getFilesWithStatus(c.QUEUED)},c.prototype.getUploadingFiles=function(){return this.getFilesWithStatus(c.UPLOADING)},c.prototype.getAddedFiles=function(){return this.getFilesWithStatus(c.ADDED)},c.prototype.getActiveFiles=function(){var a,b,d,e,f;for(e=this.files,f=[],b=0,d=e.length;d>b;b++)a=e[b],(a.status===c.UPLOADING||a.status===c.QUEUED)&&f.push(a);return f},c.prototype.init=function(){var a,b,d,e,f,g,h;for("form"===this.element.tagName&&this.element.setAttribute("enctype","multipart/form-data"),this.element.classList.contains("dropzone")&&!this.element.querySelector(".dz-message")&&this.element.appendChild(c.createElement('<div class="dz-default dz-message"><span>'+this.options.dictDefaultMessage+"</span></div>")),this.clickableElements.length&&(d=function(a){return function(){return a.hiddenFileInput&&a.hiddenFileInput.parentNode.removeChild(a.hiddenFileInput),a.hiddenFileInput=document.createElement("input"),a.hiddenFileInput.setAttribute("type","file"),(null==a.options.maxFiles||a.options.maxFiles>1)&&a.hiddenFileInput.setAttribute("multiple","multiple"),a.hiddenFileInput.className="dz-hidden-input",null!=a.options.acceptedFiles&&a.hiddenFileInput.setAttribute("accept",a.options.acceptedFiles),null!=a.options.capture&&a.hiddenFileInput.setAttribute("capture",a.options.capture),a.hiddenFileInput.style.visibility="hidden",a.hiddenFileInput.style.position="absolute",a.hiddenFileInput.style.top="0",a.hiddenFileInput.style.left="0",a.hiddenFileInput.style.height="0",a.hiddenFileInput.style.width="0",document.querySelector(a.options.hiddenInputContainer).appendChild(a.hiddenFileInput),a.hiddenFileInput.addEventListener("change",function(){var b,c,e,f;if(c=a.hiddenFileInput.files,c.length)for(e=0,f=c.length;f>e;e++)b=c[e],a.addFile(b);return a.emit("addedfiles",c),d()})}}(this))(),this.URL=null!=(g=window.URL)?g:window.webkitURL,h=this.events,e=0,f=h.length;f>e;e++)a=h[e],this.on(a,this.options[a]);return this.on("uploadprogress",function(a){return function(){return a.updateTotalUploadProgress()}}(this)),this.on("removedfile",function(a){return function(){return a.updateTotalUploadProgress()}}(this)),this.on("canceled",function(a){return function(b){return a.emit("complete",b)}}(this)),this.on("complete",function(a){return function(){return 0===a.getAddedFiles().length&&0===a.getUploadingFiles().length&&0===a.getQueuedFiles().length?setTimeout(function(){return a.emit("queuecomplete")},0):void 0}}(this)),b=function(a){return a.stopPropagation(),a.preventDefault?a.preventDefault():a.returnValue=!1},this.listeners=[{element:this.element,events:{dragstart:function(a){return function(b){return a.emit("dragstart",b)}}(this),dragenter:function(a){return function(c){return b(c),a.emit("dragenter",c)}}(this),dragover:function(a){return function(c){var d;try{d=c.dataTransfer.effectAllowed}catch(e){}return c.dataTransfer.dropEffect="move"===d||"linkMove"===d?"move":"copy",b(c),a.emit("dragover",c)}}(this),dragleave:function(a){return function(b){return a.emit("dragleave",b)}}(this),drop:function(a){return function(c){return b(c),a.drop(c)}}(this),dragend:function(a){return function(b){return a.emit("dragend",b)}}(this)}}],this.clickableElements.forEach(function(a){return function(b){return a.listeners.push({element:b,events:{click:function(d){return(b!==a.element||d.target===a.element||c.elementInside(d.target,a.element.querySelector(".dz-message")))&&a.hiddenFileInput.click(),!0}}})}}(this)),this.enable(),this.options.init.call(this)},c.prototype.destroy=function(){var a;return this.disable(),this.removeAllFiles(!0),(null!=(a=this.hiddenFileInput)?a.parentNode:void 0)&&(this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput),this.hiddenFileInput=null),delete this.element.dropzone,c.instances.splice(c.instances.indexOf(this),1)},c.prototype.updateTotalUploadProgress=function(){var a,b,c,d,e,f,g,h;if(d=0,c=0,a=this.getActiveFiles(),a.length){for(h=this.getActiveFiles(),f=0,g=h.length;g>f;f++)b=h[f],d+=b.upload.bytesSent,c+=b.upload.total;e=100*d/c}else e=100;return this.emit("totaluploadprogress",e,c,d)},c.prototype._getParamName=function(a){return"function"==typeof this.options.paramName?this.options.paramName(a):""+this.options.paramName+(this.options.uploadMultiple?"["+a+"]":"")},c.prototype._renameFilename=function(a){return"function"!=typeof this.options.renameFilename?a:this.options.renameFilename(a)},c.prototype.getFallbackForm=function(){var a,b,d,e;return(a=this.getExistingFallback())?a:(d='<div class="dz-fallback">',this.options.dictFallbackText&&(d+="<p>"+this.options.dictFallbackText+"</p>"),d+='<input type="file" name="'+this._getParamName(0)+'" '+(this.options.uploadMultiple?'multiple="multiple"':void 0)+' /><input type="submit" value="Upload!"></div>',b=c.createElement(d),"FORM"!==this.element.tagName?(e=c.createElement('<form action="'+this.options.url+'" enctype="multipart/form-data" method="'+this.options.method+'"></form>'),e.appendChild(b)):(this.element.setAttribute("enctype","multipart/form-data"),this.element.setAttribute("method",this.options.method)),null!=e?e:b)},c.prototype.getExistingFallback=function(){var a,b,c,d,e,f;for(b=function(a){var b,c,d;for(c=0,d=a.length;d>c;c++)if(b=a[c],/(^| )fallback($| )/.test(b.className))return b},f=["div","form"],d=0,e=f.length;e>d;d++)if(c=f[d],a=b(this.element.getElementsByTagName(c)))return a},c.prototype.setupEventListeners=function(){var a,b,c,d,e,f,g;for(f=this.listeners,g=[],d=0,e=f.length;e>d;d++)a=f[d],g.push(function(){var d,e;d=a.events,e=[];for(b in d)c=d[b],e.push(a.element.addEventListener(b,c,!1));return e}());return g},c.prototype.removeEventListeners=function(){var a,b,c,d,e,f,g;for(f=this.listeners,g=[],d=0,e=f.length;e>d;d++)a=f[d],g.push(function(){var d,e;d=a.events,e=[];for(b in d)c=d[b],e.push(a.element.removeEventListener(b,c,!1));return e}());return g},c.prototype.disable=function(){var a,b,c,d,e;for(this.clickableElements.forEach(function(a){return a.classList.remove("dz-clickable")}),this.removeEventListeners(),d=this.files,e=[],b=0,c=d.length;c>b;b++)a=d[b],e.push(this.cancelUpload(a));return e},c.prototype.enable=function(){return this.clickableElements.forEach(function(a){return a.classList.add("dz-clickable")}),this.setupEventListeners()},c.prototype.filesize=function(a){var b,c,d,e,f,g,h,i;if(d=0,e="b",a>0){for(g=["TB","GB","MB","KB","b"],c=h=0,i=g.length;i>h;c=++h)if(f=g[c],b=Math.pow(this.options.filesizeBase,4-c)/10,a>=b){d=a/Math.pow(this.options.filesizeBase,4-c),e=f;break}d=Math.round(10*d)/10}return"<strong>"+d+"</strong> "+e},c.prototype._updateMaxFilesReachedClass=function(){return null!=this.options.maxFiles&&this.getAcceptedFiles().length>=this.options.maxFiles?(this.getAcceptedFiles().length===this.options.maxFiles&&this.emit("maxfilesreached",this.files),this.element.classList.add("dz-max-files-reached")):this.element.classList.remove("dz-max-files-reached")},c.prototype.drop=function(a){var b,c;a.dataTransfer&&(this.emit("drop",a),b=a.dataTransfer.files,this.emit("addedfiles",b),b.length&&(c=a.dataTransfer.items,c&&c.length&&null!=c[0].webkitGetAsEntry?this._addFilesFromItems(c):this.handleFiles(b)))},c.prototype.paste=function(a){var b,c;if(null!=(null!=a&&null!=(c=a.clipboardData)?c.items:void 0))return this.emit("paste",a),b=a.clipboardData.items,b.length?this._addFilesFromItems(b):void 0},c.prototype.handleFiles=function(a){var b,c,d,e;for(e=[],c=0,d=a.length;d>c;c++)b=a[c],e.push(this.addFile(b));return e},c.prototype._addFilesFromItems=function(a){var b,c,d,e,f;for(f=[],d=0,e=a.length;e>d;d++)c=a[d],f.push(null!=c.webkitGetAsEntry&&(b=c.webkitGetAsEntry())?b.isFile?this.addFile(c.getAsFile()):b.isDirectory?this._addFilesFromDirectory(b,b.name):void 0:null!=c.getAsFile?null==c.kind||"file"===c.kind?this.addFile(c.getAsFile()):void 0:void 0);return f},c.prototype._addFilesFromDirectory=function(a,b){var c,d,e;return c=a.createReader(),d=function(a){return"undefined"!=typeof console&&null!==console&&"function"==typeof console.log?console.log(a):void 0},(e=function(a){return function(){return c.readEntries(function(c){var d,f,g;if(c.length>0){for(f=0,g=c.length;g>f;f++)d=c[f],d.isFile?d.file(function(c){return a.options.ignoreHiddenFiles&&"."===c.name.substring(0,1)?void 0:(c.fullPath=""+b+"/"+c.name,a.addFile(c))}):d.isDirectory&&a._addFilesFromDirectory(d,""+b+"/"+d.name);e()}return null},d)}}(this))()},c.prototype.accept=function(a,b){return a.size>1024*this.options.maxFilesize*1024?b(this.options.dictFileTooBig.replace("{{filesize}}",Math.round(a.size/1024/10.24)/100).replace("{{maxFilesize}}",this.options.maxFilesize)):c.isValidFile(a,this.options.acceptedFiles)?null!=this.options.maxFiles&&this.getAcceptedFiles().length>=this.options.maxFiles?(b(this.options.dictMaxFilesExceeded.replace("{{maxFiles}}",this.options.maxFiles)),this.emit("maxfilesexceeded",a)):this.options.accept.call(this,a,b):b(this.options.dictInvalidFileType)},c.prototype.addFile=function(a){return a.upload={progress:0,total:a.size,bytesSent:0},this.files.push(a),a.status=c.ADDED,this.emit("addedfile",a),this._enqueueThumbnail(a),this.accept(a,function(b){return function(c){return c?(a.accepted=!1,b._errorProcessing([a],c)):(a.accepted=!0,b.options.autoQueue&&b.enqueueFile(a)),b._updateMaxFilesReachedClass()}}(this))},c.prototype.enqueueFiles=function(a){var b,c,d;for(c=0,d=a.length;d>c;c++)b=a[c],this.enqueueFile(b);return null},c.prototype.enqueueFile=function(a){if(a.status!==c.ADDED||a.accepted!==!0)throw new Error("This file can't be queued because it has already been processed or was rejected.");return a.status=c.QUEUED,this.options.autoProcessQueue?setTimeout(function(a){return function(){return a.processQueue()}}(this),0):void 0},c.prototype._thumbnailQueue=[],c.prototype._processingThumbnail=!1,c.prototype._enqueueThumbnail=function(a){return this.options.createImageThumbnails&&a.type.match(/image.*/)&&a.size<=1024*this.options.maxThumbnailFilesize*1024?(this._thumbnailQueue.push(a),setTimeout(function(a){return function(){return a._processThumbnailQueue()}}(this),0)):void 0},c.prototype._processThumbnailQueue=function(){return this._processingThumbnail||0===this._thumbnailQueue.length?void 0:(this._processingThumbnail=!0,this.createThumbnail(this._thumbnailQueue.shift(),function(a){return function(){return a._processingThumbnail=!1,a._processThumbnailQueue()}}(this)))},c.prototype.removeFile=function(a){return a.status===c.UPLOADING&&this.cancelUpload(a),this.files=h(this.files,a),this.emit("removedfile",a),0===this.files.length?this.emit("reset"):void 0},c.prototype.removeAllFiles=function(a){var b,d,e,f;for(null==a&&(a=!1),f=this.files.slice(),d=0,e=f.length;e>d;d++)b=f[d],(b.status!==c.UPLOADING||a)&&this.removeFile(b);return null},c.prototype.createThumbnail=function(a,b){var c;return c=new FileReader,c.onload=function(d){return function(){return"image/svg+xml"===a.type?(d.emit("thumbnail",a,c.result),void(null!=b&&b())):d.createThumbnailFromUrl(a,c.result,b)}}(this),c.readAsDataURL(a)},c.prototype.createThumbnailFromUrl=function(a,b,c,d){var e;return e=document.createElement("img"),d&&(e.crossOrigin=d),e.onload=function(b){return function(){var d,g,h,i,j,k,l,m;return a.width=e.width,a.height=e.height,h=b.options.resize.call(b,a),null==h.trgWidth&&(h.trgWidth=h.optWidth),null==h.trgHeight&&(h.trgHeight=h.optHeight),d=document.createElement("canvas"),g=d.getContext("2d"),d.width=h.trgWidth,d.height=h.trgHeight,f(g,e,null!=(j=h.srcX)?j:0,null!=(k=h.srcY)?k:0,h.srcWidth,h.srcHeight,null!=(l=h.trgX)?l:0,null!=(m=h.trgY)?m:0,h.trgWidth,h.trgHeight),i=d.toDataURL("image/png"),b.emit("thumbnail",a,i),null!=c?c():void 0}}(this),null!=c&&(e.onerror=c),e.src=b},c.prototype.processQueue=function(){var a,b,c,d;if(b=this.options.parallelUploads,c=this.getUploadingFiles().length,a=c,!(c>=b)&&(d=this.getQueuedFiles(),d.length>0)){if(this.options.uploadMultiple)return this.processFiles(d.slice(0,b-c));for(;b>a;){if(!d.length)return;this.processFile(d.shift()),a++}}},c.prototype.processFile=function(a){return this.processFiles([a])},c.prototype.processFiles=function(a){var b,d,e;for(d=0,e=a.length;e>d;d++)b=a[d],b.processing=!0,b.status=c.UPLOADING,this.emit("processing",b);return this.options.uploadMultiple&&this.emit("processingmultiple",a),this.uploadFiles(a)},c.prototype._getFilesWithXhr=function(a){var b,c;return c=function(){var c,d,e,f;for(e=this.files,f=[],c=0,d=e.length;d>c;c++)b=e[c],b.xhr===a&&f.push(b);return f}.call(this)},c.prototype.cancelUpload=function(a){var b,d,e,f,g,h,i;if(a.status===c.UPLOADING){for(d=this._getFilesWithXhr(a.xhr),e=0,g=d.length;g>e;e++)b=d[e],b.status=c.CANCELED;for(a.xhr.abort(),f=0,h=d.length;h>f;f++)b=d[f],this.emit("canceled",b);this.options.uploadMultiple&&this.emit("canceledmultiple",d)}else((i=a.status)===c.ADDED||i===c.QUEUED)&&(a.status=c.CANCELED,this.emit("canceled",a),this.options.uploadMultiple&&this.emit("canceledmultiple",[a]));return this.options.autoProcessQueue?this.processQueue():void 0},e=function(){var a,b;return b=arguments[0],a=2<=arguments.length?i.call(arguments,1):[],"function"==typeof b?b.apply(this,a):b},c.prototype.uploadFile=function(a){return this.uploadFiles([a])},c.prototype.uploadFiles=function(a){var b,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L;for(w=new XMLHttpRequest,x=0,B=a.length;B>x;x++)b=a[x],b.xhr=w;p=e(this.options.method,a),u=e(this.options.url,a),w.open(p,u,!0),w.withCredentials=!!this.options.withCredentials,s=null,g=function(c){return function(){var d,e,f;for(f=[],d=0,e=a.length;e>d;d++)b=a[d],f.push(c._errorProcessing(a,s||c.options.dictResponseError.replace("{{statusCode}}",w.status),w));return f}}(this),t=function(c){return function(d){var e,f,g,h,i,j,k,l,m;if(null!=d)for(f=100*d.loaded/d.total,g=0,j=a.length;j>g;g++)b=a[g],b.upload={progress:f,total:d.total,bytesSent:d.loaded};else{for(e=!0,f=100,h=0,k=a.length;k>h;h++)b=a[h],(100!==b.upload.progress||b.upload.bytesSent!==b.upload.total)&&(e=!1),b.upload.progress=f,b.upload.bytesSent=b.upload.total;if(e)return}for(m=[],i=0,l=a.length;l>i;i++)b=a[i],m.push(c.emit("uploadprogress",b,f,b.upload.bytesSent));return m}}(this),w.onload=function(b){return function(d){var e;if(a[0].status!==c.CANCELED&&4===w.readyState){if(s=w.responseText,w.getResponseHeader("content-type")&&~w.getResponseHeader("content-type").indexOf("application/json"))try{s=JSON.parse(s)}catch(f){d=f,s="Invalid JSON response from server."}return t(),200<=(e=w.status)&&300>e?b._finished(a,s,d):g()}}}(this),w.onerror=function(){return function(){return a[0].status!==c.CANCELED?g():void 0}}(this),r=null!=(G=w.upload)?G:w,r.onprogress=t,j={Accept:"application/json","Cache-Control":"no-cache","X-Requested-With":"XMLHttpRequest"},this.options.headers&&d(j,this.options.headers);for(h in j)i=j[h],i&&w.setRequestHeader(h,i);if(f=new FormData,this.options.params){H=this.options.params;for(o in H)v=H[o],f.append(o,v)}for(y=0,C=a.length;C>y;y++)b=a[y],this.emit("sending",b,w,f);if(this.options.uploadMultiple&&this.emit("sendingmultiple",a,w,f),"FORM"===this.element.tagName)for(I=this.element.querySelectorAll("input, textarea, select, button"),z=0,D=I.length;D>z;z++)if(l=I[z],m=l.getAttribute("name"),n=l.getAttribute("type"),"SELECT"===l.tagName&&l.hasAttribute("multiple"))for(J=l.options,A=0,E=J.length;E>A;A++)q=J[A],q.selected&&f.append(m,q.value);else(!n||"checkbox"!==(K=n.toLowerCase())&&"radio"!==K||l.checked)&&f.append(m,l.value);for(k=F=0,L=a.length-1;L>=0?L>=F:F>=L;k=L>=0?++F:--F)f.append(this._getParamName(k),a[k],this._renameFilename(a[k].name));return this.submitRequest(w,f,a)},c.prototype.submitRequest=function(a,b){return a.send(b)},c.prototype._finished=function(a,b,d){var e,f,g;for(f=0,g=a.length;g>f;f++)e=a[f],e.status=c.SUCCESS,this.emit("success",e,b,d),this.emit("complete",e);return this.options.uploadMultiple&&(this.emit("successmultiple",a,b,d),this.emit("completemultiple",a)),this.options.autoProcessQueue?this.processQueue():void 0},c.prototype._errorProcessing=function(a,b,d){var e,f,g;for(f=0,g=a.length;g>f;f++)e=a[f],e.status=c.ERROR,this.emit("error",e,b,d),this.emit("complete",e);return this.options.uploadMultiple&&(this.emit("errormultiple",a,b,d),this.emit("completemultiple",a)),this.options.autoProcessQueue?this.processQueue():void 0},c}(b),a.version="4.3.0",a.options={},a.optionsForElement=function(b){return b.getAttribute("id")?a.options[c(b.getAttribute("id"))]:void 0},a.instances=[],a.forElement=function(a){if("string"==typeof a&&(a=document.querySelector(a)),null==(null!=a?a.dropzone:void 0))throw new Error("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone.");return a.dropzone},a.autoDiscover=!0,a.discover=function(){var b,c,d,e,f,g;for(document.querySelectorAll?d=document.querySelectorAll(".dropzone"):(d=[],b=function(a){var b,c,e,f;for(f=[],c=0,e=a.length;e>c;c++)b=a[c],f.push(/(^| )dropzone($| )/.test(b.className)?d.push(b):void 0);return f},b(document.getElementsByTagName("div")),b(document.getElementsByTagName("form"))),g=[],e=0,f=d.length;f>e;e++)c=d[e],g.push(a.optionsForElement(c)!==!1?new a(c):void 0);return g},a.blacklistedBrowsers=[/opera.*Macintosh.*version\/12/i],a.isBrowserSupported=function(){var b,c,d,e,f;if(b=!0,window.File&&window.FileReader&&window.FileList&&window.Blob&&window.FormData&&document.querySelector)if("classList"in document.createElement("a"))for(f=a.blacklistedBrowsers,d=0,e=f.length;e>d;d++)c=f[d],c.test(navigator.userAgent)&&(b=!1);else b=!1;else b=!1;return b},h=function(a,b){var c,d,e,f;for(f=[],d=0,e=a.length;e>d;d++)c=a[d],c!==b&&f.push(c);return f},c=function(a){return a.replace(/[\-_](\w)/g,function(a){return a.charAt(1).toUpperCase()})},a.createElement=function(a){var b;return b=document.createElement("div"),b.innerHTML=a,b.childNodes[0]},a.elementInside=function(a,b){if(a===b)return!0;for(;a=a.parentNode;)if(a===b)return!0;return!1},a.getElement=function(a,b){var c;if("string"==typeof a?c=document.querySelector(a):null!=a.nodeType&&(c=a),null==c)throw new Error("Invalid `"+b+"` option provided. Please provide a CSS selector or a plain HTML element.");return c},a.getElements=function(a,b){var c,d,e,f,g,h,i,j;if(a instanceof Array){e=[];try{for(f=0,h=a.length;h>f;f++)d=a[f],e.push(this.getElement(d,b))}catch(k){c=k,e=null}}else if("string"==typeof a)for(e=[],j=document.querySelectorAll(a),g=0,i=j.length;i>g;g++)d=j[g],e.push(d);else null!=a.nodeType&&(e=[a]);if(null==e||!e.length)throw new Error("Invalid `"+b+"` option provided. Please provide a CSS selector, a plain HTML element or a list of those.");return e},a.confirm=function(a,b,c){return window.confirm(a)?b():null!=c?c():void 0},a.isValidFile=function(a,b){var c,d,e,f,g;if(!b)return!0;for(b=b.split(","),d=a.type,c=d.replace(/\/.*$/,""),f=0,g=b.length;g>f;f++)if(e=b[f],e=e.trim(),"."===e.charAt(0)){if(-1!==a.name.toLowerCase().indexOf(e.toLowerCase(),a.name.length-e.length))return!0}else if(/\/\*$/.test(e)){if(c===e.replace(/\/.*$/,""))return!0
}else if(d===e)return!0;return!1},"undefined"!=typeof jQuery&&null!==jQuery&&(jQuery.fn.dropzone=function(b){return this.each(function(){return new a(this,b)})}),"undefined"!=typeof module&&null!==module?module.exports=a:window.Dropzone=a,a.ADDED="added",a.QUEUED="queued",a.ACCEPTED=a.QUEUED,a.UPLOADING="uploading",a.PROCESSING=a.UPLOADING,a.CANCELED="canceled",a.ERROR="error",a.SUCCESS="success",e=function(a){var b,c,d,e,f,g,h,i,j,k;for(h=a.naturalWidth,g=a.naturalHeight,c=document.createElement("canvas"),c.width=1,c.height=g,d=c.getContext("2d"),d.drawImage(a,0,0),e=d.getImageData(0,0,1,g).data,k=0,f=g,i=g;i>k;)b=e[4*(i-1)+3],0===b?f=i:k=i,i=f+k>>1;return j=i/g,0===j?1:j},f=function(a,b,c,d,f,g,h,i,j,k){var l;return l=e(b),a.drawImage(b,c,d,f,g,h,i,j,k/l)},d=function(a,b){var c,d,e,f,g,h,i,j,k;if(e=!1,k=!0,d=a.document,j=d.documentElement,c=d.addEventListener?"addEventListener":"attachEvent",i=d.addEventListener?"removeEventListener":"detachEvent",h=d.addEventListener?"":"on",f=function(c){return"readystatechange"!==c.type||"complete"===d.readyState?(("load"===c.type?a:d)[i](h+c.type,f,!1),!e&&(e=!0)?b.call(a,c.type||c):void 0):void 0},g=function(){var a;try{j.doScroll("left")}catch(b){return a=b,void setTimeout(g,50)}return f("poll")},"complete"!==d.readyState){if(d.createEventObject&&j.doScroll){try{k=!a.frameElement}catch(l){}k&&g()}return d[c](h+"DOMContentLoaded",f,!1),d[c](h+"readystatechange",f,!1),a[c](h+"load",f,!1)}},a._autoDiscoverFunction=function(){return a.autoDiscover?a.discover():void 0},d(window,a._autoDiscoverFunction)}).call(this);;
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a(jQuery)}(function(a){var b={exports:{}};return function(){var c,d,e,f,g,h,i,j,k=[].slice,l={}.hasOwnProperty,m=function(a,b){function c(){this.constructor=a}for(var d in b)l.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a};i=function(){},d=function(){function a(){}return a.prototype.addEventListener=a.prototype.on,a.prototype.on=function(a,b){return this._callbacks=this._callbacks||{},this._callbacks[a]||(this._callbacks[a]=[]),this._callbacks[a].push(b),this},a.prototype.emit=function(){var a,b,c,d,e,f;if(d=arguments[0],a=2<=arguments.length?k.call(arguments,1):[],this._callbacks=this._callbacks||{},c=this._callbacks[d])for(e=0,f=c.length;f>e;e++)b=c[e],b.apply(this,a);return this},a.prototype.removeListener=a.prototype.off,a.prototype.removeAllListeners=a.prototype.off,a.prototype.removeEventListener=a.prototype.off,a.prototype.off=function(a,b){var c,d,e,f,g;if(!this._callbacks||0===arguments.length)return this._callbacks={},this;if(d=this._callbacks[a],!d)return this;if(1===arguments.length)return delete this._callbacks[a],this;for(e=f=0,g=d.length;g>f;e=++f)if(c=d[e],c===b){d.splice(e,1);break}return this},a}(),c=function(a){function b(a,d){var e,f,g;if(this.element=a,this.version=b.version,this.defaultOptions.previewTemplate=this.defaultOptions.previewTemplate.replace(/\n*/g,""),this.clickableElements=[],this.listeners=[],this.files=[],"string"==typeof this.element&&(this.element=document.querySelector(this.element)),!this.element||null==this.element.nodeType)throw new Error("Invalid dropzone element.");if(this.element.dropzone)throw new Error("Dropzone already attached.");if(b.instances.push(this),this.element.dropzone=this,e=null!=(g=b.optionsForElement(this.element))?g:{},this.options=c({},this.defaultOptions,e,null!=d?d:{}),this.options.forceFallback||!b.isBrowserSupported())return this.options.fallback.call(this);if(null==this.options.url&&(this.options.url=this.element.getAttribute("action")),!this.options.url)throw new Error("No URL provided.");if(this.options.acceptedFiles&&this.options.acceptedMimeTypes)throw new Error("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated.");this.options.acceptedMimeTypes&&(this.options.acceptedFiles=this.options.acceptedMimeTypes,delete this.options.acceptedMimeTypes),this.options.method=this.options.method.toUpperCase(),(f=this.getExistingFallback())&&f.parentNode&&f.parentNode.removeChild(f),this.options.previewsContainer!==!1&&(this.previewsContainer=this.options.previewsContainer?b.getElement(this.options.previewsContainer,"previewsContainer"):this.element),this.options.clickable&&(this.clickableElements=this.options.clickable===!0?[this.element]:b.getElements(this.options.clickable,"clickable")),this.init()}var c,e;return m(b,a),b.prototype.Emitter=d,b.prototype.events=["drop","dragstart","dragend","dragenter","dragover","dragleave","addedfile","addedfiles","removedfile","thumbnail","error","errormultiple","processing","processingmultiple","uploadprogress","totaluploadprogress","sending","sendingmultiple","success","successmultiple","canceled","canceledmultiple","complete","completemultiple","reset","maxfilesexceeded","maxfilesreached","queuecomplete"],b.prototype.defaultOptions={url:null,method:"post",withCredentials:!1,parallelUploads:2,uploadMultiple:!1,maxFilesize:256,paramName:"file",createImageThumbnails:!0,maxThumbnailFilesize:10,thumbnailWidth:120,thumbnailHeight:120,filesizeBase:1e3,maxFiles:null,params:{},clickable:!0,ignoreHiddenFiles:!0,acceptedFiles:null,acceptedMimeTypes:null,autoProcessQueue:!0,autoQueue:!0,addRemoveLinks:!1,previewsContainer:null,hiddenInputContainer:"body",capture:null,renameFilename:null,dictDefaultMessage:"Drop files here to upload",dictFallbackMessage:"Your browser does not support drag'n'drop file uploads.",dictFallbackText:"Please use the fallback form below to upload your files like in the olden days.",dictFileTooBig:"File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.",dictInvalidFileType:"You can't upload files of this type.",dictResponseError:"Server responded with {{statusCode}} code.",dictCancelUpload:"Cancel upload",dictCancelUploadConfirmation:"Are you sure you want to cancel this upload?",dictRemoveFile:"Remove file",dictRemoveFileConfirmation:null,dictMaxFilesExceeded:"You can not upload any more files.",accept:function(a,b){return b()},init:function(){return i},forceFallback:!1,fallback:function(){var a,c,d,e,f,g;for(this.element.className=""+this.element.className+" dz-browser-not-supported",g=this.element.getElementsByTagName("div"),e=0,f=g.length;f>e;e++)a=g[e],/(^| )dz-message($| )/.test(a.className)&&(c=a,a.className="dz-message");return c||(c=b.createElement('<div class="dz-message"><span></span></div>'),this.element.appendChild(c)),d=c.getElementsByTagName("span")[0],d&&(null!=d.textContent?d.textContent=this.options.dictFallbackMessage:null!=d.innerText&&(d.innerText=this.options.dictFallbackMessage)),this.element.appendChild(this.getFallbackForm())},resize:function(a){var b,c,d;return b={srcX:0,srcY:0,srcWidth:a.width,srcHeight:a.height},c=a.width/a.height,b.optWidth=this.options.thumbnailWidth,b.optHeight=this.options.thumbnailHeight,null==b.optWidth&&null==b.optHeight?(b.optWidth=b.srcWidth,b.optHeight=b.srcHeight):null==b.optWidth?b.optWidth=c*b.optHeight:null==b.optHeight&&(b.optHeight=1/c*b.optWidth),d=b.optWidth/b.optHeight,a.height<b.optHeight||a.width<b.optWidth?(b.trgHeight=b.srcHeight,b.trgWidth=b.srcWidth):c>d?(b.srcHeight=a.height,b.srcWidth=b.srcHeight*d):(b.srcWidth=a.width,b.srcHeight=b.srcWidth/d),b.srcX=(a.width-b.srcWidth)/2,b.srcY=(a.height-b.srcHeight)/2,b},drop:function(){return this.element.classList.remove("dz-drag-hover")},dragstart:i,dragend:function(){return this.element.classList.remove("dz-drag-hover")},dragenter:function(){return this.element.classList.add("dz-drag-hover")},dragover:function(){return this.element.classList.add("dz-drag-hover")},dragleave:function(){return this.element.classList.remove("dz-drag-hover")},paste:i,reset:function(){return this.element.classList.remove("dz-started")},addedfile:function(a){var c,d,e,f,g,h,i,j,k,l,m,n,o;if(this.element===this.previewsContainer&&this.element.classList.add("dz-started"),this.previewsContainer){for(a.previewElement=b.createElement(this.options.previewTemplate.trim()),a.previewTemplate=a.previewElement,this.previewsContainer.appendChild(a.previewElement),l=a.previewElement.querySelectorAll("[data-dz-name]"),f=0,i=l.length;i>f;f++)c=l[f],c.textContent=this._renameFilename(a.name);for(m=a.previewElement.querySelectorAll("[data-dz-size]"),g=0,j=m.length;j>g;g++)c=m[g],c.innerHTML=this.filesize(a.size);for(this.options.addRemoveLinks&&(a._removeLink=b.createElement('<a class="dz-remove" href="javascript:undefined;" data-dz-remove>'+this.options.dictRemoveFile+"</a>"),a.previewElement.appendChild(a._removeLink)),d=function(c){return function(d){return d.preventDefault(),d.stopPropagation(),a.status===b.UPLOADING?b.confirm(c.options.dictCancelUploadConfirmation,function(){return c.removeFile(a)}):c.options.dictRemoveFileConfirmation?b.confirm(c.options.dictRemoveFileConfirmation,function(){return c.removeFile(a)}):c.removeFile(a)}}(this),n=a.previewElement.querySelectorAll("[data-dz-remove]"),o=[],h=0,k=n.length;k>h;h++)e=n[h],o.push(e.addEventListener("click",d));return o}},removedfile:function(a){var b;return a.previewElement&&null!=(b=a.previewElement)&&b.parentNode.removeChild(a.previewElement),this._updateMaxFilesReachedClass()},thumbnail:function(a,b){var c,d,e,f;if(a.previewElement){for(a.previewElement.classList.remove("dz-file-preview"),f=a.previewElement.querySelectorAll("[data-dz-thumbnail]"),d=0,e=f.length;e>d;d++)c=f[d],c.alt=a.name,c.src=b;return setTimeout(function(){return function(){return a.previewElement.classList.add("dz-image-preview")}}(this),1)}},error:function(a,b){var c,d,e,f,g;if(a.previewElement){for(a.previewElement.classList.add("dz-error"),"String"!=typeof b&&b.error&&(b=b.error),f=a.previewElement.querySelectorAll("[data-dz-errormessage]"),g=[],d=0,e=f.length;e>d;d++)c=f[d],g.push(c.textContent=b);return g}},errormultiple:i,processing:function(a){return a.previewElement&&(a.previewElement.classList.add("dz-processing"),a._removeLink)?a._removeLink.textContent=this.options.dictCancelUpload:void 0},processingmultiple:i,uploadprogress:function(a,b){var c,d,e,f,g;if(a.previewElement){for(f=a.previewElement.querySelectorAll("[data-dz-uploadprogress]"),g=[],d=0,e=f.length;e>d;d++)c=f[d],g.push("PROGRESS"===c.nodeName?c.value=b:c.style.width=""+b+"%");return g}},totaluploadprogress:i,sending:i,sendingmultiple:i,success:function(a){return a.previewElement?a.previewElement.classList.add("dz-success"):void 0},successmultiple:i,canceled:function(a){return this.emit("error",a,"Upload canceled.")},canceledmultiple:i,complete:function(a){return a._removeLink&&(a._removeLink.textContent=this.options.dictRemoveFile),a.previewElement?a.previewElement.classList.add("dz-complete"):void 0},completemultiple:i,maxfilesexceeded:i,maxfilesreached:i,queuecomplete:i,addedfiles:i,previewTemplate:'<div class="dz-preview dz-file-preview">\n  <div class="dz-image"><img data-dz-thumbnail /></div>\n  <div class="dz-details">\n    <div class="dz-size"><span data-dz-size></span></div>\n    <div class="dz-filename"><span data-dz-name></span></div>\n  </div>\n  <div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>\n  <div class="dz-error-message"><span data-dz-errormessage></span></div>\n  <div class="dz-success-mark">\n    <svg width="54px" height="54px" viewBox="0 0 54 54" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">\n      <title>Check</title>\n      <defs></defs>\n      <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">\n        <path d="M23.5,31.8431458 L17.5852419,25.9283877 C16.0248253,24.3679711 13.4910294,24.366835 11.9289322,25.9289322 C10.3700136,27.4878508 10.3665912,30.0234455 11.9283877,31.5852419 L20.4147581,40.0716123 C20.5133999,40.1702541 20.6159315,40.2626649 20.7218615,40.3488435 C22.2835669,41.8725651 24.794234,41.8626202 26.3461564,40.3106978 L43.3106978,23.3461564 C44.8771021,21.7797521 44.8758057,19.2483887 43.3137085,17.6862915 C41.7547899,16.1273729 39.2176035,16.1255422 37.6538436,17.6893022 L23.5,31.8431458 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z" id="Oval-2" stroke-opacity="0.198794158" stroke="#747474" fill-opacity="0.816519475" fill="#FFFFFF" sketch:type="MSShapeGroup"></path>\n      </g>\n    </svg>\n  </div>\n  <div class="dz-error-mark">\n    <svg width="54px" height="54px" viewBox="0 0 54 54" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">\n      <title>Error</title>\n      <defs></defs>\n      <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">\n        <g id="Check-+-Oval-2" sketch:type="MSLayerGroup" stroke="#747474" stroke-opacity="0.198794158" fill="#FFFFFF" fill-opacity="0.816519475">\n          <path d="M32.6568542,29 L38.3106978,23.3461564 C39.8771021,21.7797521 39.8758057,19.2483887 38.3137085,17.6862915 C36.7547899,16.1273729 34.2176035,16.1255422 32.6538436,17.6893022 L27,23.3431458 L21.3461564,17.6893022 C19.7823965,16.1255422 17.2452101,16.1273729 15.6862915,17.6862915 C14.1241943,19.2483887 14.1228979,21.7797521 15.6893022,23.3461564 L21.3431458,29 L15.6893022,34.6538436 C14.1228979,36.2202479 14.1241943,38.7516113 15.6862915,40.3137085 C17.2452101,41.8726271 19.7823965,41.8744578 21.3461564,40.3106978 L27,34.6568542 L32.6538436,40.3106978 C34.2176035,41.8744578 36.7547899,41.8726271 38.3137085,40.3137085 C39.8758057,38.7516113 39.8771021,36.2202479 38.3106978,34.6538436 L32.6568542,29 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z" id="Oval-2" sketch:type="MSShapeGroup"></path>\n        </g>\n      </g>\n    </svg>\n  </div>\n</div>'},c=function(){var a,b,c,d,e,f,g;for(d=arguments[0],c=2<=arguments.length?k.call(arguments,1):[],f=0,g=c.length;g>f;f++){b=c[f];for(a in b)e=b[a],d[a]=e}return d},b.prototype.getAcceptedFiles=function(){var a,b,c,d,e;for(d=this.files,e=[],b=0,c=d.length;c>b;b++)a=d[b],a.accepted&&e.push(a);return e},b.prototype.getRejectedFiles=function(){var a,b,c,d,e;for(d=this.files,e=[],b=0,c=d.length;c>b;b++)a=d[b],a.accepted||e.push(a);return e},b.prototype.getFilesWithStatus=function(a){var b,c,d,e,f;for(e=this.files,f=[],c=0,d=e.length;d>c;c++)b=e[c],b.status===a&&f.push(b);return f},b.prototype.getQueuedFiles=function(){return this.getFilesWithStatus(b.QUEUED)},b.prototype.getUploadingFiles=function(){return this.getFilesWithStatus(b.UPLOADING)},b.prototype.getAddedFiles=function(){return this.getFilesWithStatus(b.ADDED)},b.prototype.getActiveFiles=function(){var a,c,d,e,f;for(e=this.files,f=[],c=0,d=e.length;d>c;c++)a=e[c],(a.status===b.UPLOADING||a.status===b.QUEUED)&&f.push(a);return f},b.prototype.init=function(){var a,c,d,e,f,g,h;for("form"===this.element.tagName&&this.element.setAttribute("enctype","multipart/form-data"),this.element.classList.contains("dropzone")&&!this.element.querySelector(".dz-message")&&this.element.appendChild(b.createElement('<div class="dz-default dz-message"><span>'+this.options.dictDefaultMessage+"</span></div>")),this.clickableElements.length&&(d=function(a){return function(){return a.hiddenFileInput&&a.hiddenFileInput.parentNode.removeChild(a.hiddenFileInput),a.hiddenFileInput=document.createElement("input"),a.hiddenFileInput.setAttribute("type","file"),(null==a.options.maxFiles||a.options.maxFiles>1)&&a.hiddenFileInput.setAttribute("multiple","multiple"),a.hiddenFileInput.className="dz-hidden-input",null!=a.options.acceptedFiles&&a.hiddenFileInput.setAttribute("accept",a.options.acceptedFiles),null!=a.options.capture&&a.hiddenFileInput.setAttribute("capture",a.options.capture),a.hiddenFileInput.style.visibility="hidden",a.hiddenFileInput.style.position="absolute",a.hiddenFileInput.style.top="0",a.hiddenFileInput.style.left="0",a.hiddenFileInput.style.height="0",a.hiddenFileInput.style.width="0",document.querySelector(a.options.hiddenInputContainer).appendChild(a.hiddenFileInput),a.hiddenFileInput.addEventListener("change",function(){var b,c,e,f;if(c=a.hiddenFileInput.files,c.length)for(e=0,f=c.length;f>e;e++)b=c[e],a.addFile(b);return a.emit("addedfiles",c),d()})}}(this))(),this.URL=null!=(g=window.URL)?g:window.webkitURL,h=this.events,e=0,f=h.length;f>e;e++)a=h[e],this.on(a,this.options[a]);return this.on("uploadprogress",function(a){return function(){return a.updateTotalUploadProgress()}}(this)),this.on("removedfile",function(a){return function(){return a.updateTotalUploadProgress()}}(this)),this.on("canceled",function(a){return function(b){return a.emit("complete",b)}}(this)),this.on("complete",function(a){return function(){return 0===a.getAddedFiles().length&&0===a.getUploadingFiles().length&&0===a.getQueuedFiles().length?setTimeout(function(){return a.emit("queuecomplete")},0):void 0}}(this)),c=function(a){return a.stopPropagation(),a.preventDefault?a.preventDefault():a.returnValue=!1},this.listeners=[{element:this.element,events:{dragstart:function(a){return function(b){return a.emit("dragstart",b)}}(this),dragenter:function(a){return function(b){return c(b),a.emit("dragenter",b)}}(this),dragover:function(a){return function(b){var d;try{d=b.dataTransfer.effectAllowed}catch(e){}return b.dataTransfer.dropEffect="move"===d||"linkMove"===d?"move":"copy",c(b),a.emit("dragover",b)}}(this),dragleave:function(a){return function(b){return a.emit("dragleave",b)}}(this),drop:function(a){return function(b){return c(b),a.drop(b)}}(this),dragend:function(a){return function(b){return a.emit("dragend",b)}}(this)}}],this.clickableElements.forEach(function(a){return function(c){return a.listeners.push({element:c,events:{click:function(d){return(c!==a.element||d.target===a.element||b.elementInside(d.target,a.element.querySelector(".dz-message")))&&a.hiddenFileInput.click(),!0}}})}}(this)),this.enable(),this.options.init.call(this)},b.prototype.destroy=function(){var a;return this.disable(),this.removeAllFiles(!0),(null!=(a=this.hiddenFileInput)?a.parentNode:void 0)&&(this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput),this.hiddenFileInput=null),delete this.element.dropzone,b.instances.splice(b.instances.indexOf(this),1)},b.prototype.updateTotalUploadProgress=function(){var a,b,c,d,e,f,g,h;if(d=0,c=0,a=this.getActiveFiles(),a.length){for(h=this.getActiveFiles(),f=0,g=h.length;g>f;f++)b=h[f],d+=b.upload.bytesSent,c+=b.upload.total;e=100*d/c}else e=100;return this.emit("totaluploadprogress",e,c,d)},b.prototype._getParamName=function(a){return"function"==typeof this.options.paramName?this.options.paramName(a):""+this.options.paramName+(this.options.uploadMultiple?"["+a+"]":"")},b.prototype._renameFilename=function(a){return"function"!=typeof this.options.renameFilename?a:this.options.renameFilename(a)},b.prototype.getFallbackForm=function(){var a,c,d,e;return(a=this.getExistingFallback())?a:(d='<div class="dz-fallback">',this.options.dictFallbackText&&(d+="<p>"+this.options.dictFallbackText+"</p>"),d+='<input type="file" name="'+this._getParamName(0)+'" '+(this.options.uploadMultiple?'multiple="multiple"':void 0)+' /><input type="submit" value="Upload!"></div>',c=b.createElement(d),"FORM"!==this.element.tagName?(e=b.createElement('<form action="'+this.options.url+'" enctype="multipart/form-data" method="'+this.options.method+'"></form>'),e.appendChild(c)):(this.element.setAttribute("enctype","multipart/form-data"),this.element.setAttribute("method",this.options.method)),null!=e?e:c)},b.prototype.getExistingFallback=function(){var a,b,c,d,e,f;for(b=function(a){var b,c,d;for(c=0,d=a.length;d>c;c++)if(b=a[c],/(^| )fallback($| )/.test(b.className))return b},f=["div","form"],d=0,e=f.length;e>d;d++)if(c=f[d],a=b(this.element.getElementsByTagName(c)))return a},b.prototype.setupEventListeners=function(){var a,b,c,d,e,f,g;for(f=this.listeners,g=[],d=0,e=f.length;e>d;d++)a=f[d],g.push(function(){var d,e;d=a.events,e=[];for(b in d)c=d[b],e.push(a.element.addEventListener(b,c,!1));return e}());return g},b.prototype.removeEventListeners=function(){var a,b,c,d,e,f,g;for(f=this.listeners,g=[],d=0,e=f.length;e>d;d++)a=f[d],g.push(function(){var d,e;d=a.events,e=[];for(b in d)c=d[b],e.push(a.element.removeEventListener(b,c,!1));return e}());return g},b.prototype.disable=function(){var a,b,c,d,e;for(this.clickableElements.forEach(function(a){return a.classList.remove("dz-clickable")}),this.removeEventListeners(),d=this.files,e=[],b=0,c=d.length;c>b;b++)a=d[b],e.push(this.cancelUpload(a));return e},b.prototype.enable=function(){return this.clickableElements.forEach(function(a){return a.classList.add("dz-clickable")}),this.setupEventListeners()},b.prototype.filesize=function(a){var b,c,d,e,f,g,h,i;if(d=0,e="b",a>0){for(g=["TB","GB","MB","KB","b"],c=h=0,i=g.length;i>h;c=++h)if(f=g[c],b=Math.pow(this.options.filesizeBase,4-c)/10,a>=b){d=a/Math.pow(this.options.filesizeBase,4-c),e=f;break}d=Math.round(10*d)/10}return"<strong>"+d+"</strong> "+e},b.prototype._updateMaxFilesReachedClass=function(){return null!=this.options.maxFiles&&this.getAcceptedFiles().length>=this.options.maxFiles?(this.getAcceptedFiles().length===this.options.maxFiles&&this.emit("maxfilesreached",this.files),this.element.classList.add("dz-max-files-reached")):this.element.classList.remove("dz-max-files-reached")},b.prototype.drop=function(a){var b,c;a.dataTransfer&&(this.emit("drop",a),b=a.dataTransfer.files,this.emit("addedfiles",b),b.length&&(c=a.dataTransfer.items,c&&c.length&&null!=c[0].webkitGetAsEntry?this._addFilesFromItems(c):this.handleFiles(b)))},b.prototype.paste=function(a){var b,c;if(null!=(null!=a&&null!=(c=a.clipboardData)?c.items:void 0))return this.emit("paste",a),b=a.clipboardData.items,b.length?this._addFilesFromItems(b):void 0},b.prototype.handleFiles=function(a){var b,c,d,e;for(e=[],c=0,d=a.length;d>c;c++)b=a[c],e.push(this.addFile(b));return e},b.prototype._addFilesFromItems=function(a){var b,c,d,e,f;for(f=[],d=0,e=a.length;e>d;d++)c=a[d],f.push(null!=c.webkitGetAsEntry&&(b=c.webkitGetAsEntry())?b.isFile?this.addFile(c.getAsFile()):b.isDirectory?this._addFilesFromDirectory(b,b.name):void 0:null!=c.getAsFile?null==c.kind||"file"===c.kind?this.addFile(c.getAsFile()):void 0:void 0);return f},b.prototype._addFilesFromDirectory=function(a,b){var c,d,e;return c=a.createReader(),d=function(a){return"undefined"!=typeof console&&null!==console&&"function"==typeof console.log?console.log(a):void 0},(e=function(a){return function(){return c.readEntries(function(c){var d,f,g;if(c.length>0){for(f=0,g=c.length;g>f;f++)d=c[f],d.isFile?d.file(function(c){return a.options.ignoreHiddenFiles&&"."===c.name.substring(0,1)?void 0:(c.fullPath=""+b+"/"+c.name,a.addFile(c))}):d.isDirectory&&a._addFilesFromDirectory(d,""+b+"/"+d.name);e()}return null},d)}}(this))()},b.prototype.accept=function(a,c){return a.size>1024*this.options.maxFilesize*1024?c(this.options.dictFileTooBig.replace("{{filesize}}",Math.round(a.size/1024/10.24)/100).replace("{{maxFilesize}}",this.options.maxFilesize)):b.isValidFile(a,this.options.acceptedFiles)?null!=this.options.maxFiles&&this.getAcceptedFiles().length>=this.options.maxFiles?(c(this.options.dictMaxFilesExceeded.replace("{{maxFiles}}",this.options.maxFiles)),this.emit("maxfilesexceeded",a)):this.options.accept.call(this,a,c):c(this.options.dictInvalidFileType)},b.prototype.addFile=function(a){return a.upload={progress:0,total:a.size,bytesSent:0},this.files.push(a),a.status=b.ADDED,this.emit("addedfile",a),this._enqueueThumbnail(a),this.accept(a,function(b){return function(c){return c?(a.accepted=!1,b._errorProcessing([a],c)):(a.accepted=!0,b.options.autoQueue&&b.enqueueFile(a)),b._updateMaxFilesReachedClass()}}(this))},b.prototype.enqueueFiles=function(a){var b,c,d;for(c=0,d=a.length;d>c;c++)b=a[c],this.enqueueFile(b);return null},b.prototype.enqueueFile=function(a){if(a.status!==b.ADDED||a.accepted!==!0)throw new Error("This file can't be queued because it has already been processed or was rejected.");return a.status=b.QUEUED,this.options.autoProcessQueue?setTimeout(function(a){return function(){return a.processQueue()}}(this),0):void 0},b.prototype._thumbnailQueue=[],b.prototype._processingThumbnail=!1,b.prototype._enqueueThumbnail=function(a){return this.options.createImageThumbnails&&a.type.match(/image.*/)&&a.size<=1024*this.options.maxThumbnailFilesize*1024?(this._thumbnailQueue.push(a),setTimeout(function(a){return function(){return a._processThumbnailQueue()}}(this),0)):void 0},b.prototype._processThumbnailQueue=function(){return this._processingThumbnail||0===this._thumbnailQueue.length?void 0:(this._processingThumbnail=!0,this.createThumbnail(this._thumbnailQueue.shift(),function(a){return function(){return a._processingThumbnail=!1,a._processThumbnailQueue()}}(this)))},b.prototype.removeFile=function(a){return a.status===b.UPLOADING&&this.cancelUpload(a),this.files=j(this.files,a),this.emit("removedfile",a),0===this.files.length?this.emit("reset"):void 0},b.prototype.removeAllFiles=function(a){var c,d,e,f;for(null==a&&(a=!1),f=this.files.slice(),d=0,e=f.length;e>d;d++)c=f[d],(c.status!==b.UPLOADING||a)&&this.removeFile(c);return null},b.prototype.createThumbnail=function(a,b){var c;return c=new FileReader,c.onload=function(d){return function(){return"image/svg+xml"===a.type?(d.emit("thumbnail",a,c.result),void(null!=b&&b())):d.createThumbnailFromUrl(a,c.result,b)}}(this),c.readAsDataURL(a)},b.prototype.createThumbnailFromUrl=function(a,b,c,d){var e;return e=document.createElement("img"),d&&(e.crossOrigin=d),e.onload=function(b){return function(){var d,f,g,i,j,k,l,m;return a.width=e.width,a.height=e.height,g=b.options.resize.call(b,a),null==g.trgWidth&&(g.trgWidth=g.optWidth),null==g.trgHeight&&(g.trgHeight=g.optHeight),d=document.createElement("canvas"),f=d.getContext("2d"),d.width=g.trgWidth,d.height=g.trgHeight,h(f,e,null!=(j=g.srcX)?j:0,null!=(k=g.srcY)?k:0,g.srcWidth,g.srcHeight,null!=(l=g.trgX)?l:0,null!=(m=g.trgY)?m:0,g.trgWidth,g.trgHeight),i=d.toDataURL("image/png"),b.emit("thumbnail",a,i),null!=c?c():void 0}}(this),null!=c&&(e.onerror=c),e.src=b},b.prototype.processQueue=function(){var a,b,c,d;if(b=this.options.parallelUploads,c=this.getUploadingFiles().length,a=c,!(c>=b)&&(d=this.getQueuedFiles(),d.length>0)){if(this.options.uploadMultiple)return this.processFiles(d.slice(0,b-c));for(;b>a;){if(!d.length)return;this.processFile(d.shift()),a++}}},b.prototype.processFile=function(a){return this.processFiles([a])},b.prototype.processFiles=function(a){var c,d,e;for(d=0,e=a.length;e>d;d++)c=a[d],c.processing=!0,c.status=b.UPLOADING,this.emit("processing",c);return this.options.uploadMultiple&&this.emit("processingmultiple",a),this.uploadFiles(a)},b.prototype._getFilesWithXhr=function(a){var b,c;return c=function(){var c,d,e,f;for(e=this.files,f=[],c=0,d=e.length;d>c;c++)b=e[c],b.xhr===a&&f.push(b);return f}.call(this)},b.prototype.cancelUpload=function(a){var c,d,e,f,g,h,i;if(a.status===b.UPLOADING){for(d=this._getFilesWithXhr(a.xhr),e=0,g=d.length;g>e;e++)c=d[e],c.status=b.CANCELED;for(a.xhr.abort(),f=0,h=d.length;h>f;f++)c=d[f],this.emit("canceled",c);this.options.uploadMultiple&&this.emit("canceledmultiple",d)}else((i=a.status)===b.ADDED||i===b.QUEUED)&&(a.status=b.CANCELED,this.emit("canceled",a),this.options.uploadMultiple&&this.emit("canceledmultiple",[a]));return this.options.autoProcessQueue?this.processQueue():void 0},e=function(){var a,b;return b=arguments[0],a=2<=arguments.length?k.call(arguments,1):[],"function"==typeof b?b.apply(this,a):b},b.prototype.uploadFile=function(a){return this.uploadFiles([a])},b.prototype.uploadFiles=function(a){var d,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L;for(w=new XMLHttpRequest,x=0,B=a.length;B>x;x++)d=a[x],d.xhr=w;p=e(this.options.method,a),u=e(this.options.url,a),w.open(p,u,!0),w.withCredentials=!!this.options.withCredentials,s=null,g=function(b){return function(){var c,e,f;for(f=[],c=0,e=a.length;e>c;c++)d=a[c],f.push(b._errorProcessing(a,s||b.options.dictResponseError.replace("{{statusCode}}",w.status),w));return f}}(this),t=function(b){return function(c){var e,f,g,h,i,j,k,l,m;if(null!=c)for(f=100*c.loaded/c.total,g=0,j=a.length;j>g;g++)d=a[g],d.upload={progress:f,total:c.total,bytesSent:c.loaded};else{for(e=!0,f=100,h=0,k=a.length;k>h;h++)d=a[h],(100!==d.upload.progress||d.upload.bytesSent!==d.upload.total)&&(e=!1),d.upload.progress=f,d.upload.bytesSent=d.upload.total;if(e)return}for(m=[],i=0,l=a.length;l>i;i++)d=a[i],m.push(b.emit("uploadprogress",d,f,d.upload.bytesSent));return m}}(this),w.onload=function(c){return function(d){var e;if(a[0].status!==b.CANCELED&&4===w.readyState){if(s=w.responseText,w.getResponseHeader("content-type")&&~w.getResponseHeader("content-type").indexOf("application/json"))try{s=JSON.parse(s)}catch(f){d=f,s="Invalid JSON response from server."}return t(),200<=(e=w.status)&&300>e?c._finished(a,s,d):g()}}}(this),w.onerror=function(){return function(){return a[0].status!==b.CANCELED?g():void 0}}(this),r=null!=(G=w.upload)?G:w,r.onprogress=t,j={Accept:"application/json","Cache-Control":"no-cache","X-Requested-With":"XMLHttpRequest"},this.options.headers&&c(j,this.options.headers);for(h in j)i=j[h],i&&w.setRequestHeader(h,i);if(f=new FormData,this.options.params){H=this.options.params;for(o in H)v=H[o],f.append(o,v)}for(y=0,C=a.length;C>y;y++)d=a[y],this.emit("sending",d,w,f);if(this.options.uploadMultiple&&this.emit("sendingmultiple",a,w,f),"FORM"===this.element.tagName)for(I=this.element.querySelectorAll("input, textarea, select, button"),z=0,D=I.length;D>z;z++)if(l=I[z],m=l.getAttribute("name"),n=l.getAttribute("type"),"SELECT"===l.tagName&&l.hasAttribute("multiple"))for(J=l.options,A=0,E=J.length;E>A;A++)q=J[A],q.selected&&f.append(m,q.value);else(!n||"checkbox"!==(K=n.toLowerCase())&&"radio"!==K||l.checked)&&f.append(m,l.value);for(k=F=0,L=a.length-1;L>=0?L>=F:F>=L;k=L>=0?++F:--F)f.append(this._getParamName(k),a[k],this._renameFilename(a[k].name));return this.submitRequest(w,f,a)},b.prototype.submitRequest=function(a,b){return a.send(b)},b.prototype._finished=function(a,c,d){var e,f,g;for(f=0,g=a.length;g>f;f++)e=a[f],e.status=b.SUCCESS,this.emit("success",e,c,d),this.emit("complete",e);return this.options.uploadMultiple&&(this.emit("successmultiple",a,c,d),this.emit("completemultiple",a)),this.options.autoProcessQueue?this.processQueue():void 0},b.prototype._errorProcessing=function(a,c,d){var e,f,g;for(f=0,g=a.length;g>f;f++)e=a[f],e.status=b.ERROR,this.emit("error",e,c,d),this.emit("complete",e);return this.options.uploadMultiple&&(this.emit("errormultiple",a,c,d),this.emit("completemultiple",a)),this.options.autoProcessQueue?this.processQueue():void 0},b}(d),c.version="4.3.0",c.options={},c.optionsForElement=function(a){return a.getAttribute("id")?c.options[e(a.getAttribute("id"))]:void 0},c.instances=[],c.forElement=function(a){if("string"==typeof a&&(a=document.querySelector(a)),null==(null!=a?a.dropzone:void 0))throw new Error("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone.");return a.dropzone},c.autoDiscover=!0,c.discover=function(){var a,b,d,e,f,g;for(document.querySelectorAll?d=document.querySelectorAll(".dropzone"):(d=[],a=function(a){var b,c,e,f;for(f=[],c=0,e=a.length;e>c;c++)b=a[c],f.push(/(^| )dropzone($| )/.test(b.className)?d.push(b):void 0);return f},a(document.getElementsByTagName("div")),a(document.getElementsByTagName("form"))),g=[],e=0,f=d.length;f>e;e++)b=d[e],g.push(c.optionsForElement(b)!==!1?new c(b):void 0);return g},c.blacklistedBrowsers=[/opera.*Macintosh.*version\/12/i],c.isBrowserSupported=function(){var a,b,d,e,f;if(a=!0,window.File&&window.FileReader&&window.FileList&&window.Blob&&window.FormData&&document.querySelector)if("classList"in document.createElement("a"))for(f=c.blacklistedBrowsers,d=0,e=f.length;e>d;d++)b=f[d],b.test(navigator.userAgent)&&(a=!1);else a=!1;else a=!1;return a},j=function(a,b){var c,d,e,f;for(f=[],d=0,e=a.length;e>d;d++)c=a[d],c!==b&&f.push(c);return f},e=function(a){return a.replace(/[\-_](\w)/g,function(a){return a.charAt(1).toUpperCase()})},c.createElement=function(a){var b;return b=document.createElement("div"),b.innerHTML=a,b.childNodes[0]},c.elementInside=function(a,b){if(a===b)return!0;for(;a=a.parentNode;)if(a===b)return!0;return!1},c.getElement=function(a,b){var c;if("string"==typeof a?c=document.querySelector(a):null!=a.nodeType&&(c=a),null==c)throw new Error("Invalid `"+b+"` option provided. Please provide a CSS selector or a plain HTML element.");return c},c.getElements=function(a,b){var c,d,e,f,g,h,i,j;if(a instanceof Array){e=[];try{for(f=0,h=a.length;h>f;f++)d=a[f],e.push(this.getElement(d,b))}catch(k){c=k,e=null}}else if("string"==typeof a)for(e=[],j=document.querySelectorAll(a),g=0,i=j.length;i>g;g++)d=j[g],e.push(d);else null!=a.nodeType&&(e=[a]);if(null==e||!e.length)throw new Error("Invalid `"+b+"` option provided. Please provide a CSS selector, a plain HTML element or a list of those.");return e},c.confirm=function(a,b,c){return window.confirm(a)?b():null!=c?c():void 0},c.isValidFile=function(a,b){var c,d,e,f,g;if(!b)return!0;for(b=b.split(","),d=a.type,c=d.replace(/\/.*$/,""),f=0,g=b.length;g>f;f++)if(e=b[f],e=e.trim(),"."===e.charAt(0)){if(-1!==a.name.toLowerCase().indexOf(e.toLowerCase(),a.name.length-e.length))return!0
}else if(/\/\*$/.test(e)){if(c===e.replace(/\/.*$/,""))return!0}else if(d===e)return!0;return!1},"undefined"!=typeof a&&null!==a&&(a.fn.dropzone=function(a){return this.each(function(){return new c(this,a)})}),"undefined"!=typeof b&&null!==b?b.exports=c:window.Dropzone=c,c.ADDED="added",c.QUEUED="queued",c.ACCEPTED=c.QUEUED,c.UPLOADING="uploading",c.PROCESSING=c.UPLOADING,c.CANCELED="canceled",c.ERROR="error",c.SUCCESS="success",g=function(a){var b,c,d,e,f,g,h,i,j,k;for(h=a.naturalWidth,g=a.naturalHeight,c=document.createElement("canvas"),c.width=1,c.height=g,d=c.getContext("2d"),d.drawImage(a,0,0),e=d.getImageData(0,0,1,g).data,k=0,f=g,i=g;i>k;)b=e[4*(i-1)+3],0===b?f=i:k=i,i=f+k>>1;return j=i/g,0===j?1:j},h=function(a,b,c,d,e,f,h,i,j,k){var l;return l=g(b),a.drawImage(b,c,d,e,f,h,i,j,k/l)},f=function(a,b){var c,d,e,f,g,h,i,j,k;if(e=!1,k=!0,d=a.document,j=d.documentElement,c=d.addEventListener?"addEventListener":"attachEvent",i=d.addEventListener?"removeEventListener":"detachEvent",h=d.addEventListener?"":"on",f=function(c){return"readystatechange"!==c.type||"complete"===d.readyState?(("load"===c.type?a:d)[i](h+c.type,f,!1),!e&&(e=!0)?b.call(a,c.type||c):void 0):void 0},g=function(){var a;try{j.doScroll("left")}catch(b){return a=b,void setTimeout(g,50)}return f("poll")},"complete"!==d.readyState){if(d.createEventObject&&j.doScroll){try{k=!a.frameElement}catch(l){}k&&g()}return d[c](h+"DOMContentLoaded",f,!1),d[c](h+"readystatechange",f,!1),a[c](h+"load",f,!1)}},c._autoDiscoverFunction=function(){return c.autoDiscover?c.discover():void 0},f(window,c._autoDiscoverFunction)}.call(this),b.exports});;

/************************************************************

	Main Scripts

*************************************************************/

!(function ($) {
    'use strict';

    // Global Onyx object
    var Onyx = Onyx || {};

    Onyx = {
        /**
         * Fire all functions
         */
        init: function () {
            var self = this,
                obj;

            for (obj in self) {
                if (self.hasOwnProperty(obj)) {
                    var _method = self[obj];
                    if (_method.selector !== undefined && _method.init !== undefined) {
                        if ($(_method.selector).length > 0) {
                            _method.init();
                        }
                    }
                }
            }
        },

        /**
         * Files upload
         */
        userFilesDropzone: {
            selector: 'form.dropzone',
            init: function () {
                var base = this,
                    container = $(base.selector);

                base.initFileUploader(base, 'form.dropzone');
            },
            initFileUploader: function (base, target) {
                var previewNode = document.querySelector('#onyx-dropzone-template'), // Dropzone template holder
                    warningsHolder = $('#warnings'); // Warning messages' holder

                previewNode.id = '';

                var previewTemplate = previewNode.parentNode.innerHTML;
                previewNode.parentNode.removeChild(previewNode);

                var onyxDropzone = new Dropzone(target, {
                    url: $(target).attr('action') ? $(target).attr('action') : '../../file-upload.php', // Check that our form has an action attr and if not, set one here
                    maxFiles: 5,
                    maxFilesize: 20,
                    acceptedFiles:
                        'image/*,application/pdf,.doc,.docx,.xls,.xlsx,.csv,.tsv,.ppt,.pptx,.pages,.odt,.rtf',
                    previewTemplate: previewTemplate,
                    previewsContainer: '#previews',
                    clickable: true,

                    createImageThumbnails: true,

                    /**
                     * The text used before any files are dropped.
                     */
                    dictDefaultMessage: 'Drop files here to upload.', // Default: Drop files here to upload

                    /**
                     * The text that replaces the default message text it the browser is not supported.
                     */
                    dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.", // Default: Your browser does not support drag'n'drop file uploads.

                    /**
                     * If the filesize is too big.
                     * `{{filesize}}` and `{{maxFilesize}}` will be replaced with the respective configuration values.
                     */
                    dictFileTooBig: 'File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.', // Default: File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.

                    /**
                     * If the file doesn't match the file type.
                     */
                    dictInvalidFileType: "You can't upload files of this type.", // Default: You can't upload files of this type.

                    /**
                     * If the server response was invalid.
                     * `{{statusCode}}` will be replaced with the servers status code.
                     */
                    dictResponseError: 'Server responded with {{statusCode}} code.', // Default: Server responded with {{statusCode}} code.

                    /**
                     * If `addRemoveLinks` is true, the text to be used for the cancel upload link.
                     */
                    dictCancelUpload: 'Cancel upload.', // Default: Cancel upload

                    /**
                     * The text that is displayed if an upload was manually canceled
                     */
                    dictUploadCanceled: 'Upload canceled.', // Default: Upload canceled.

                    /**
                     * If `addRemoveLinks` is true, the text to be used for confirmation when cancelling upload.
                     */
                    dictCancelUploadConfirmation: 'Are you sure you want to cancel this upload?', // Default: Are you sure you want to cancel this upload?

                    /**
                     * If `addRemoveLinks` is true, the text to be used to remove a file.
                     */
                    dictRemoveFile: 'Remove file', // Default: Remove file

                    /**
                     * If this is not null, then the user will be prompted before removing a file.
                     */
                    dictRemoveFileConfirmation: null, // Default: null

                    /**
                     * Displayed if `maxFiles` is st and exceeded.
                     * The string `{{maxFiles}}` will be replaced by the configuration value.
                     */
                    dictMaxFilesExceeded: 'You can not upload any more files.', // Default: You can not upload any more files.

                    /**
                     * Allows you to translate the different units. Starting with `tb` for terabytes and going down to
                     * `b` for bytes.
                     */
                    dictFileSizeUnits: { tb: 'TB', gb: 'GB', mb: 'MB', kb: 'KB', b: 'b' }
                });

                Dropzone.autoDiscover = false;

                onyxDropzone.on('addedfile', function (file) {
                    $('.preview-container').css('visibility', 'visible');
                    file.previewElement.classList.add('type-' + base.fileType(file.name)); // Add type class for this element's preview
                });

                onyxDropzone.on('totaluploadprogress', function (progress) {
                    var progr = document.querySelector('.progress .determinate');

                    if (progr === undefined || progr === null) return;

                    progr.style.width = progress + '%';
                });

                onyxDropzone.on('dragenter', function () {
                    $(target).addClass('hover');
                });

                onyxDropzone.on('dragleave', function () {
                    $(target).removeClass('hover');
                });

                onyxDropzone.on('drop', function () {
                    $(target).removeClass('hover');
                });

                onyxDropzone.on('addedfile', function () {
                    // Remove no files notice
                    $('.no-files-uploaded').slideUp('easeInExpo');
                });

                onyxDropzone.on('removedfile', function (file) {
                    $.ajax({
                        type: 'POST',
                        url: $(target).attr('action') ? $(target).attr('action') : '../../file-upload.php',
                        data: {
                            target_file: file.upload_ticket,
                            delete_file: 1
                        }
                    });

                    // Show no files notice
                    if (base.dropzoneCount() == 0) {
                        $('.no-files-uploaded').slideDown('easeInExpo');
                        $('.uploaded-files-count').html(base.dropzoneCount());
                    }
                });

                onyxDropzone.on('success', function (file, response) {
                    let parsedResponse = JSON.parse(response);
                    file.upload_ticket = parsedResponse.file_link;

                    // Make it wait a little bit to take the new element
                    setTimeout(function () {
                        $('.uploaded-files-count').html(base.dropzoneCount());
                        console.log('Files count: ' + base.dropzoneCount());
                    }, 350);

                    // Something to happen when file is uploaded, like showing a message
                    if (typeof parsedResponse.info !== 'undefined') {
                        console.log(parsedResponse.info);
                        warningsHolder.children('span').html(parsedResponse.info);
                        warningsHolder.slideDown('easeInExpo');
                    }
                });
            },
            dropzoneCount: function () {
                var filesCount = $('#previews > .dz-success.dz-complete').length;
                return filesCount;
            },
            fileType: function (fileName) {
                var fileType = /[.]/.exec(fileName) ? /[^.]+$/.exec(fileName) : undefined;
                return fileType[0];
            }
        }
    };

    $(document).ready(function () {
        Onyx.init();
    });
})(jQuery);
;
!function (t) { "use strict"; "function" == typeof define && define.amd ? define(["jquery"], t) : "object" == typeof exports ? module.exports = t(require("jquery")) : t(jQuery) }(function (t) { "use strict"; Number.isNaN = Number.isNaN || function (t) { return "number" == typeof t && t != t }; var i, e = "rangeslider", n = 0, s = ((i = document.createElement("input")).setAttribute("type", "range"), "text" !== i.type), o = { polyfill: !0, orientation: "horizontal", rangeClass: "rangeslider", disabledClass: "rangeslider--disabled", activeClass: "rangeslider--active", horizontalClass: "rangeslider--horizontal", verticalClass: "rangeslider--vertical", fillClass: "rangeslider__fill", handleClass: "rangeslider__handle", startEvent: ["mousedown", "touchstart", "pointerdown"], moveEvent: ["mousemove", "touchmove", "pointermove"], endEvent: ["mouseup", "touchend", "pointerup"] }, r = { orientation: { horizontal: { dimension: "width", direction: "left", directionStyle: "left", coordinate: "x" }, vertical: { dimension: "height", direction: "top", directionStyle: "bottom", coordinate: "y" } } }; function h(t) { return t && (0 === t.offsetWidth || 0 === t.offsetHeight || !1 === t.open) } function a(t, i) { var e = function (t) { for (var i = [], e = t.parentNode; h(e);)i.push(e), e = e.parentNode; return i }(t), n = e.length, s = [], o = t[i]; function r(t) { void 0 !== t.open && (t.open = !t.open) } if (n) { for (var a = 0; a < n; a++)s[a] = e[a].style.cssText, e[a].style.setProperty ? e[a].style.setProperty("display", "block", "important") : e[a].style.cssText += ";display: block !important", e[a].style.height = "0", e[a].style.overflow = "hidden", e[a].style.visibility = "hidden", r(e[a]); o = t[i]; for (var l = 0; l < n; l++)e[l].style.cssText = s[l], r(e[l]) } return o } function l(t, i) { var e = parseFloat(t); return Number.isNaN(e) ? i : e } function d(t) { return t.charAt(0).toUpperCase() + t.substr(1) } function u(i, h) { if (this.$window = t(window), this.$document = t(document), this.$element = t(i), this.options = t.extend({}, o, h), this.polyfill = this.options.polyfill, this.orientation = this.$element[0].getAttribute("data-orientation") || this.options.orientation, this.onInit = this.options.onInit, this.onSlide = this.options.onSlide, this.onSlideEnd = this.options.onSlideEnd, this.DIMENSION = r.orientation[this.orientation].dimension, this.DIRECTION = r.orientation[this.orientation].direction, this.DIRECTION_STYLE = r.orientation[this.orientation].directionStyle, this.COORDINATE = r.orientation[this.orientation].coordinate, this.polyfill && s) return !1; this.identifier = "js-" + e + "-" + n++, this.startEvent = this.options.startEvent.join("." + this.identifier + " ") + "." + this.identifier, this.moveEvent = this.options.moveEvent.join("." + this.identifier + " ") + "." + this.identifier, this.endEvent = this.options.endEvent.join("." + this.identifier + " ") + "." + this.identifier, this.toFixed = (this.step + "").replace(".", "").length - 1, this.$fill = t('<div class="' + this.options.fillClass + '" />'), this.$handle = t('<div class="' + this.options.handleClass + '" />'), this.$range = t('<div class="' + this.options.rangeClass + " " + this.options[this.orientation + "Class"] + '" id="' + this.identifier + '" />').insertAfter(this.$element).prepend(this.$fill, this.$handle), this.$element.css({ position: "absolute", width: "1px", height: "1px", overflow: "hidden", opacity: "0" }), this.handleDown = t.proxy(this.handleDown, this), this.handleMove = t.proxy(this.handleMove, this), this.handleEnd = t.proxy(this.handleEnd, this), this.init(); var a, l, d = this; this.$window.on("resize." + this.identifier, (a = function () { !function (t, i) { var e = Array.prototype.slice.call(arguments, 2); setTimeout(function () { return t.apply(null, e) }, i) }(function () { d.update(!1, !1) }, 300) }, l = (l = 20) || 100, function () { if (!a.debouncing) { var t = Array.prototype.slice.apply(arguments); a.lastReturnVal = a.apply(window, t), a.debouncing = !0 } return clearTimeout(a.debounceTimeout), a.debounceTimeout = setTimeout(function () { a.debouncing = !1 }, l), a.lastReturnVal })), this.$document.on(this.startEvent, "#" + this.identifier + ":not(." + this.options.disabledClass + ")", this.handleDown), this.$element.on("change." + this.identifier, function (t, i) { if (!i || i.origin !== d.identifier) { var e = t.target.value, n = d.getPositionFromValue(e); d.setPosition(n) } }) } return u.prototype.init = function () { this.update(!0, !1), this.onInit && "function" == typeof this.onInit && this.onInit() }, u.prototype.update = function (t, i) { (t = t || !1) && (this.min = l(this.$element[0].getAttribute("min"), 0), this.max = l(this.$element[0].getAttribute("max"), 100), this.value = l(this.$element[0].value, Math.round(this.min + (this.max - this.min) / 2)), this.step = l(this.$element[0].getAttribute("step"), 1)), this.handleDimension = a(this.$handle[0], "offset" + d(this.DIMENSION)), this.rangeDimension = a(this.$range[0], "offset" + d(this.DIMENSION)), this.maxHandlePos = this.rangeDimension - this.handleDimension, this.grabPos = this.handleDimension / 2, this.position = this.getPositionFromValue(this.value), this.$element[0].disabled ? this.$range.addClass(this.options.disabledClass) : this.$range.removeClass(this.options.disabledClass), this.setPosition(this.position, i) }, u.prototype.handleDown = function (t) { if (t.preventDefault(), this.$element.focus(), !(t.button && 0 !== t.button || (this.$document.on(this.moveEvent, this.handleMove), this.$document.on(this.endEvent, this.handleEnd), this.$range.addClass(this.options.activeClass), (" " + t.target.className + " ").replace(/[\n\t]/g, " ").indexOf(this.options.handleClass) > -1))) { var i = this.getRelativePosition(t), e = this.$range[0].getBoundingClientRect()[this.DIRECTION], n = this.getPositionFromNode(this.$handle[0]) - e, s = "vertical" === this.orientation ? this.maxHandlePos - (i - this.grabPos) : i - this.grabPos; this.setPosition(s), i >= n && i < n + this.handleDimension && (this.grabPos = i - n) } }, u.prototype.handleMove = function (t) { t.preventDefault(); var i = this.getRelativePosition(t), e = "vertical" === this.orientation ? this.maxHandlePos - (i - this.grabPos) : i - this.grabPos; this.setPosition(e) }, u.prototype.handleEnd = function (t) { t.preventDefault(), this.$document.off(this.moveEvent, this.handleMove), this.$document.off(this.endEvent, this.handleEnd), this.$range.removeClass(this.options.activeClass), this.$element.trigger("change", { origin: this.identifier }), this.onSlideEnd && "function" == typeof this.onSlideEnd && this.onSlideEnd(this.position, this.value) }, u.prototype.cap = function (t, i, e) { return t < i ? i : t > e ? e : t }, u.prototype.setPosition = function (t, i) { var e, n; void 0 === i && (i = !0), e = this.getValueFromPosition(this.cap(t, 0, this.maxHandlePos)), n = this.getPositionFromValue(e), this.$fill[0].style[this.DIMENSION] = n + this.grabPos + "px", this.$handle[0].style[this.DIRECTION_STYLE] = n + "px", this.setValue(e), this.position = n, this.value = e, i && this.onSlide && "function" == typeof this.onSlide && this.onSlide(n, e) }, u.prototype.getPositionFromNode = function (t) { for (var i = 0; null !== t;)i += t.offsetLeft, t = t.offsetParent; return i }, u.prototype.getRelativePosition = function (t) { var i = d(this.COORDINATE), e = this.$range[0].getBoundingClientRect()[this.DIRECTION], n = 0; return void 0 !== t.originalEvent["client" + i] ? n = t.originalEvent["client" + i] : t.originalEvent.touches && t.originalEvent.touches[0] && void 0 !== t.originalEvent.touches[0]["client" + i] ? n = t.originalEvent.touches[0]["client" + i] : t.currentPoint && void 0 !== t.currentPoint[this.COORDINATE] && (n = t.currentPoint[this.COORDINATE]), n - e }, u.prototype.getPositionFromValue = function (t) { var i; return i = (t - this.min) / (this.max - this.min), Number.isNaN(i) ? 0 : i * this.maxHandlePos }, u.prototype.getValueFromPosition = function (t) { var i, e; return i = t / (this.maxHandlePos || 1), e = this.step * Math.round(i * (this.max - this.min) / this.step) + this.min, Number(e.toFixed(this.toFixed)) }, u.prototype.setValue = function (t) { t === this.value && "" !== this.$element[0].value || this.$element.val(t).trigger("input", { origin: this.identifier }) }, u.prototype.destroy = function () { this.$document.off("." + this.identifier), this.$window.off("." + this.identifier), this.$element.off("." + this.identifier).removeAttr("style").removeData("plugin_" + e), this.$range && this.$range.length && this.$range[0].parentNode.removeChild(this.$range[0]) }, t.fn[e] = function (i) { var n = Array.prototype.slice.call(arguments, 1); return this.each(function () { var s = t(this), o = s.data("plugin_" + e); o || s.data("plugin_" + e, o = new u(this, i)), "string" == typeof i && o[i].apply(o, n) }) }, "rangeslider.js is available in jQuery context e.g $(selector).rangeslider(options);" });;
(function ($) {
    Site.LifeFormExperience = (function () {
        var _debug = !/^www/.test($(location).attr('hostname'));
        var genericFormExperienceScript = new Site.Form();

        return {
            Initialize: function (formSelector) {                
                genericFormExperienceScript.Initialize(formSelector, { onSubmitOverride: onLifeFormSubmit });
                $('[data-toggle="tooltip"]').tooltip();
                $('span.field-validation-error').show();
                $('#AarpMemberYes, #AarpMemberNo').click(function() {
                    Site.LifeFormExperience.ToggleMembership();
                });
                $("#AarpMember").on('change', function () {
                    Site.LifeFormExperience.ShowMemberDueText(this);

                });

                Site.LifeFormExperience.BindEventHandlers();
                Site.LifeFormExperience.ToggleMembership();
                Site.LifeFormExperience.ValidateFormWhenPrefilled(formSelector);
            }, 
            ToggleMembership: function (control) {
                let _val = $("input[name='AarpMember']:checked").val();
                if (_val === 'Y') {
                    $('#IsNotAarpMember').hide();
                    if ($('#IsAarpMember').length)
                        $('#IsAarpMember').show();
                } else if (_val === 'N') {
                    if ($('#IsAarpMember').length)
                        $('#IsAarpMember').hide();
                    $('#IsNotAarpMember').show();
                } 
            },
            ValidateFormWhenPrefilled: function (formSelector) {
                var isFormPrefilled = getUrlParameter("lg");
                if (isFormPrefilled) {
                    $(formSelector).valid();
                }
            },

            ShowMemberDueText: function (control) {
               let val = $(control).val();
                
                if (val === 'N')
                    $("#lblNonMember").removeClass("d-none");
                else if (val === 'Y')
                    $("#lblNonMember").addClass("d-none");
            },

            BindEventHandlers: function() {
                $('body').on('nyl:checkPlan', function(event, fieldName) {
                    _log("Handling nyl:checkPlan trigger for " + fieldName);
                    event.stopImmediatePropagation();
                    let state = $('#State').val();
                    let productType = $('#Product_ProductType').val();
                    let url = '/ddk/lead/ProductResult';
                    let tobaccoQuestion = $('.tobaccoQuestion');
                    if (state) {
                        $.getJSON(url, { 'state': state, 'productType': productType }, function(result) {
                            if (result.TobaccoEnabled === 'Y') {
                                tobaccoQuestion.show();
                            } else {
                                tobaccoQuestion.hide();
                            }
                        });
                    }
                });

                $('#State').change(function() {
                    _log("Stage changed - triggering nyl:checkPlan");
                    $('body').trigger('nyl:checkPlan', 'state');
                });
            }
        };

        function _log(s) {
            if (_debug && /chrom(e|ium)/.test(navigator.userAgent.toLowerCase()))
                console.log(s);
        }
        function onLifeFormSubmit(formSelector) {
            _log(">> onLifeFormSubmit [" + formSelector + "]");
            $(formSelector).submit(function (event) {
                $('span.field-validation-error').show();
               
                if ($(this).valid()) {
                    Site.Form().toggleSpinner();
                    Site.Form().ToggleButtonProcessing(jQuery('.btn[type=submit]'));
                    return true;
                }
            });
        }


    })();
})(jQuery);

function postQuoteCTA() {
    $("#lf-kit").submit();
};
$(document).ready(function () {
    var formSelector = "#claimsForm";

    if ($(formSelector).length) {

        Site.Form().Initialize(formSelector, { onSubmitOverride: onClaimsFormSubmit });

        function onClaimsFormSubmit(formSelector) {
            $(formSelector).submit(function () {
                if ($(this).valid()) {
                    const spinner = '<span class="spinner-border spinner-border-sm text-light ml-3 d-inline-block" role="status" aria-hidden="true"></span><span class="sr-only">Loading...</span>';
                    var button = $(this).find('button[type="submit"]')
                    button.html(button.html() + spinner).prop("disabled", true);
                }
            });
        }

        function showAsterisk(labelId) {
            var label = $("#" + labelId);
            if (label) {
                var content = label.html().endsWith('*') ? label.html() : label.html().concat("*");
                label.html(content);
            }
        }

        function hideAsterisk(labelId) {
            var label = $("#" + labelId);
            if (label) {
                var content = label.html().replace("*", "");
                label.html(content);
            }
        }

        $("select[name=MannerOfDeath]").change(function () {
            if ($(this).val() == "Diseases_or_Illness") {
                showAsterisk("lblCauseOfDeath");
            }
            else {
                hideAsterisk("lblCauseOfDeath");
            }
        });


        $("input[name=BeneficiaryCountry]").change(function () {
            if ($(this).val() == "United_States_of_America") {
                showAsterisk("lblBeneficiaryStreetAddress");
                showAsterisk("lblBeneficiaryCity");
                showAsterisk("lblBeneficiaryState");
                showAsterisk("lblBeneficiaryZipCode");
            }
            else {
                hideAsterisk("lblBeneficiaryStreetAddress");
                hideAsterisk("lblBeneficiaryCity");
                hideAsterisk("lblBeneficiaryState");
                hideAsterisk("lblBeneficiaryZipCode");
                $("select[name=BeneficiaryState]").val("");
            }
        });



        $("select[name=LocationOfDeath]").change(function () {
            $("input[name=LocationOfDeathOutsideUS]").prop("checked", false);
        });

        $("input[name=LocationOfDeathOutsideUS]").click(function () {
            $("select[name=LocationOfDeath]").val("");
        });

        $("#add_bene_address_2").click(function () {
            $("#add_bene_address_2_row").hide();
            $("#bene_address_2_row").show();
        });

        $("#add_fh_address_2").click(function () {
            $("#add_fh_address_2_row").hide();
            $("#fh_address_2_row").show();
        });

        $("input[name='IncTaxCertSelection']").change(function () {
            if ($(this).val() == "Individual_beneficiary") {
                $("#ssn_group").show();
                $("#ein_group").hide();
                $("#inctaxcertcapacity_row .individual-radio").show();
                $("#inctaxcertcapacity_row .estate-radio").hide();
                $("#inctaxcertcapacity_row").show();
            }
            if ($(this).val() == "Estate_Trust_or_Corporation") {
                $("#ssn_group").hide();
                $("#ein_group").show();
                $("#inctaxcertcapacity_row .individual-radio").hide();
                $("#inctaxcertcapacity_row .estate-radio").show();
                $("#inctaxcertcapacity_row").show();
            }
        });

        $("input[name='FHProceeds']").change(function () {
            if ($(this).val() == "Beneficiary") {
                $("#FHProceeds_SSN").show();
                $("#FHProceeds_EIN").hide();
            }
            if ($(this).val() == "Funeral_Home") {
                $("#FHProceeds_SSN").hide();
                $("#FHProceeds_EIN").show();
            }
        });

    }
});;
(function ($) {
    Site.LTCFormExperience = (function () {
        var _debug = !/^www/.test($(location).attr('hostname'));
        var genericFormExperienceScript = new Site.Form();

        return {
            Initialize: function (formSelector) {                
                genericFormExperienceScript.Initialize(formSelector, { onSubmitOverride: onLtcFormSubmit });
            }
        };

        function _log(s) {
            if (_debug && /chrom(e|ium)/.test(navigator.userAgent.toLowerCase()))
                console.log(s);
        }
        function onLtcFormSubmit(formSelector) {
            _log(">> onLtcFormSubmit [" + formSelector + "]");
            $(formSelector).submit(function (event) {                
                $('span.field-validation-error').show();
                if ($(this).valid()) {
                    Site.Form().toggleSpinner();
                    Site.Form().ToggleButtonProcessing(jQuery('.btn[type=submit]'));
                    return true;
                }
            });
        }


    })();
})(jQuery);;
(function($) {
    Site.PasswordComplexity = (function() {
        var minPasswordLength = 8;
        var maxPasswordLength = 20;

        var _hasLowerCase = /[a-z]/;
        var _hasUpperCase = /[A-Z]/;
        var _hasDigit = /\d/;
        var _hasSpecial = /([.,:;\[\]^_\{\}\-\?\*\#|\~\@$!%&\(\)\+\=])/;

        var password = [];

        var hasEightCharsListItem,
            hasUpperCaseListItem,
            hasLowerCaseListItem,
            hasSpecialListItem,
            hasDigitListItem;
        return {
            checkAndSwitchClasses: function (has, $element) {
                if (has) {
                    $element.find(".fa-circle").removeClass("fa-circle").addClass("fa-check");
                    $element.find(".account-pwd ").removeClass('text-error').addClass('text-success');
                    return true;
                } else {
                    $element.find(".fa-check ").removeClass("fa-check").addClass("fa-circle"); // specifying font family changes the look of the icon
                    $element.find(".account-pwd ").removeClass('text-success').addClass('text-error');
                    return false;
                }
            },
            enforceRules: function () {

                $('#password-error-list').show();

                var pw = password.val().toLowerCase();

                var hasEight = (pw.length >= minPasswordLength && pw.length <= maxPasswordLength);
                var hasLower = _hasLowerCase.test(password.val());
                var hasUpper = _hasUpperCase.test(password.val());
                var hasDigit = _hasDigit.test(password.val());
                var hasSpecial = _hasSpecial.test(password.val());

                Site.PasswordComplexity.checkAndSwitchClasses(hasEight, hasEightCharsListItem);
                Site.PasswordComplexity.checkAndSwitchClasses(hasLower, hasLowerCaseListItem);
                Site.PasswordComplexity.checkAndSwitchClasses(hasUpper, hasUpperCaseListItem);
                Site.PasswordComplexity.checkAndSwitchClasses(hasDigit, hasDigitListItem);
                Site.PasswordComplexity.checkAndSwitchClasses(hasSpecial, hasSpecialListItem);

            },
            init: function (ele) {
                password = $(ele);
                // hook all req list items
                hasEightCharsListItem = $('#req-length');
                hasUpperCaseListItem = $('#req-upper');
                hasLowerCaseListItem = $('#req-lower');
                hasSpecialListItem = $('#req-special');
                hasDigitListItem = $('#req-digit');


                $(password).bind('keyup focus input propertychange mouseup', Site.PasswordComplexity.enforceRules);
            }
        };
    })();

})(jQuery);


(function ($) {
    Site.AccountForm = (function () {
        var _debug = !/^www/.test($(location).attr('hostname'));
        var genericFormExperienceScript = new Site.Form();

        return {
            Initialize: function (formSelector) {
                genericFormExperienceScript.Initialize(formSelector, { onSubmitOverride: onAccountFormSubmit });
                $(formSelector).validate({ ignore: [] });
                jQuery('[data-toggle="tooltip"]').tooltip();
                jQuery('span.field-validation-error').show();
                jQuery('#txtDateOfBirth').mask('00/00/0000');                
                jQuery('input[data-val-autotab]').autotab();
                jQuery("input[data-val-mask]").each(function () {
                    $(this).mask($(this).attr("data-val-mask"));
                });
                Site.AccountForm.ScrollToError();

                if (formSelector == "#select-policies-form")
                {
                    $("#selectAll").click(function () {
                        var status = $("#selectAll").prop('checked');
                        $(formSelector + " input[type=checkbox]").each(function () {
                            $(this).prop("checked", status);
                        });
                    });
                    
                    $("#Policies_0__Selected").prop("checked", true);                    
                }

            },

            InitializeAjax: function (formSelector) {
                genericFormExperienceScript.Initialize(formSelector, { onSubmitOverride: onLoginFlyoutFormSubmit });
                $(formSelector).validate({ ignore: [] });
                jQuery('[data-toggle="tooltip"]').tooltip();
                jQuery('span.field-validation-error').show();
            },
            
            ToggleButtonProcessing: function (btn) {
                const spinner =
                    '<span class="spinner-border spinner-border-sm text-light ml-3 d-inline-block" role="status" aria-hidden="true"></span><span class="sr-only">Loading...</span>';
                if (btn.is(':enabled')) {
                    let _html = btn.html();
                    btn.html(_html + spinner);
                    btn.attr("disabled", "disabled");
                } else {
                    btn.find('span').remove();
                    btn.removeAttr("disabled");
                }
            },

            StopButtonProcessing: function (btn) {
                btn.find('span').remove();
                btn.removeAttr("disabled");
            },

            BindCountryToggle: function () {
                const countrySelector = ".change-address-country > select";

                $(countrySelector).change(toggleFields);
                toggleFields();

                function toggleFields() {
                    const country = $(countrySelector).val();
                    $('.change-address-toggle').hide();
                    if (country == 1) {
                        $('.change-address-state').show();
                        $('.change-address-zip').show();
                    } else if (country == 2) {
                        $('.change-address-province').show();
                        $('.change-address-postal-code').show();
                    }
                }
            },
            BindAccountToggle: function () {
                const accountSelector = ".change-type-account > select";

                $(accountSelector).change(toggleFields);
                toggleFields();

                function toggleFields() {
                    const accountType = $('input[name="SelectAccountValidation"]:checked').val();
                    $('.change-type-account').hide();                
                    if (accountType == "Contract") {
                        $('.change-type-account').show();
                        $('#txtConfirmEmail').val("");
                        $('#txtConfirmEmail').removeClass('input-validation-error');
                        var confirmE = document.getElementById("ce");
                        var confirmErrMsg = confirmE.querySelector(".field-validation-error");
                        confirmErrMsg.innerHTML = "";
                        $('#txtEmail').removeClass('input-validation-error');
                        $('#txtRegistrationPolicyNumber').removeClass('input-validation-error');
                        var confirmC = document.getElementById("cc");
                        confirmErrMsg = confirmC.querySelector(".field-validation-error");
                        confirmErrMsg.innerHTML = "";
                        confirmC = document.getElementById("cc2");
                        confirmErrMsg = confirmC.querySelector(".field-validation-error");
                        confirmErrMsg.innerHTML = ""; 
                    } else {
                        $('.change-type-account').hide();
                        $('#txtRegistrationPolicyNumber').val("");
                        $('#txtEmail').val("");
                    }
                }
            },
            BindConfirmToggle: function () {
                const accountSelector = ".confirm-processed";
                $('.confirm-succeed').hide();

                $("#SendRmail").click(function () {
                    $(accountSelector).change(toggleFields);
                    toggleFields();
                })

                function toggleFields() {
                    $('.confirm-processed').hide();
                    $('.confirm-succeed').show();
                }
            },
            Otp: function () {
                jQuery("body, .account-otp input[type='text']")
                    .bind("paste", function(e) {
                        const clip = e.originalEvent.clipboardData.getData("text");
                        jQuery("#Otp1").val(clip[0]);
                        jQuery("#Otp2").val(clip[1]);
                        jQuery("#Otp3").val(clip[2]);
                        jQuery("#Otp4").val(clip[3]);
                        jQuery("#Otp5").val(clip[4]);
                        jQuery("#Otp6").val(clip[5]);
                        e.preventDefault();
                        jQuery(".form-control").blur();
                    });

                jQuery(".account-otp input[type='text']").each(function() {
                    jQuery(this).removeClass("input-validation-error");
                    jQuery(this).val("");
                }); 

                jQuery(".account-otp").fadeIn("fast");

            },

            /*
             * Scroll to the top most validation error on the page
             */
            ScrollToError: function () {
                const firstError = jQuery('.input-validation-error').first();
                if (firstError !== undefined && firstError.length > 0) {
                    let y = firstError.closest('form').offset().top - 175;
                    jQuery("html,body").animate({ scrollTop: y }, 500);
                }
            }

        };

        function _log(s) {
            if (_debug && /chrom(e|ium)/.test(navigator.userAgent.toLowerCase()))
                console.log(s);
        }
        function onAccountFormSubmit(formSelector) {
            _log(">> onAccountFormSubmit [" + formSelector + "]");
            $(formSelector).submit(function (event) {
                $('span.field-validation-error').show();

                if ($(this).valid()) {
                    Site.AccountForm.ToggleButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));
                    toggleSpinner();
                    return true;
                }
            });
        }

        //function onLoginFlyoutFormSubmit(formSelector) {
        //    _log(">> onLoginFlyoutFormSubmit [" + formSelector + "]");
        //    $(formSelector).submit(function(event) {
        //        event.preventDefault();

        //        const validator = $(this).validate();

        //        if ($(this).valid()) {
        //            Site.AccountForm.ToggleButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));

        //            var form = $(formSelector);
        //            var url = location.pathname;

        //            $.ajax({
        //                type: "POST",
        //                url: url,
        //                data: form.serialize(),
        //                success: function (data) {
        //                    if (data.RedirectUrl) {
        //                        document.location.href = data.RedirectUrl;
        //                    } else {
        //                        let fv = $(formSelector).validate();
        //                        fv.errorList.push({
        //                            message: data.Message,
        //                            element: $(formSelector + " #txtUsername")[0]
        //                        });
        //                        fv.errorList.push({
        //                            message: data.Message,
        //                            element: $(formSelector + " #Password")[0]
        //                        });

        //                        fv.showErrors();

        //                        $("[data-valmsg-for='Username']").addClass("field-validation-error").html('<span id="txtUsername-error">' + data.Message + '</span>');
        //                        $("[data-valmsg-for='Password']").addClass("field-validation-error").html('<span id="Password-error">' + data.Message + '</span>');

        //                        $(formSelector + ' #txtUsername').val('');
        //                        $(formSelector + ' #Password').val('');
        //                        Site.AccountForm.ToggleButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));
        //                    }
        //                },
        //                failure: function() {
        //                    Site.AccountForm.ToggleButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));
        //                    document.location.href = '/Account/Login/Invalid?Reason=Error';
        //                }
        //            });
        //        }
        //    });
        //}
    })();
})(jQuery);;
(function ($) {
    Site.Coverage = (function() {
        var _debug = !/^www/.test($(location).attr("hostname"));
        var genericFormExperienceScript = new Site.Form();
        let deleteBeneId = undefined;

        return {

            Initialize: function (formSelector) {
                if (formSelector === '#edit-distribution-form')
                    genericFormExperienceScript.Initialize(formSelector, { onSubmitOverride: onEditDistributionFormSubmit });
                else if (formSelector == '#edit-beneficiary-form')
                    genericFormExperienceScript.Initialize(formSelector, { onSubmitOverride: onTermsAndConditionsFormSubmit });
                else
                    genericFormExperienceScript.Initialize(formSelector, { onSubmitOverride: onCoverageFormSubmit });
                $(formSelector).validate({ ignore: [] });
                jQuery('[data-toggle="tooltip"]').tooltip({ boundary: "window" });
                jQuery("span.field-validation-error").show();
                jQuery("#txtDateOfBirth").mask("00/00/0000");
                jQuery("#txtPhoneNumber").mask("(000) 000-0000");
                jQuery("input[data-val-autotab]").autotab();
                jQuery("input[data-val-mask]").each(function () {
                    $(this).mask($(this).attr("data-val-mask"));
                });
                Site.AccountForm.ScrollToError();
            },
            BindTogglePolicy: function() {
                $("#policy-toggle").on("change", function () {
                    const policyIdxKey = "cpol";
                    const idx = $(this).val();
                    const urlIdx = getUrlParameter(policyIdxKey);

                    if (urlIdx === idx)
                        return;

                    $("#policyToggleModal").modal('show');
                    try {
                        const newUrl = encodeURI(updateUrlParameter(location.href, policyIdxKey, idx));
                        document.location.href = newUrl;
                    } catch (err) {
                        _log("Error handling policy toggle: " + _err);
                        $("#policyToggleModal").modal('hide');
                    }
                });
            },

            BindChangeNameReasonToggle: function() {
                const changeReason = $(".name-change-reason");
                const changeReasonOther = $(".name-change-reason-other");
                const fnOrig = $("#OriginalFirstName").val();
                const lnOrig = $("#OriginalLastName").val();
                toggleAdditionalInfo();
                toggleChangeReason();

                $("#NameChangeReason").on("change", function () {
                    toggleAdditionalInfo();
                });

                $("#txtFirstName, #txtLastName").on("input propertychange paste", function () {
                    toggleChangeReason();
                });

                function toggleAdditionalInfo() {
                    const val = $("#NameChangeReason").val();
                    if (val === "Other")
                        changeReasonOther.show();
                    else
                        changeReasonOther.hide();
                }

                function toggleChangeReason() {
                    const fn = $("#txtFirstName").val();
                    const ln = $("#txtLastName").val();

                    _log("Name Compare: [" + fn + "," + fnOrig + "], [" + ln + "," + lnOrig + "]");
                    if (fn !== fnOrig || ln !== lnOrig) {
                        _log("Name has changed, showing change reason");
                        changeReason.show();
                    } else {
                        _log("Name is unchanged, hiding change reason");
                        changeReason.hide();
                    }
                }
            },

            BindReviewAndConfirm: function (formSelector) {
                const reviewAndConfirm = $("#ReviewAndConfirm");
                const submitBtn = $(formSelector).find("[type='submit']");
                toggleSubmitButton();

                reviewAndConfirm.on("change", function() {
                    toggleSubmitButton();
                });

                function toggleSubmitButton() {
                    if (reviewAndConfirm.is(":checked")) {
                        submitBtn.removeAttr("disabled");
                    } else {
                        submitBtn.attr("disabled", "disabled");
                    }
                }
            },

            /*
             * Get the available share based on all "enabled" shares in a class.  Divide that share
             * and evenly distribute it among all enabled beneficiaries.  Disabled bene's include Trusts
             * and IRBs.  Shares are restricted to whole numbers, with the extra points required for balance
             * going top down in the bene list.
             */
            DistributionSharesEvenly: function(beneClass) {
                var benes = $("#bene-class-" + beneClass + " .bene-share:enabled").length;
                var disabledBenes = $("#bene-class-" + beneClass + " .bene-share:disabled").length;
                _log("Bene count in class " + beneClass + " is " + benes + " editable benes and " + disabledBenes + " locked benes.");
                
                if (benes > 0) {

                    var disabledTotal = 0;
                    if (disabledBenes > 0)
                        $("#bene-class-" + beneClass + " .bene-share:disabled").each(function() {
                            disabledTotal += ($(this).val() / 1);
                        });
                    _log("Disabled bene share total is " + disabledTotal);

                    var _share = 100 - disabledTotal;

                    var amount = Math.floor(_share / benes);
                    var extraPoints = _share - (amount * benes);
                    _log("Even share distribution is " + amount + "% with " + extraPoints + " getting an extra point");
                    
                    $("#bene-class-" + beneClass + " .bene-share:enabled").each(function (idx) {
                        if (idx < extraPoints) {
                            $(this).val(amount + 1);
                        } else {
                            $(this).val(amount);
                        }
                    });
                    Site.Coverage.BeneficiaryDistributionCalculation();
                }
            },

            /*
             * Sets the distribution total for each beneficiary class, adding up the
             * bene-share for each bene and placing the value into distribution-total
             */
            BeneficiaryDistributionCalculation: function() {
                for (let i = 1; i <= 3; i++) {
                    let total = 0;
                    $("#bene-class-" + i + " .bene-share, #SharePercent").each(function () {
                        var beneValue = parseFloat($(this).val());
                        if (isNaN(beneValue)) beneValue = 0;
                        total += beneValue;
                    });
                    const dTotal = $("#bene-class-" + i + " .distribution-total");
                    if (isNaN(total))
                        dTotal.addClass("input-validation-error");
                    else {
                        dTotal.removeClass("input-validation-error");
                        dTotal.val(total);
                        if (total === 100)
                            dTotal.closest("tr").removeClass("distribution-error");
                        else
                            dTotal.closest("tr").addClass("distribution-error");
                    }
                }
            },

            ConfirmBeneficiaryDelete: function(beneId) {
                _log("Popping modal to confirm bene deletion for " + beneId);

                var beneClass = $("#bene-row-" + beneId).parents("table").attr("id");

                if (beneClass == "bene-class-1") {
                    if (Site.Coverage.GetTableBeneficiaryCount("#bene-class-1") === 1) {
                        $("#delete-first-class-bene-error").modal();
                        return;
                    }
                }
                else if (beneClass == "bene-class-2") {
                    if (Site.Coverage.GetTableBeneficiaryCount("#bene-class-3") > 0 && Site.Coverage.GetTableBeneficiaryCount("#bene-class-2") === 1) {
                        $("#delete-second-class-bene-error").modal();
                        return;
                    }
                }

                Site.Coverage.deleteBeneId = beneId;
                $("#delete-bene").modal();
            },

            DeleteBeneficiary: function() {
                _log("Deleting beneficiary " + Site.Coverage.deleteBeneId);
                $("#bene-row-" + Site.Coverage.deleteBeneId).remove();
                Site.Coverage.BeneficiaryDistributionCalculation();
                Site.Coverage.BalanceBeneficiaryTableStructures();
                $("#delete-bene").modal("hide");
            },

            BindBeneficiaryDistribution: function () {
                _log("Initialize bene class distribution table");
                $(".bene-class-sort tbody").sortable({
                    cursor: "move",
                    connectWith: ".bene-class-sort tbody",
                    axis: "y",
                    cancel: ".disable-sort-item",
                    helper: function(e, tr) {
                        var $originals = tr.children();
                        const $helper = tr.clone();
                        $helper.children().each(function(idx) {
                            $(this).width($originals.eq(idx).width());
                        });
                        return $helper;
                    },
                    handle: ".handle",
                    placeholder: "bene-sortable-placeholder",
                    opacity: 0.8,
                    receive: function (event, ui) {
                        const tableRecv = $(event.target).parent("table");
                        const tableId = tableRecv.attr("id");
                        _log("Element has been dropped onto " + tableId);

                        // Disallow changes to bene table resorts when second class 
                        // becomes empty and third class has a beneficiary
                        if (Site.Coverage.GetTableBeneficiaryCount("#bene-class-2") === 0 && Site.Coverage.GetTableBeneficiaryCount("#bene-class-3") > 0) {
                            _log("Reverting the drop");
                            notifyAnimate($("#bene-class-3").closest(".beneficiary-list"), 'shake');
                            ui.sender.sortable("cancel");
                        }
                        
                        tableRecv.find(".bene-list-empty").hide();

                        Site.Coverage.BalanceBeneficiaryTableStructures();
                    }
                }).disableSelection();

                $(".bene-share").mask('999.99').on("input propertychange paste change", function () {
                    Site.Coverage.BeneficiaryDistributionCalculation();
                });

                Site.Coverage.BalanceBeneficiaryTableStructures();
            },
            
            /*
             * Perform a count of the number of beneficiaries within a class by using
             * the ID of the beneficiary table:  #bene-class-N
             */
            GetTableBeneficiaryCount: function(tableId) {
                const beneCount = $(tableId + " tbody tr:not(.bene-list-empty)").length;
                _log("Total bene count in " + tableId + " is " + beneCount);
                return beneCount;
            },

            BalanceBeneficiaryTableStructures: function() {
                setBeneficiaryEmptyListAndFoot();
                setTableSortableFlags();
                setBeneClassValues();
                Site.Coverage.BeneficiaryDistributionCalculation();

                /*
                 * Loop through each beneficiary table - if there are no beneficiaries
                 * then show the .bene-list-empty table row. If there are beneficiaries
                 * then show the table footer which contains the total share percentage.
                 */
                function setBeneficiaryEmptyListAndFoot() {
                    $(".bene-class-sort tbody").each(function () {
                        if ($(this).find("tr:not(.bene-list-empty)").length === 0) {
                            $(this).find(".bene-list-empty").show();
                            $(this).siblings("tfoot").hide();
                        } else {
                            $(this).siblings("tfoot").show();
                        }
                    });
                }

                /*
                 * If there is only 1 beneficiary in the first class table then do not allow
                 * it to be resorted.
                 *
                 * If the second class beneficiary table is empty, do not allow sorting into
                 * the third class table
                 */
                function setTableSortableFlags() {
                    // if the first class bene count is 1, then don't allow it to be dragged out
                    if ($("#bene-class-1 tbody tr").length === 1)
                        $("#bene-class-1 tbody tr").addClass("disable-sort-item");
                    else
                        $("#bene-class-1 tbody tr").removeClass("disable-sort-item");


                    // if the second class bene table is empty do not allow third class sorting
                    if (!Site.Coverage.GetTableBeneficiaryCount("#bene-class-2"))
                        $("#bene-class-3").removeClass("bene-class-sort");
                    else
                        $("#bene-class-3").addClass("bene-class-sort");
                }

                /*
                 * Set the bene class value (.bene-action) for each beneficiary per row
                 * to the appropriate class number
                 */
                function setBeneClassValues() {
                    for (var i = 1; i <= 3; i++) {
                        $("#bene-class-" + i + " .bene-action").each(function () {
                            $(this).val(i);
                        });
                    }
                }
            },

            ToggleTaxId: function() {
                $('#taxidreadonly').hide();
                $('#taxidedit').show();
            },
            disableUpload: function () {
                $('#Submit').hide(); 
            },
            enableUpload: function () {
                $('#Submit').show(); 
            },
            GetDropZone: function () {
                Site.Coverage.disableUpload();
                var previewNode = document.querySelector("#template");
                previewNode.id = "";
                var previewTemplate = previewNode.parentNode.innerHTML;
                previewNode.parentNode.removeChild(previewNode);
                let acceptedTotalBytes = 0;
                let secureDropzone = new Dropzone("#myDropzone", {
                url: "/Coverage/Documents/SecureUpload/UploadDocuments", autoProcessQueue: false,
                paramName: "files",
                clickable: '#previews',
                previewsContainer: "#previewFiles",
                previewTemplate: previewTemplate,
                autoProcessQueue: false,
                uploadMultiple: true,
                parallelUploads: 25,
                maxFiles: 25,
                maxFilesize: 25,
                addRemoveLinks: true,
                dictResponseError: 'Server not Configured',
                dictFileTooBig: "File is too big ({{filesize}}MB). Max filesize: 25MB.",
                dictInvalidFileType: "You cannot upload files of this type.",
                dictMaxFilesExceeded: "You cannot upload any more files.",
                acceptedFiles: ".tiff,.tif,.png,.jpg,.jpeg,.gif,.bmp,.pdf,.doc,.docx",
                createImageThumbnails: false,
                maxThumbnailFilesize: 10,
                thumbnailWidth: 50,
                thumbnailHeight: 50,
                thumbnailMethod: 'contain',
                dictCancelUpload: null,
                //dictInvalidFileType: "File type is invalid.",
                dictCancelUploadConfirmation: null,
                    accept: function (file, done) {
                        if (file.size > 0) {
                            acceptedTotalBytes += file.size;
                            if (acceptedTotalBytes > (this.options.maxFilesize * 1024 * 1024)) {
                                done('Adding file exceeds 25MB limit - please upload separately.');
                                console.log('Exceeded maximum total upload size of 25MB. ', file);
                                //this.removeFile(file);
                            } else {
                                Site.Coverage.enableUpload();
                                $(".file-upload").toggleClass("file-upload-ready file-upload");
                                return done();
                            }
                        }
                        else {
                            done('Empty files will not be uploaded.');
                            console.log('empty file rejected: ', file);
                        };
                },
                init: function () {
                    var self = this;
                    var fileTypes = {
                        "pdf": "icon-pdf",
                        "application/pdf": "icon-pdf",
                        "png": "icon-png",
                        "image/png": "icon-png",
                        "jpg": "icon-jpg",
                        "image/jpg": "icon-jpg",
                        "jpeg": "icon-jpg",
                        "image/jpeg": "icon-jpg",
                        "gif": "icon-gif",
                        "image/gif": "icon-gif",
                        "bmp": "icon-bmp",
                        "image/bmp": "icon-bmp",
                        "tiff": "icon-tif",
                        "image/tiff": "icon-tif",
                        "tif": "icon-tif",
                        "image/tif": "icon-tif",
                        "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "icon-docx",
                        "application/msword": "icon-doc",
                        "docx": "/icon-docx",
                        "application/docx": "icon-docx"
                    };

                    self.options.addRemoveLinks = true;
                    self.options.dictRemoveFile = "Remove";

                    self.on("addedfile", function (file, xhr, formData) {
                        console.log('new file added ', file);

                        if ($('.data-dz-errormessage').length > 1) {
                            $('data-dz-errormessage').parent('dz-error-message').siblings('progress').children('progress-bar').css( "background-color", "#d45252" )
                        }
                     
                        var iconClass = fileTypes[file.type];
                        file.previewElement.querySelector(".data-dz-thumbnail").classList.add(iconClass == null ? "icon-error" : iconClass);

                        // Wrap the last added file's remove link in a bootstrap column.
                        $("a.dz-remove").last().wrap("<div class='col-1 pt-3 px-3'></div>");
                    });

                    self.on("queuecomplete", function (file) {
                        console.log('queue complete ');   
                        if (OnSuccess != null) {
                            OnSuccess();
                        }

                    });
                    self.on("complete", function (file) {
                        console.log('complete file added ', file);

                    });

                    self.on("completemultiple", function (files) {
                        console.log('completemultiple files added ', self.getAcceptedFiles().length);
                        // Check if all files have been removed.
                        if (self.getAcceptedFiles().length == 0) {
                            Site.Coverage.disableUpload();
                        }
                    });

                    self.on("sending", function (file, xhr, formData) {
                        // Will send the filesize along with the file as POST data.
                        console.log('upload started ', file);

                        Site.Coverage.disableUpload();

                    });
                    self.on("removedfile", function (file) {
                        console.log('removed file ', file);

                        // Increate max file size based on the size of the file just removed.
                        self.options.maxFilesize += file.size / 1048576; // (1024 * 1024)

                        // Check if all files have been removed.
                        if (self.getAcceptedFiles().length == 0) {
                            Site.Coverage.disableUpload();
                            $(".file-upload-ready").toggleClass("file-upload-ready file-upload");
                        }                                  
                    });


                    self.on("uploadprogress", function (file, progress, bytesSent) {
                        console.log('uploadprogress ', file, ' bytes: ', bytesSent );
                    });

                    self.on("totaluploadprogress", function (progress) {
                        console.log('total upload progress ', progress);
                       // document.querySelector("#total-progress .progress-bar").style.width = progress + "%";
                    });
                    self.on("queuecomplete", function () {
                        console.log('queue complete ');
                    });
                     
                    // Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
                    // of the sending event because uploadMultiple is set to true.
                    self.on("sendingmultiple", function (file, xhr, formData) {
                        // Gets triggered when the form is actually being sent.
                        // Hide the success button or the complete form.
                        console.log('upload started ', file);
                        $('.meter').show();

                     
                    });
                    self.on("success", function (file, response) {
                        // Gets triggered when the files have successfully been sent.
                        // Redirect user or notify of success.
                        console.log("Successfully uploaded : ");
                        
                    });
                    self.on("error", function (file, response) {
                        file.previewElement.querySelector(".progress-bar").classList.add("progress-bar-error");
                        file.previewElement.querySelector(".dz-remove").classList.add("dz-error-message");
                        file.previewElement.querySelector(".progress-bar").style.width = "100%";
                        file.previewElement.querySelector(".data-dz-thumbnail").classList.add("icon-error");

                        console.log("Error uploading : " + response);
                        // Gets triggered when the files have successfully been sent.
                        // Redirect user or notify of success.
                        console.log("Error uploading : " + response);
                       
                    });
                    self.on("successmultiple", function (files, response, e) {
                        // Gets triggered when the files have successfully been sent.
                        // Redirect user or notify of success.
                        console.log("success multiple uploading : ");
                        document.body.innerHTML = response;
                    });
                    self.on("errormultiple", function (files, message, xhr) {
                        // Gets triggered when there was an error sending the files.
                        // Maybe show form again, and notify user of error
                        console.log("Error multiple uploading : " + message)

                        if (xhr != null) {
                            document.body.innerHTML = xhr.response;
                        }
                    });

                    $('#Submit').on("click", function (e) {          
                        $('body').css({ 'overflow': 'hidden' });
                        window.scrollTo({ top: 0, behavior: 'smooth' });
                        Site.Form().toggleSpinner();
                        e.preventDefault();
                        e.stopPropagation();
                        
                        if (self.getQueuedFiles().length > 0) {
                            var result = self.processQueue(function (data) {
                                var x = data;
                            });
                      
                        } else {
                            if (self.getAcceptedFiles().length > 0) {
                                self.uploadFiles([]);
                                $('#myDropzone').submit();
                            } else {
                                $('.overlay').hide();
                                alert("No files have been uploaded");
                            };
                        };

                    });

                }

            });
             
        }
        };

        function _log(s) {
            if (_debug && /chrom(e|ium)/.test(navigator.userAgent.toLowerCase()))
                console.log(s);
        }

        function notifyAnimate(selector, animationType) {
            $(selector).addClass(animationType).on("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend", function () {
                $(selector).removeClass(animationType);
            });
        }

        function onCoverageFormSubmit(formSelector) {
            _log(">> onCoverageFormSubmit [" + formSelector + "]");
            $(formSelector).submit(function (event) {
                $("span.field-validation-error").show();

                if ($(this).valid()) {
                    Site.AccountForm.ToggleButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));
                    Site.Form().toggleSpinner();
                    return true;
                }
            });
        }

        function onEditDistributionFormSubmit(formSelector) {
            _log(">> onEditDistributionFormSubmit [" + formSelector + "]");

            $(formSelector).submit(function (event) {
                $("span.field-validation-error").show();

                if ($(this).valid()) {
                    Site.AccountForm.ToggleButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));

                    // verify all totals are 100%
                    $('.distribution-total').each(function () {
                        if ($(this).val() !== "100" && $(this).is(":visible")) {
                            _log("Found a distribution total that is not 100%. Stopping submission");
                            Site.AccountForm.StopButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));
                            let y = $(this).closest('.beneficiary-list').offset().top;
                            if (y > 50) // add a little top margin to the scroll position if available
                                y = y - 50;
                            jQuery("html,body").animate({ scrollTop: y }, 250);
                            notifyAnimate($(this).closest('.input-group'), 'pulsate');
                            event.preventDefault();
                            return false;
                        }
                    });

                    // verify that the review and confirm language is checked
                    const terms = $('#ReviewAndConfirm');
                    if (!terms.is(':checked')) {
                        notifyAnimate('.review-and-confirm', 'pulsate');
                        Site.AccountForm.StopButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));
                        return false;
                    }

                    return true;
                }
            });
        }

        function onTermsAndConditionsFormSubmit(formSelector) {
            _log(">> onTermsAndConditionsFormSubmit [" + formSelector + "]");

            $(formSelector).submit(function (event) {
                $("span.field-validation-error").show();

                if ($(this).valid()) {
                    Site.AccountForm.ToggleButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));

                    const terms = $('#ReviewAndConfirm');
                    if (!terms.is(':checked')) {
                        notifyAnimate('.review-and-confirm', 'pulsate');
                        Site.AccountForm.ToggleButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));
                        return false;
                    }

                    return true;
                }
            });
        }
        
    })();
})(jQuery);;
(function ($) {
    Site.Payment = (function() {
        var _debug = !/^www/.test($(location).attr("hostname"));
        var genericFormExperienceScript = new Site.Form();

        return {

            Initialize: function (formSelector) {
                if (formSelector === '#select-payment-form')
                    genericFormExperienceScript.Initialize(formSelector, { onSubmitOverride: onSelectPaymentFormSubmit });
                else if (formSelector == '#autopay-form')
                    genericFormExperienceScript.Initialize(formSelector, { onSubmitOverride: onTermsAndConditionsFormSubmit });
                else
                    genericFormExperienceScript.Initialize(formSelector, { onSubmitOverride: onPaymentFormSubmit });
                $(formSelector).validate({ ignore: [] });
                jQuery('[data-toggle="tooltip"]').tooltip({ boundary: "window" });
                jQuery("span.field-validation-error").show();
                jQuery('#txtDateOfBirth').mask('00/00/0000');   
                jQuery("input[data-val-autotab]").autotab();
                jQuery("input[data-val-mask]").each(function () {
                    $(this).mask($(this).attr("data-val-mask"));
                });
                jQuery(".custom-radio-frequency input[type='radio']").change(function () {
                    var frequency = $(this).val().replace("ly", "").toLowerCase();
                    jQuery('.custom-terms-text span').text(frequency);
                });
                Site.AccountForm.ScrollToError();
            },

            TogglePaymentFrequencyCTA: function () {
                var btn = $('#payment-frequency-form [type="submit"]');
                btn.prop('disabled', true);
                $('[name="PaymentFrequency"]').on('change', function () {
                    btn.prop('disabled', !btn.is(':disabled'));
                });
            },

            ToggleSelectPaymentCTA: function() {
                var btn = $('#select-payment-form [type="submit"]');
                btn.prop('disabled', true);
                $('[name="SelectPayment"]').on('change', function () {
                    btn.prop('disabled', false);
                });
            }
        };

        function _log(s) {
            if (_debug && /chrom(e|ium)/.test(navigator.userAgent.toLowerCase()))
                console.log(s);
        }

        function notifyAnimate(selector, animationType) {
            $(selector).addClass(animationType).on("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend", function () {
                $(selector).removeClass(animationType);
            });
        }

        function onPaymentFormSubmit(formSelector) {
            _log(">> onPaymentFormSubmit [" + formSelector + "]");
            $(formSelector).submit(function (event) {
                $("span.field-validation-error").show();

                if ($(this).valid()) {
                    Site.AccountForm.ToggleButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));
                    toggleSpinner();
                    return true;
                }
            });
        }

        function onSelectPaymentFormSubmit(formSelector) {
            _log(">> onSelectPaymentFormSubmit [" + formSelector + "]");
            $(formSelector).submit(function (event) {
                $("span.field-validation-error").show();

                if ($(this).valid()) {
                    Site.AccountForm.ToggleButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));
                    toggleSpinner();
                    const selectedOption = $('input[name="SelectPayment"]:checked').val();
                    _log("Handling payment selection event=" + selectedOption);
                    if (selectedOption === "ManagePayments") {
                        // handle FIS/SSO connectivity
                        event.preventDefault();
                        Site.AccountForm.ToggleButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));
                        window.open('/aarp_api/SelectPayment/Process', "_self");
                    } else {
                        return true;
                    }

                }
            });
        }

        function onTermsAndConditionsFormSubmit(formSelector) {
            _log(">> onTermsAndConditionsFormSubmit [" + formSelector + "]");

            $(formSelector).submit(function (event) {
                $("span.field-validation-error").show();

                if ($(this).valid()) {
                    Site.AccountForm.ToggleButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));

                    const terms = $('#ReviewAndConfirm');
                    if (!terms.is(':checked')) {
                        notifyAnimate('.auth-copy', 'pulsate');
                        Site.AccountForm.ToggleButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));
                        return false;
                    }

                    return true;
                }
            });
        }

    })();
})(jQuery);

/*
 * Validate Routing Number
 *
 * Attempts to validate a routing number against a standard algorithm. This method
 * also serves as a "is numeric" check.
 */
jQuery.validator.addMethod("validateroutingnumber", function (value, element, params) {
    _log(">> Routing Number Validator");

    if (jQuery.trim(value) === "" || !jQuery.isNumeric(value))
        return false;

    if (value.length !== 9) {
        var x = "000000000" + value;
        value = x.substr(x.length - 9, x.length);
    };

    if (value[0] === '5') return false;

    var checksumTotal = (7 * (parseInt(value.charAt(0), 10) + parseInt(value.charAt(3), 10) + parseInt(value.charAt(6), 10))) +
        (3 * (parseInt(value.charAt(1), 10) + parseInt(value.charAt(4), 10) + parseInt(value.charAt(7), 10))) +
        (9 * (parseInt(value.charAt(2), 10) + parseInt(value.charAt(5), 10) + parseInt(value.charAt(8), 10)));

    if (checksumTotal === 0) return false;

    var checksumMod = checksumTotal % 10;
    return (checksumMod === 0);
});

jQuery.validator.unobtrusive.adapters.add("validateroutingnumber", [], function (options) {
    options.rules["validateroutingnumber"] = options.params;
    options.messages["validateroutingnumber"] = options.message;
});


/*
 * Fields are different than each other
 *
 * Compares the value of the current field with the current value in the
 * field passed in the params:  param.field.
 *
 * This used primarily for making sure Account Number and Routing Number
 */
jQuery.validator.addMethod("differentthan", function (value, element, params) {
    _log(">> Different Than Validation");

    // ignore differences if the value is empty
    if (jQuery.trim(value) == "")
        return true;

    const otherValue = jQuery('#' + params.field).val();
    return (value !== otherValue);
});

jQuery.validator.unobtrusive.adapters.add("differentthan", ["field"], function (options) {
    options.rules["differentthan"] = options.params;
    options.messages["differentthan"] = options.message;
});
;
var Site = window.Site || {};
(function ($) {
    Site.NYLRRC = (function () {
        var json = {};
        var coverageChoice = '#nylrrc-coverage-choice';
        var ageChoice = '#nylrrc-age-choice';
        var ageSelect = '#nylrrc-age-select';
        var tabList = '#nylrrc-tabs a';
        var male = "Male";
        var female = "Female";
        var rcdbg = !/^www/.test($(location).attr('hostname'));
        var compact = false;
        return {
            Init: function (data) {
                 
               this.json = JSON.parse(eval(data.html()));

                Site.NYLRRC.BuildRateChart();
                $('body').on('nyl:RateChart', function (evt, action) {
                    Site.NYLRRC.Log("Received action: " + action);
                    if (action == "Update") {
                        Site.NYLRRC.LiveUpdate();
                    }
                });

                this.OnCoverageChange(function () {
                      var useModel = false;
                      //if state element doesn't exist - use the values from model(ex: quote page)
                      if (!$("#State")[0]) {
                          useModel = true;
                      }
                      var coverageVal = $("#nylrrc-coverage-choice").val();
                      //if state element exists but doesn't have value use default value 
                      var state = $("#State").val();
                      if (!state)
                          state = Site.NYLRRC.json.State;
                      var age = !!Site.EventsFormExperience ? Site.EventsFormExperience.getAge() : Site.NYLRRC.json.Age;
                      var gender = $("[name=Gender]:checked").val();
                      if (!gender)
                          gender = Site.NYLRRC.json.Gender;
                      var smoker = $("[name=TobaccoQuestion]:checked").val();
                      if (!smoker)
                          smoker = Site.NYLRRC.json.Smoker;
                      if ($("#nylrrc-age-choice")[0]) {
                          Site.NYLRRC.UpdateRates();
                      } else {
                          Site.NYLRRC.ShowPersonalizedRateChart(gender, state, smoker, age, coverageVal, useModel);
                      }
                  });
                $(ageChoice)
                    .change(function () {
                        Site.NYLRRC.UpdateRates();
                    });
            },
            BuildRateChart: function () {
                Site.NYLRRC.compact = ($('.nylrrc-container').hasClass('nylrrc-compact'));
                $(tabList).click(function (e) {
                    e.preventDefault();
                    $(this).closest('ul.nav').find('li').each(function (idx, listItem) {
                        $(listItem).removeClass('active');
                    });
                    $(this).parent().addClass('active');
                    Site.NYLRRC.UpdateRates();
                });
                Site.NYLRRC.BindAges();
                Site.NYLRRC.BindCoverages();
            },
            OnCoverageChange: function (callback) {
                $(coverageChoice).change(function (e) {
                    callback();
                });
            },
            BindCoverages: function () {
                var dd = $(coverageChoice);
                dd.empty();
                $.each(Site.NYLRRC.json.CoverageAmounts, function (i, data) {
                    var opt =
                        $('<option>', {
                            value: data.Value,
                            text: data.Display //data.Value.toString().replace(/(\d)(?=(\d{3})$)/g, "$1,")
                        }, '</option>');
                    dd.append(opt);
                });
                dd.val(Site.NYLRRC.json.DefaultCoverageAmount);
                Site.NYLRRC.UpdateRates();
            },
            BindAges: function () {
                var dd = $(ageChoice);

                if (dd.length) { // drop down exists, add the ages
                    dd.empty();
                    if (Site.NYLRRC.IsPersonalized()) {
                        var opt = $('<option>', {
                            value: Site.NYLRRC.json.Age,
                            text: Site.NYLRRC.json.Age
                        }, '</option>');
                        dd.append(opt);
                    } else {

                        for (var i = Site.NYLRRC.json.ProductMinAge; i <= Site.NYLRRC.json.ProductMaxAge; i += 5) {
                            var ceiling = (i + 4);
                            if (ceiling > Site.NYLRRC.json.ProductMaxAge) ceiling = Site.NYLRRC.json.ProductMaxAge;
                            var optionText = i + '-' + ceiling;
                            if (i == Site.NYLRRC.json.ProductMaxAge)
                                optionText = i;
                            var opt = $('<option>', {
                                value: i,
                                text: optionText
                            }, '</option>');
                            dd.append(opt);
                        }
                    }
                }
            },
            UpdateRates: function () {
                var isLevelBenefitTerm = Site.NYLRRC.json.ProductType === 'LevelBenefitTerm';
                var isLevelBenefitTermRider = Site.NYLRRC.json.ProductType === 'LevelBenefitTermRider';
                var tbody = $('.nylrrc-table tbody');
                tbody.empty();

                if (Site.NYLRRC.compact) {
                    tbody.append("<tr class=\"compact-head\"><td>Issue Age</td><td>Rates for " + ((Site.NYLRRC.json.Gender === male) ? "Men" : "Women") + "</td></tr>");
                }

                if (isLevelBenefitTerm) {
                    Site.NYLRRC.UpdateRatesLBT();
                }else
                    if (isLevelBenefitTermRider) {
                        Site.NYLRRC.UpdateRatesLBT();
                    } else {
                        Site.NYLRRC.UpdateRatesStandard();
                        }

                // toggle tabs if this is a personalized chart
                if (Site.NYLRRC.json.Gender) {
                    $('#nylrrc-tabs').hide();
                }
                if (Site.NYLRRC.IsPersonalized()) {
                    $(ageSelect).hide();
                    $('#nylrrc-title').html(Site.NYLRRC.json.Title);
                    var coverageRangeLabel = $('#nylrrc-coverage-range-label');
                    $('#nylrrc-age-hd').css('text-align', 'right').html(coverageRangeLabel.html());
                    $('#nylrrc-coverage-hd').css('text-align', 'left');
                    coverageRangeLabel.hide();
                    $("#rateChartDisclaimer").html(Site.NYLRRC.json.Disclaimer);
                }
                if (!Site.NYLRRC.compact) {
                    var tbody = $('.nylrrc-table tbody');
                    // add final footer table row
                    tbody.append("<tr class=\"foot\"><td colspan=\"2\">" + Site.NYLRRC.json.RateChartFooter + "</td></tr>");

                    // Update Banner height once rates have been established
                    var banner = $('.nylrrc-banner');

                    //var containerHeight = banner.parent().height();
                    var containerHeight = $('.nylrrc-container').height();
                    banner.css('height', containerHeight + 'px');
                }
            },
            UpdateRatesStandard: function () {
                var tbody = $('.nylrrc-table tbody');
                var gender = "Men";
                if (!Site.NYLRRC.compact) {
                    if (Site.NYLRRC.IsPersonalized()) {
                        if (Site.NYLRRC.json.Gender)
                            gender = Site.NYLRRC.json.Gender == "Female" ? "Women" : "Men";
                        else if (Site.NYLRRC.GenderIs('female')) {
                            gender = "Women";
                        }

                        tbody.append("<tr><td class=\"age\">Issue Age</td><td class=\"age\">" + "Rates for " + gender + "</td></tr>");
                    } else {
                        tbody.append("<tr><td class=\"age\">Issue Age</td><td class=\"age\">Monthly Rate</td></tr>");
                    }

                }
                var covamt = parseInt($(coverageChoice).val(), 10);
                if (covamt === undefined || covamt == null)
                    covamt = Site.NYLRRC.json.DefaultCoverageAmount;

                var selectedAge = parseInt($(ageChoice).val());

                var realAge = Site.NYLRRC.json.Age;
                var rowCount = 0;
                $.each(Site.NYLRRC.json.Rates, function (i, data) {
                    if ((Site.NYLRRC.GenderIs('male') && data.Gender === male) || (Site.NYLRRC.GenderIs('female') && data.Gender === female)) {
                        if (data.CoverageAmount === covamt) {
                            if ((realAge == 0 && data.Age >= selectedAge && data.Age <= (selectedAge + 4)) || realAge == data.Age) {
                                rowCount++;
                                //if (data.Age == selectedAge && data.Age <= (selectedAge + 4)) {
                                tbody.append("<tr><td class=\"age\">" + data.Age + "</td><td  class=\"amt-align\"><span class=\"dollar\">$</span>" +
                                parseFloat(data.Premium).toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") + "</td></tr>");
                            }
                        }
                    }
                });

                if (rowCount === 0) {
                    var cov = encodeURIComponent(JSON.stringify($(coverageChoice + ' option:selected').text()));
                    tbody.append("<tr><td class=\"age\" colspan=\"2\">Rates are unavailable for <span class=\"dollar\"></span>" +
                        decodeURIComponent(cov) + "</td></tr>");
                }
            },
            UpdateRatesLBT: function () {
                var tbody = $('.nylrrc-table tbody');
                var covamt = parseInt($(coverageChoice).val(), 10);
                covamt = parseInt(covamt) || parseInt(Site.NYLRRC.json.DefaultCoverageAmount);
                Site.NYLRRC.Log("Parsing for Coverage: " + covamt);
                var rowCount = 0;
                $.each(Site.NYLRRC.json.Rates, function (i, data) {
                    if ((Site.NYLRRC.GenderIs('male') && data.Gender === male) || (Site.NYLRRC.GenderIs('female') && data.Gender === female)) {
                        if (data.CoverageAmount === covamt) {
                            rowCount++;
                            var ageHtml = data.Age + '-' + parseInt(data.Age + 4);
                            tbody.append("<tr><td class=\"age\">" + ageHtml + "</td><td class=\"amt-align\"><span class=\"dollar\">$</span>" +
                            parseFloat(data.Premium).toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") + "</td></tr>");
                        }
                    }
                });
                if (Site.NYLRRC.IsPersonalized() && !Site.NYLRRC.compact) {
                    var rateText = Site.NYLRRC.GenderIs("female") ? "Rates for Women" : "Rates for Men";
                    $(".nylrrc-container table tbody tr:first").before("<tr class=\"sub-header\"><td>Issue Age</td><td>" + rateText + "</td></tr>");
                }
                if (rowCount === 0) {
                    var cov = encodeURIComponent(JSON.stringify($(coverageChoice + ' option:selected').text()));
                    tbody.append("<tr><td class=\"age\" colspan=\"2\">Rates are unavailable for <span class=\"dollar\"></span>" +
                        decodeURIComponent(cov) + "</td></tr>");
                }

            },
            UpdateCustomCoverage: function (covamt) {

                if (covamt === undefined || covamt == null)
                    covamt = Site.NYLRRC.json.DefaultCoverageAmount;

                var hasCustomCoverageAmount = false;
                $.each(Site.NYLRRC.json.CoverageAmounts, function (i, data) {
                    if (data.Value == covamt) {
                        hasCustomCoverageAmount = true;
                    }
                });

                // Remove previous binding
                $(coverageChoice).unbind();

                // Rebind Coverage drop down event
                this.OnCoverageChange(function () {
                    var covamt = parseInt($(coverageChoice).val(), 10);
                    Site.NYLRRC.UpdateRateChartContent(covamt, Site.NYLRRC.json.Smoker, Site.NYLRRC.json.Gender)
                        .done(function () {
                            Site.NYLRRC.UpdateRates();
                        });
                });

                if (hasCustomCoverageAmount) {
                    Site.NYLRRC.Log("Found custom coverage amount in preloaded list.");
                    $(coverageChoice).val(covamt);
                    Site.NYLRRC.UpdateRates();
                    return;
                }

                Site.NYLRRC.Log("Updating rate chart with custom coverage: " + covamt);
                Site.NYLRRC.json.DefaultCoverageAmount = covamt;
                Site.NYLRRC.LiveUpdate(true);


            },
            UpdateRateChartContent: function (coverage, smoker, gender) {

                if (!!!Site.NYLRRC.json) return jQuery.when();

                return this.GetRateChartJsonPersonalized(gender, Site.NYLRRC.json.State, smoker, Site.NYLRRC.json.Age, coverage, false);
            },
            ShowPersonalizedRateChart: function (gender, state, smoker, age, coverage, useModel) {

                if (!!!Site.NYLRRC.json) return;

                this.GetRateChartJsonPersonalized(gender, state, smoker, age, coverage, useModel)
                    .done(function() {
                        Site.NYLRRC.BuildRateChart();
                    });
            },
            GetRateChartJsonPersonalized: function (gender, state, smoker, age, coverage, useModel) {

                if (!!!Site.NYLRRC.json) return jQuery.when();

                var promise = $.getJSON('/RCP/RateChart/RenderRateChartJsonPersonalized', {
                    contextItemId: Site.NYLRRC.json.ContextItemId,
                    renderingItemId: Site.NYLRRC.json.RenderingItemId,
                    age: age > 0 ? age : Site.NYLRRC.json.ProductMinAge,
                    gender: gender,
                    state: state,
                    coverageAmount: coverage,
                    productType: Site.NYLRRC.json.ProductType,
                    smoker: !!!smoker ? Site.NYLRRC.json.Smoker : smoker,
                    overrideCoverage: true,
                    useModel: useModel
                }, function (result) {
                    Site.NYLRRC.json = result;
                });

                return promise;
            },
            LiveUpdate: function (overrideCoverage) {

                if (overrideCoverage === undefined)
                    overrideCoverage = false;
                $.getJSON('/RCP', {
                    contextItemId: Site.NYLRRC.json.ContextItemId,
                    renderingItemId: Site.NYLRRC.json.RenderingItemId,
                    age: Site.NYLRRC.json.Age,
                    gender: Site.NYLRRC.json.Gender,
                    state: Site.NYLRRC.json.State,
                    coverageAmount: Site.NYLRRC.json.DefaultCoverageAmount,
                    productType: Site.NYLRRC.json.ProductType,
                    smoker: Site.NYLRRC.json.Smoker,
                    overrideCoverage: overrideCoverage
                }, function (result) {
                    Site.NYLRRC.json = result;
                    Site.NYLRRC.BuildRateChart();
                });
            },
            GenderIs: function (gender) {
                if (Site.NYLRRC.json.Gender)
                    return (gender.toLowerCase() === Site.NYLRRC.json.Gender.toLowerCase());

                return $('#nylrrc-' + gender).hasClass('active');
            },
            IsPersonalized: function () {
                return Site.NYLRRC.json.Age > 0;
            },
            Log: function (msg) {
                if (rcdbg) console.log(msg);
            }
        };
    })();
})(jQuery);

function showRateChart() {
    if ($('#NYLDRateChartLightbox').length) {
        $('html body').animate({ scrollTop: 0 }, 'slow');
        $.blockUI({
            message: $('#NYLDRateChartLightbox'),
            css: {
                border: 0,
                background: 'transparent',
                textAlign: 'left',
                position: 'absolute'
            }
        });
    } else if ($('#NYLDRateChart').length) {
        $('html, body').animate({
            scrollTop: $("#NYLDRateChart").offset().top
        }, 1000);
    } else if ($('.nyl-responsive-ratechart').length) {
        $('html,body').animate({
            scrollTop: $('.nyl-responsive-ratechart').offset().top
        }, 1000);
    }
    $('body').trigger('ratechart:click');
}

function showRateChartResponsive() {
    showRateChart();
};
var Site = window.Site || {};
var baseurl = '/Apply/Application';
var _editMode = false;
var _debug = !/^www/.test($(location).attr('hostname'));

jQuery.validator.addMethod("benerequired", function (value, element) {
    _log(">> BeneRequired validation fired");

    //const beneRows = $(".beneficiary-row:visible")
    //let valid = true;
    //beneRows.each(function (index, elem) {
    //    $(elem).find("input[type='text']").each(function (n, input) {
    //        if ($(input).val() === "") {
    //            valid = false;
    //            return;
    //        }
               
    //    });
    //});

    return $.trim(value) !=="";
});
jQuery.validator.unobtrusive.adapters.add("benerequired", [], function (options) {
    options.rules["benerequired"] = options.params;
    options.messages["benerequired"] = options.message;
});


/*
 * Beneficiary Total is 100
 * > Bene Share
 *
 * Check both beneficiary share percentages and make sure they total 100.
 * If bene share 1 is hidden, consider it a zero.  Consider a value of empty
 * or undefined as a zero.
 */
jQuery.validator.addMethod("benesharetotal", function () {
    _log(">> BeneShareTotal validation fired");

    let shareTotal = 0;
    // const beneShareFields = ["#Beneficiaries_0__BeneShare", "#Beneficiaries_1__BeneShare"];
    const beneShareFields = $(".beneficiary-row").find("input[id$='BeneShare'").each(function (index, elem) {
        if (jQuery(elem).is(":visible")) {
            let shareVal = parseInt($(elem).val());
            if (!isNaN(shareVal)) {
                shareTotal += shareVal
            }

        }
    });

    const validShare = shareTotal === 100;

    if (validShare) {
        beneShareFields.each(function (index, elem) {
            $(elem).removeClass("input-validation-error");
            $(elem).parent().siblings(".field-validation-error").hide();
        });

        return true;
    }

    return false;
});

jQuery.validator.unobtrusive.adapters.add("benesharetotal", [], function (options) {
    options.rules["benesharetotal"] = options.params;
    options.messages["benesharetotal"] = options.message;
});

/*
 * Fields are different than each other
 *
 * Compares the value of the current field with the current value in the
 * field passed in the params:  param.field.
 *
 * This used primarily for making sure Account Number and Routing Number
 */
jQuery.validator.addMethod("differentthan", function (value, element, params) {
    _log(">> Different Than Validation");

    // ignore differences if the value is empty
    if (jQuery.trim(value) == "")
        return true;

    const otherValue = jQuery('#' + params.field).val();
    return (value !== otherValue);
});

jQuery.validator.unobtrusive.adapters.add("differentthan", ["field"], function (options) {
    options.rules["differentthan"] = options.params;
    options.messages["differentthan"] = options.message;
});

/*
 *  Custom validator of the consent and sign.
 */
jQuery.validator.addMethod("consentrequired", function (value, element) {
    _log(">> Consent Required Field Validator");

    return element.checked;
});

jQuery.validator.unobtrusive.adapters.add("consentrequired", [], function (options) {
    options.rules["consentrequired"] = options.params;
    options.messages["consentrequired"] = options.message;
});


jQuery.validator.addMethod("eftrequired", function (value, element) {
    _log(">> EFT Required Fields Validator");

    if (jQuery("input[name='PaymentOption']:checked").val() !== "A")
        return true;

    if (jQuery.trim(value) === "")
        return false;

    return true;
});

jQuery.validator.unobtrusive.adapters.add("eftrequired", [], function (options) {
    options.rules["eftrequired"] = options.params;
    options.messages["eftrequired"] = options.message;
});

/*
 * Validate Routing Number
 *
 * Attempts to validate a routing number against a standard algorithm. This method
 * also serves as a "is numeric" check.
 */
jQuery.validator.addMethod("validateroutingnumber", function (value, element, params) {
    _log(">> Routing Number Validator");

    if (jQuery.trim(value) === "" || !jQuery.isNumeric(value))
        return false;

    if (value.length !== 9) {
        var x = "000000000" + value;
        value = x.substr(x.length - 9, x.length);
    };

    if (value[0] === '5') return false;

    var checksumTotal = (7 * (parseInt(value.charAt(0), 10) + parseInt(value.charAt(3), 10) + parseInt(value.charAt(6), 10))) +
        (3 * (parseInt(value.charAt(1), 10) + parseInt(value.charAt(4), 10) + parseInt(value.charAt(7), 10))) +
        (9 * (parseInt(value.charAt(2), 10) + parseInt(value.charAt(5), 10) + parseInt(value.charAt(8), 10)));

    if (checksumTotal === 0) return false;

    var checksumMod = checksumTotal % 10;
    return (checksumMod === 0);
});

jQuery.validator.unobtrusive.adapters.add("validateroutingnumber", [], function (options) {
    options.rules["validateroutingnumber"] = options.params;
    options.messages["validateroutingnumber"] = options.message;
});

function getNumericFromField(elem) {
    if (elem === undefined || jQuery(elem) === undefined)
        return 0;

    let value = jQuery(elem).val();

    if (jQuery.isNumeric(value))
        return value * 1;

    return 0;
}

/*
 * Validate Other Coverage Amount to be in increments of 500
 * and between the Min and Max coverage amounts                   
 */
jQuery.validator.addMethod("validateothercoverageamount", function (value, element, params) {
    console.log("Other coverage amount value is " + value);
    // only validate if other coverage amount is selected
    const selectedCoverageAmount = jQuery("#SelectedCoverageAmount").val();
    if (selectedCoverageAmount !== undefined && selectedCoverageAmount.toLocaleLowerCase() !== "other")
        return true;

    if (value.indexOf(",") > 0)
        value = value.replace(/,/g, "");

    if (!jQuery.isNumeric(value))
        return false;

    const coverage = parseInt(value, 10);
    const minCoverage = parseInt($("#MinCoverageAmount").val(), 10);
    const maxCoverage = parseInt($("#MaxCoverageAmount").val(), 10);

    return (coverage % 500 === 0) && coverage >= minCoverage && coverage <= maxCoverage;
});

jQuery.validator.unobtrusive.adapters.add("validateothercoverageamount", [], function (options) {
    options.rules["validateothercoverageamount"] = options.params;
    const minCoverage = $("#MinCoverageAmount").val();
    const maxCoverage = $("#MaxCoverageAmount").val();
    options.messages["validateothercoverageamount"] = options.message.replace("[MinCoverage]", minCoverage).replace("[MaxCoverage]", maxCoverage);
});

/**
 * Override pattern handler in additional-methods to support numeric keypads without forcing the
 * invalid format message.
 */
jQuery.validator.addMethod("pattern", function (e, t, n) {
    return this.optional(t) || n === "[0-9]*" ? !0 : (typeof n === "string" && (n = new RegExp("^(?:" + n + ")$")), n.test(e))
}, "Invalid format.");


function _log(s) {
    if (_debug && /chrom(e|ium)/.test(navigator.userAgent.toLowerCase()))
        console.log(s);
}

function toggleSpinner(form, optionalDeactivate) {
    var _overlay = (form === undefined) ? jQuery('.overlay') : jQuery(form).find('.overlay');
    if (optionalDeactivate) {
        _overlay.hide();
    } else {
        if (_overlay.is(':visible'))
            _overlay.hide();
        else
            _overlay.css('display', 'flex');
    }
}

function deactivateSpinner() {
    toggleSpinner(undefined, true);
}

// Watch for push state events on the browser
window.addEventListener('popstate', function (e) {
    var step = (e.state) ? e.state.step : '';
    Site.ApplicationForm.ApplyPushState(step);
});
;
var Site = window.Site || {};

(function (jQuery, undefined) {
    Site.ApplicationForm = (function () {
        var genericFormExperienceScript = new Site.Form();
        var form;

        return {
            Initialize: function (formSelector) {
                form = formSelector;

                if (typeof _SC_EXPERIENCE_EDITOR_EDITING !== undefined) {
                    _editMode = _SC_EXPERIENCE_EDITOR_EDITING;
                    if (_editMode) {
                        Site.ApplicationForm.InitializeForPageEditor();
                        return;
                    }
                }

                genericFormExperienceScript.Initialize(formSelector, {});

                jQuery('[data-toggle="tooltip"]').tooltip({ delay: { "hide": 2000 } });
                jQuery('span.field-validation-error').show();
                Site.ApplicationForm.SetupSessionExpiration();
                Site.ApplicationForm.SetupMasks();
                Site.ApplicationForm.SetupNavigationLinks();
                Site.ApplicationForm.SecurePersonalInfo();
                Site.ApplicationForm.BindCallToAction();
                Site.ApplicationForm.SetupBeneficiaries();
                Site.ApplicationForm.BindPaymentOptions();
                Site.ApplicationForm.SetupListeners();
                Site.ApplicationForm.SetupStatementOfHealth();
                Site.ApplicationForm.SetupQuote();
                Site.ApplicationForm.SetupRateChart();
                Site.ApplicationForm.ApplyPushState('/step1'); //window.location.pathname.replace(baseurl, ''));
            },

            SetupSessionExpiration: function () {
                var timeout;
                $(document).ready(function () {
                    resetTimer();
                    $(this).mousemove(function (e) {
                        resetTimer();
                    });
                    $(this).keypress(function (e) {
                        resetTimer();
                    });
                });

                function sessionHasExpired() {
                    // clear cookie and redirect
                    document.cookie = "nyl=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
                    window.location.href = "/Apply/SessionExpired";
                }

                function resetTimer() {
                    clearTimeout(timeout);
                    timeout = setTimeout(sessionHasExpired, _SESSION_TIMEOUT_IN_MILLISECS)
                }
            },

            SetupMasks: function () {
                jQuery("[data-val-mask]:not([type=hidden])").each(function () {
                    const mask = jQuery(this).attr("data-val-mask");
                    const reverseMask = (jQuery(this).attr('id') == "OtherCoverageAmount");
                    jQuery(this).mask(mask, { reverse: reverseMask });
                });
            },

            /*
             * Scroll to the top most validation error on the page
             */
            ScrollToError: function () {
                const firstError = jQuery('.input-validation-error').first();
                if (firstError) {
                    let y = firstError.offset().top;
                    if (y > 50) // add a little top margin to the scroll position if available
                        y = y - 50;
                    jQuery("html,body").animate({ scrollTop: y }, 500);
                }
            },

            /*
             * Set up navigation links to use push state for steps 1, 2, 3
             */
            SetupNavigationLinks: function () {
                jQuery('.nav-link').slice(0, -2).on("click", function (e) {
                    e.preventDefault();
                });
            },

            /**
             * Initialize statement of health component:
             * - Sets up risks to be enabled/disabled based on presence of a 'yes' HQ response
             * - Set up the hidden field toggle for checkboxes on conditions
             * - Set up toggle of question details for permanent HQ's
             */
            SetupStatementOfHealth: function () {
                const nameOfLastQuestion = jQuery('.hq-radio').last().attr('name');
                jQuery("input[name='" + nameOfLastQuestion + "']").on('change', function () {
                    Site.ApplicationForm.ToggleHealthRisks();
                });

                // toggle health risks by default to allow for checkbox enabled 
                // when page is loaded and model has data
                Site.ApplicationForm.ToggleHealthRisks();

                // establish health risk value tech for conditions
                jQuery("input:checkbox.health-risk").click(function () {
                    Site.ApplicationForm.ApplyHealthRiskSelection(this);
                });
                jQuery("input:checkbox.health-risk").each(function (idx, elem) {
                    Site.ApplicationForm.ApplyHealthRiskSelection(this);
                });

                // If permanent questions exist set up toggle for question details
                if (jQuery('.perm-question').length > 0) {
                    jQuery(".hq-radio").on('change', function () {
                        Site.ApplicationForm.ToggleQuestionDetailsResponse(this);
                    }).each(function () {
                        Site.ApplicationForm.ToggleQuestionDetailsResponse(this);
                    });
                }
            },

            /**
             * When a health condition checkbox is clicked apply the value to the
             * hidden field that ASPNet creates via the Html.CheckboxFor func
             * @param {any} elem
             */
            ApplyHealthRiskSelection: function (elem) {
                var checked = jQuery(elem).is(":checked");
                var name = jQuery(elem).attr('name');
                jQuery(elem).val(checked);
                jQuery("input:hidden[name='" + name + "']").val(checked);
            },

            /**
             * Used with permanent health questions to show/hide the question
             * details text area
             *
             * @param {any} elem
             */
            ToggleQuestionDetailsResponse: function (elem) {
                const _name = jQuery(elem).attr('name');
                const _questionId = _name.match(/\d+/g);
                if (jQuery("input[name='" + _name + "']:checked").val() === "Y") {
                    jQuery("#health-question-details-" + _questionId[0]).show();
                } else {
                    jQuery("#health-question-details-" + _questionId[0]).hide();
                }

            },

            /**
             * Look at the last health question selection. If it's equal to "Y"
             * then enable all of the checkboxes for health conditions.  If it's
             * "N" then disable them all.
             */
            ToggleHealthRisks: function () {
                const nameOfLastQuestion = jQuery('.hq-radio').last().attr('name');
                const answer = jQuery("input[name='" + nameOfLastQuestion + "']:checked").val();
                if (answer === "Y") {
                    jQuery('.health-risk').prop('disabled', false);
                } else {
                    $("input.health-risk").each(function () {
                        if (!(this.id.toLowerCase().indexOf("_readonly_") > 0)) {
                            if (this.checked) {
                                $("#" + this.id).trigger("click");   // Must use trigger otherwise values are not getting saved.
                            };
                        }
                    });
                    jQuery('.health-risk').prop('disabled', true);

                }
            },

            ToggleButtonProcessing: function (btn) {
                const spinner =
                    '<span class="spinner-border spinner-border-sm text-light ml-3 d-inline-block" role="status" aria-hidden="true"></span><span class="sr-only">Loading...</span>';
                if (btn.is(':enabled')) {
                    let _html = btn.html();
                    btn.html(_html + spinner);
                    //btn.removeClass("btn-primary").addClass("btn-secondary");
                    btn.attr("disabled", "disabled");
                } else {
                    btn.find('span').remove();
                    //btn.removeClass("btn-secondary").addClass("btn-primary");
                    btn.removeAttr("disabled");
                }
            },

            /*
             * Mask any fields that need to be hidden.  Example: SSN
             */
            SecurePersonalInfo: function () {
                jQuery('input[data-val-togglepassword]:not(.toggle-password)')
                    .addClass('toggle-password')
                    .togglePassword();
            },

            SetupQuote: function () {

                const otherCoverageAmount = jQuery(".other-coverage");
                let coverageAmount = jQuery(".select-coverage select").val();

                if (coverageAmount === "other") {
                    otherCoverageAmount.show();
                    $('#collapse-siderail').collapse('show');
                }
                else
                    otherCoverageAmount.hide();


                function RefreshQuote() {
                    const quote = jQuery(".quote");

                    if (quote.length == 0) return;
                    const ratelink = jQuery(".view-rate-chart");
                    const coverageAmount = jQuery("#CoverageAmount").val();
                    if (coverageAmount === "other") {
                        coverageAmount = jQuery("#OtherCoverageAmount").cleanVal();
                    }
                    const gender = jQuery("input[name='Gender']:checked").val() || jQuery("input[type='hidden'][name='Gender']").val();
                    const smokerElem = jQuery("input[name='TobaccoQuestion']:checked") || jQuery("input[type='hidden'][name='TobaccoQuestion']");
                    let smoker= 'N'
                    if (smokerElem && smokerElem.length>0)
                        smoker = smokerElem.val();
                    var minCovAmt = parseInt($("#MinCoverageAmount").val());
                    var maxCovAmt = parseInt($("#MaxCoverageAmount").val());                   
                    var isCoverageAmountValid = coverageAmount && (coverageAmount >= minCovAmt && coverageAmount <= maxCovAmt) && jQuery("#OtherCoverageAmount").valid();
                   
                    if (isCoverageAmountValid && gender && smoker) {
                        jQuery.ajax({
                            url: "/ddk/applicationquote?coverage=" + coverageAmount + "&gender=" + gender + "&smoker=" + smoker
                        }).then(function (data) {
                            jQuery('.coverage .amount').text("$" + parseInt(coverageAmount).toLocaleString());
                            jQuery('.premium .amount').text(data);
                            if (data > 0) {
                                quote.show();
                                ratelink.show();
                            } else {
                                quote.hide();
                                ratelink.hide();
                            }

                        });
                    }
                    else {
                        quote.hide();
                        ratelink.hide();
                    }
                }

                jQuery("[data-val-triggerquoteupdate]").each(function () {
                    const type = jQuery(this).attr("type");
                    if (type === "radio") {
                        const name = jQuery(this).attr("name");
                        jQuery("input[name='" + jQuery(this).attr("name") + "']").on("change",
                            function () {
                                _log("EventFire::Update Quote;Radio=" + name);
                                Site.ApplicationForm.FireQuoteUpdate();
                            });
                    } else if (type === "text") {
                        jQuery(this).on("blur",
                            function () {
                                _log("EventFire::Update Quote;Blur=" + jQuery(this).attr("id"));
                                Site.ApplicationForm.FireQuoteUpdate();
                            });
                    } else {
                        jQuery(this).on("change",
                            function () {
                                _log("EventFire::Update Quote;Source=" + jQuery(this).attr("id"));
                                Site.ApplicationForm.FireQuoteUpdate();
                            });
                    }
                });

                function onCoverageAmountChange() {
                    const otherCoverageAmount = jQuery(".other-coverage");
                    let coverageAmount = jQuery(".select-coverage select").val();

                    if (coverageAmount === "other") {
                        coverageAmount = jQuery(".other-coverage input").cleanVal();
                        otherCoverageAmount.show();

                        $('#collapse-siderail').collapse('show');
                    }
                    else
                        otherCoverageAmount.hide();

                    jQuery("#CoverageAmount").val(coverageAmount);
                    RefreshQuote();
                }

                jQuery(".select-coverage select").on("change", onCoverageAmountChange);
                jQuery(".other-coverage input").on("change", onCoverageAmountChange);

                function refreshRateChart() {
                    var rateChart = jQuery("#nylrrc-json");
                    if (rateChart.length == 0) return;
                    let coverageAmount = $("#CoverageAmount").val();
                    if (coverageAmount === "other") coverageAmount = jQuery("#OtherCoverageAmount").unmask().val();
                    const gender = jQuery("input[name='Gender']:checked").val() || jQuery("input[type='hidden'][name='Gender']").val();
                    const tobaccoQuestion = jQuery("input[name='TobaccoQuestion']:checked").val() || jQuery("input[type='hidden'][name='TobaccoQuestion']").val();
                    Site.NYLRRC.UpdateRateChartContent(coverageAmount, tobaccoQuestion, gender)
                        .done(function () {
                            // Build the rate chart and update the coverage
                            Site.NYLRRC.BuildRateChart();
                            Site.NYLRRC.UpdateCustomCoverage(coverageAmount);
                            jQuery("#ApplicationRateChart").modal();
                        });
                }

                jQuery(".view-rate-chart .btn").click(refreshRateChart);

                jQuery("body").on("nyl:updateQuote", RefreshQuote);
            },

            FireQuoteUpdate: function () {
                jQuery("body").trigger("nyl:updateQuote");
            },

            SetupRateChart: function () {
                var rateChart = jQuery("#nylrrc-json");
                if (rateChart.length == 0) return;
                Site.NYLRRC.Init(rateChart);
                $("[data-val-rate-chart='open']").click(function () {
                    var _modal = $("<div class='modal-body'><p>I am the rate chart.</div>");
                    $('body').append(_modal);
                    $(_modal).modal();
                });
            },

            /*
             * Establish events bound to listeners from other
             * form inputs.
             */
            SetupListeners: function () {
                jQuery("input[name='Gender']").change(function () {
                    const gender = jQuery("input[name='Gender']:checked").val();
                    Site.NYLRRC.json.Gender = gender === "M" ? "male" : "female";
                });
            },

            /*
             * 1. The show & hide of the payment option EFT
             *    screen depending on what the prospect selects.
             * 2. Apply the name to the account holder field when
             *    EFT is selected
             */
            BindPaymentOptions: function () {
                jQuery('input[name="PaymentOption"]').click(function () {
                    if (jQuery(this).val() === 'A') {
                        const fn = jQuery("#txtFirstName").val() || jQuery("#FirstName").val();
                        const ln = jQuery("#txtLastName").val() || jQuery("#LastName").val();
                        jQuery('#txtAccountHolder').val(fn + ' ' + ln);
                        jQuery('#eft-container').slideDown(500);
                        _log("showing eft container");
                    } else {
                        jQuery('#eft-container').slideUp(500);
                        _log("hiding eft container");
                    }
                });

                // payment option for EFT preselected, show the container
                if (jQuery('input[name="PaymentOption"]:checked').val() === "A") {
                    const accountHolderName = jQuery('#txtAccountHolder').val();
                    if (accountHolderName === undefined || accountHolderName === '')
                        jQuery('#txtAccountHolder').val(jQuery('#txtFirstName').val() + " " + jQuery('#txtLastName').val());

                    jQuery("#eft-container").show();
                }
            },

            ApplyPushState: function (section) {
                jQuery('.data-gather-step').hide();
                if (section) {
                    if (section.charAt(0) === "/")
                        section = section.substr(1);
                    section = section.toLowerCase();

                    window.history.pushState({ step: section }, '', '/Apply/Application/' + section);
                    _log("Applying push state for section: " + section);
                }

                if (!section) {
                    _log('No push state.  Hiding all but step 1');
                    Site.ApplicationForm.HighlightNavigation(0);
                    jQuery('.data-gather-step').first().show();
                    return false;
                }

                const elem = jQuery.find('[data-val-form-section="' + section.toLowerCase() + '"]');
                _log("Element found: " + elem);

                // figure out the index from hte data section name
                const dataGatherSteps = $('.data-gather-step');
                for (let i = 0; i < dataGatherSteps.length; i++)
                    if (jQuery(dataGatherSteps[i]).attr('data-val-form-section') === section)
                        Site.ApplicationForm.HighlightNavigation(i);

                jQuery(elem).show();
            },

            ValidateQuoteInApp: function () {
                const qia = jQuery('.app-quote form');
                if (qia.length > 0 && !qia.validate().form()) {
                    Site.ApplicationForm.ScrollToError();
                    return false;
                }
                return true;
            },
            HandleQuoteInAppSubmit: function () {
                const qia = jQuery('.app-quote form');
                _log("catching submit on qia");
                if (qia.validate().form()) {
                    Site.ApplicationForm.FireQuoteUpdate();
                    return false;
                }
                return false;
            },

            SetupBeneficiaries: function () {
                const $addBeneficiary = $(".add-beneficiary");
                const $deleteBeneficiary = $(".delete-beneficiary");
                const beneRowSelector = ".beneficiary-row";
                const distributeSelector = ".dist-even";

                $(beneRowSelector).find("input[id$='BeneShare'").change(function () {
                    runningTotal();
                });
                let distributeVisible = function () {
                    visibleCount = $(beneRowSelector + ":visible").length
                    if (visibleCount <= 1) {
                        $(distributeSelector).hide();
                        return;
                    }
                    $(distributeSelector).show();
                }
                let runningTotal = function () {
                    let visibleRows = $(beneRowSelector + ":visible");
                    if (visibleRows.length == 1)
                        $("#totalBene").hide();
                    else
                        $("#totalBene").show();
                    let sum = 0;
                    visibleRows.each(function (index, row) {
                        let shareVal = parseInt($(row).find("input[id$='BeneShare'").val());
                        if (!isNaN(shareVal))
                            sum += shareVal;
                    });
                    _log("total share " + sum);

                    $("#totalBene").text(isNaN(sum) ? "" : "Total: " + sum + "%");


                }
                distributeVisible();
                $addBeneficiary.off('click');
                $addBeneficiary.on('click',function () {
                    let visibleCount = $(beneRowSelector + ":visible").length

                    const hiddenBene = $(beneRowSelector + ":hidden").first();
                    $(hiddenBene).show();
                    if (visibleCount == 3) {
                        $addBeneficiary.hide();
                    }
                    distributeVisible();
                   
                    $("input[id$='BeneShare'").val('');
                    runningTotal();
                });
                $(distributeSelector).on('click',function () {
                    let visibleRows = $(beneRowSelector + ":visible");
                    let count = visibleRows.length
                    let share = Math.floor(100 / count);
                    let sum = 0;
                    visibleRows.each(function (index, row) {
                        if (index < count - 1) {
                            sum = sum + share;
                            $(row).find("input[id$='BeneShare'").val(share);
                        }
                        else {
                            $(row).find("input[id$='BeneShare'").val(100 - sum);
                        }

                    });
                    runningTotal();

                });
                $deleteBeneficiary.on('click',function () {
                    let beneRow = $(this).closest(beneRowSelector)
                    //blank out everything 
                    beneRow.find("input").val('')
                    beneRow.find("input[id$='BeneficiaryId']").val('0');
                    beneRow.find("select").val("");
                    beneRow.hide();

                    var firstDivId = beneRow.find("input[id$='FirstName']").attr("id");

                    let otherBene = $(beneRowSelector).not(function (n, elem) {
                        return $(elem).find("input[id$='FirstName']").attr("id") == firstDivId;
                    });
                    otherBene.find("input[id$='BeneShare']").val('');
                    let visibleCount = $(beneRowSelector + ":visible").length
                    $addBeneficiary.show();

                    if (visibleCount == 1) {
                        $("#Beneficiaries_0__BeneShare").val('100');
                    }
                    distributeVisible();
                    runningTotal();
                });
            },


            /*
             * Set up toggle for coverage amount.  If value selected is "other"
             * then show the other coverage amount field.
             */
            SetupCoverageAmount: function () {
                const coverageAmount = jQuery("#CoverageAmount");
                const otherCoverageAmount = jQuery("#OtherCoverageAmount");
                //const otherCoverageAmountMsg = jQuery("[data-valmsg-for='OtherCoverageAmount']");
                //otherCoverageAmountMsg.hide();

                if (coverageAmount.val() === "other") {
                    otherCoverageAmount.removeClass("d-none");
                    //otherCoverageAmountMsg.hide();
                }

                coverageAmount.on('change', function (e) {
                    if (jQuery(this).val() === "other") {
                        otherCoverageAmount.removeClass("d-none");
                        jQuery('.money-icon i').removeClass("d-none");
                    } else {
                        otherCoverageAmount.addClass("d-none");
                        jQuery('.money-icon i').addClass("d-none");
                    }
                });
            },

            HighlightNavigation: function (idx) {
                _log("Highlighting nav item " + idx);
                $('.app-nav .nav-link').removeClass('active');

                // assume index is zero based
                idx = idx + 1;
                $('.app-nav .nav-link:nth-child(' + idx + ')').addClass('active');
            },
            UpdateDataLayer: function (stepIndex) {
                var step = (stepIndex === 0 ? "Personal Info" : (stepIndex === 1 ? "Coverage" : (stepIndex === 2 ? "Health Questions" : "Step" + ++stepIndex)));
                window.formEventData[0].form.progress.step = step;
                var lastIndex = window.pageEventData.page.name.lastIndexOf(" > ");
                if (lastIndex !== -1) {
                    window.pageEventData.page.name = window.pageEventData.page.name.substring(0, lastIndex) + " > " + step;
                }
            },
            BindCallToAction: function () {
                if (!_editMode) {
                    _log('>> Binding CTA button clicks');
                    jQuery('.app-submit').on('click',
                        function (e) {
                            _log("CTA Click...");

                            const dataGatherSteps = jQuery('.data-gather-step');
                            for (let i = 0; i < dataGatherSteps.length; i++) {
                                const elem = jQuery(dataGatherSteps[i]);
                                if (elem.is(':visible')) {

                                    // validate the form before proceeding
                                    jQuery(form).validate().form();
                                    if (!jQuery(form).valid()) {
                                        Site.ApplicationForm.ScrollToError();
                                        deactivateSpinner();
                                        return false;
                                    }

                                    // validate the QIA form
                                    const qiaValid = Site.ApplicationForm.ValidateQuoteInApp();
                                    if (!qiaValid)
                                        return false;

                                    Site.ApplicationForm.ShowNextElement(i + 1);
                                    break;
                                }
                            }
                        });
                } else {
                    _log('Viewing application in page editor - ignoring CTA button clicks');
                }
            },

            ShowNextElement: function (idx) {
                var dataGatherSteps = $('.data-gather-step');
                if (idx === dataGatherSteps.length) {
                    _log("Submitting form " + form);
                    Site.ApplicationForm.ToggleButtonProcessing(jQuery('.app-submit'));
                    toggleSpinner(form);
                    jQuery(form).submit(function (event) {
                        if (!$(this).valid()) {
                            return false;
                        }
                        return true;
                    }).submit();
                } else {
                    _log("Hide and show the data gather step...");
                    var step = $(dataGatherSteps[idx]);
                    var stepHref = step.attr('data-val-form-section');
                    window.pageEventData.page.name = window.pageEventData.page.name.substr(0, window.pageEventData.page.name.lastIndexOf(">")).trim() + " > " + stepHref;
                    window.history.pushState({ step: stepHref }, '', baseurl + '/' + stepHref);

                    var previousStep = $(dataGatherSteps[idx - 1]);
                    previousStep.hide();

                    Site.ApplicationForm.HighlightNavigation(idx);
                    $(dataGatherSteps[idx]).show();
                    $('html,body').animate({ scrollTop: 0 }, 'slow');

                    Site.ApplicationForm.UpdateDataLayer(idx);
                    dataLayerPageLoad();
                }
            },

            /*
             * Set up the javascript for barebones functionality
             * that allows the page editor to work as expected.
             */
            InitializeForPageEditor: function () {

                // Show all data gather steps for page editor
                $('.data-gather-step').show();

                // Show only the first bene row
                $('.beneficiary-row:not(:first)').hide();

                // show the EFT section
                $('#eft-container').show();
            },
            ToInches: function (n) {
                return Math.floor(n / 12) + "'" + (n % 12) + '"';
            },
            RangeSlider: function (formSelector) {

                if ($(formSelector).find('#HeightinFeet').length && $(formSelector).find('#HeightinFeet').val()) {
                    var heightFormat = $(formSelector).find('#HeightinFeet').val() * 12;
                    heightFormat += 1 * $(formSelector).find('#HeightinInches').val();
                    $(formSelector).find('#txtHeightSlider').val('Y');
                    $('input[type="range"]').val(heightFormat).change();
                }
                else {
                    $('#HeightFeetInches').val("51");
                }

                $('input[type="range"]').rangeslider({
                    // Feature detection the default is `true`.
                    // Set this to `false` if you want to use
                    // the polyfill also in Browsers which support
                    // the native <input type="range"> element.
                    polyfill: false,

                    // Default CSS classes
                    rangeClass: "rangeslider",
                    disabledClass: "rangeslider--disabled",
                    horizontalClass: "rangeslider--horizontal",
                    fillClass: "rangeslider__fill",
                    handleClass: "rangeslider__handle",
                    // Callback function
                    onInit: function () {
                        $rangeEl = this.$range;
                        // add value label to handle
                        var $handle = $rangeEl.find(".rangeslider__handle");
                        var heightFormat;
                        heightFormat = Site.ApplicationForm.ToInches(this.value);

                        var handleValue =
                            '<div class="rangeslider__handle__value">' +
                            heightFormat +
                            "</div>";
                        $handle.append(handleValue);

                        // get range index labels
                        var rangeLabels = this.$element.attr("labels");
                        rangeLabels = rangeLabels.split(", ");

                        // add labels
                        $rangeEl.append(
                            '<div class="rangeslider__labels"></div>'
                        );
                        $(rangeLabels).each(function (index, value) {
                            $rangeEl
                                .find(".rangeslider__labels")
                                .append(
                                    '<span class="rangeslider__labels__label">' +
                                    value +
                                    "</span>"
                                );
                        });

                        if ($(formSelector).find('#txtHeightSlider').val() == 'Y')
                            $(".rangeslider--horizontal").addClass("slider-focus");

                    },

                    // Callback function
                    onSlide: function (position, value) {
                        var heightFormat = Site.ApplicationForm.ToInches(this.value);
                        var $handle = this.$range.find(
                            ".rangeslider__handle__value"
                        );
                        $handle.text(heightFormat);
                        this.$element
                            .next("div.rangeslider")
                            .addClass("slider-focus");
                        this.$element.prev().attr("value", "Y");
                        var spotvalidate = this.$element.prev();
                        var validator = $("form").validate();
                        validator.element(spotvalidate);

                        let height = this.$element.val();
                        let feet = Math.floor(height / 12);
                        let inches = (height - (feet * 12));

                        $(formSelector).find('#HeightinFeet').val(feet);
                        $(formSelector).find('#HeightinInches').val(inches);

                    },
                    // Callback function
                    onSlideEnd: function (position, value) { },
                });
            }
        };



    })();
})(jQuery);;
var Site = window.Site || {};

(function (jQuery, undefined) {
    Site.ApplicationConfirm = (function () {
        var genericFormExperienceScript = new Site.Form();
        var form;

        return {
            Initialize: function (formSelector) {

                form = formSelector;
                if (typeof _SC_EXPERIENCE_EDITOR_EDITING !== undefined) {
                    _editMode = _SC_EXPERIENCE_EDITOR_EDITING;
                    if (_editMode) {
                        return;
                    }
                }

                _log(">> Initializing the confirm form: " + formSelector);

                genericFormExperienceScript.Initialize(formSelector,
                    {
                        onSubmitOverride: Site.ApplicationConfirm.SubmitConfirmForm
                    });

                jQuery('[data-toggle="tooltip"]').tooltip({ delay: { "hide": 2000 } });
                jQuery('span.field-validation-error').show();

                Site.ApplicationConfirm.SetupCancelButton();
                Site.ApplicationConfirm.SetupEditToggle();
                Site.ApplicationConfirm.SetupPersonalConfirmForm();
                Site.ApplicationForm.SetupMasks();          
                Site.ApplicationForm.SecurePersonalInfo();
                Site.ApplicationForm.SetupCoverageAmount();
                Site.ApplicationForm.SetupBeneficiaries();
                Site.ApplicationForm.BindPaymentOptions();
                if (form == "#f-confirm-health") Site.ApplicationForm.SetupStatementOfHealth();
                Site.ApplicationForm.RangeSlider('#f-confirm-personal');
            },
            /**
             * Setup the consent modal functionality
             * */
            SetupConsentAndSign: function (modalId) {
                var consentChkBox = $("#ConsentAndSign"), consentAlert = $("#consent"),
                    consentForm = $('#f-confirm-consent'), consentBtn = $('#consentBtn');

                // Set form to editing to initialize validation
                inEditMode(true);

                if (consentChkBox[0].checked) {
                    ShowConsentAndSignSuccess();
                }

                // On click we submit the form
                consentAlert.on("click", function (evt) {

                    // If the consent isn't checked launch modal.
                    if (!consentChkBox[0].checked) {
                        // Launch the modal
                        $('#' + modalId).modal('show');
                    }
                });

                // On click we submit the form but also uncheck the checkbox
                consentChkBox.on("click", function (evt) {

                    if (!consentChkBox[0].checked) {
                        // submit the form
                        submitConsentAndSign(consentForm);
                        evt.stopPropagation();
                        return;
                    }

                    // Remove valid class for the checkbox which causes it to look "unchecked" while the modal is displayed.
                    consentChkBox.removeClass("valid");

                    // Stop the event propagation 
                    evt.preventDefault();
                    evt.stopPropagation();

                    // Launch the modal
                    $('#' + modalId).modal('show');
                });

                // On the consent button click we close the modal and check the checkbox.
                consentBtn.on("click", function (e) {
                    // show checkbox checked.
                    consentChkBox[0].checked = true;
                    // submit the form
                    submitConsentAndSign(consentForm);

                });

                // bind to the checkbox's invalid event
                consentForm.on("invalid", function () {
                    if (!consentChkBox[0].checked) {
                        ShowConsentAndSignError();
                    }
                });

                // submit consent and sign
                function submitConsentAndSign(formObject) {
                    const url = formObject.attr("action");
                    const id = '#' + formObject[0].id;
                    toggleSpinner(id);

                    jQuery.ajax({
                        type: "POST",
                        url: url,
                        data: formObject.serialize(),
                        success: function (result) {
                            toggleSpinner(id, true);
                            if (result.toLowerCase() == "true") {
                                // show success
                                ShowConsentAndSignSuccess();
                            }
                            else {
                                ShowConsentAndSignError();
                            }
                        }
                    });
                }

                function inEditMode(mode) {
                    // Set the form's edit mode so that the cta will validate
                    if (mode) consentForm.attr("data-val-editing", mode);
                    else consentForm.removeAttr("data-val-editing");
                }

                function ShowConsentAndSignError() {
                    consentAlert.removeClass("alert-success alert-primary");
                    consentAlert.addClass("alert-danger");
                    // Set the form's edit mode so that the cta will validate
                    inEditMode(true);
                    // validate form
                    consentForm.valid();
                }

                function ShowConsentAndSignSuccess() {
                    consentAlert.removeClass("alert-primary alert-danger");
                    consentAlert.addClass("alert-success");
                    // Clear the form's edit mode since it now valid.
                    inEditMode(false);
                    // validate form
                    consentForm.valid();

                }
            },
            /**
             * Tell the "span" around the weight to have a min width on IE
             */
            SetupPersonalConfirmForm: function () {
                const ua = window.navigator.userAgent;
                if (ua.indexOf("MSIE") > 0 || ua.indexOf("Trident") > 0) {
                    jQuery("#container-confirm-personal").find(".d-flex span").css("min-width", "150px");
                }
            },

            /**
             * Set up the click event on the "edit" button to hide the readonly
             * mode items and display the "edit" mode items from the data-val-mode
             * attribute.
             *
             * When the form is in readonly mode it changes it to edit mode
             *
             * When the form is in edit mode it submits
             */
            SetupEditToggle: function () {

                jQuery(form).find(".confirm-submit").click(function (e) {
                    var f = jQuery(this).closest("form");

                    if (f.attr("data-val-editing") === "true") {
                        // fire validation on all forms prior to submit - why?
                        jQuery('form').each(function () {
                            if (this.id !== "f-confirm-consent") {
                                jQuery(this).valid();
                            }
                        });
                        if (jQuery(f).validate().valid()) {
                            Site.ApplicationForm.FireQuoteUpdate();
                        }

                        jQuery(f).submit();

                    } else {
                        _log("Showing edit mode for " + f.attr('id'));
                        jQuery(f).find("[data-val-mode='readonly']").hide();
                        jQuery(f).find("[data-val-mode='edit']").show();

                        const validator = f.validate();
                        validator.resetForm();
                        jQuery(f).find('.health-risks').addClass("d-flex");
                        if (f[0].id == "f-confirm-health") {
                            Site.ApplicationForm.ToggleHealthRisks();
                        }
                        jQuery(f).find('#HeightFeetInches').rangeslider('update', true);
                        var saveText = encodeURIComponent($(".data-val-save-copy").val());
                        jQuery(this)
                            .html(saveText);

                        f.attr("data-val-editing", "true");
                    }
                    e.preventDefault();
                });

            },
            InitTappies: function (formId) {
                $("form" + formId + " input[type = radio]").each(function () {
                    var selectedValue = $("input[name='" + this.name + "']:checked").val();
                    if ($("#" + this.id).val() == selectedValue) {
                        $('label[for=' + this.id + ']').addClass('active');
                    }
                    else {
                        $('label[for=' + this.id + ']').removeClass('active');
                    }

                    if ($("#" + this.id).attr("hasRisks") == "True") {
                        $("input.health-risks").each(function () {
                            $(this).checked = false;
                        });
                    }
                });
            },
            SubmitConfirmForm: function (formId) {
                jQuery(formId).submit(function (event) {
                    event.preventDefault();
                    jQuery('span.field-validation-error').show();

                    if (jQuery(this).valid()) {
                        toggleSpinner(formId);

                        const formObject = jQuery(this);
                        const url = formObject.attr("action");
                        const resultContainer = formObject.attr("data-ajax-update");
                        
                        jQuery.ajax({
                            type: "POST",
                            url: url,
                            data: formObject.serialize(),
                            success: function (data) {
                                jQuery(resultContainer).replaceWith(data);
                                toggleSpinner(formId, true);
                                Site.ApplicationConfirm.InitTappies(formId);
                            }
                        });
                    }
                });
            },

            SetupCancelButton: function () {
                jQuery(".btn-cancel").on("click", function (evt) {
                    var f = jQuery(this).closest("form");
                    evt.preventDefault();
                    jQuery(f).find("[data-val-mode='edit']").hide();
                    jQuery(f).find("[data-val-mode='readonly']").show();
                    jQuery('.health-risks').removeClass("d-flex");

                    var btn = jQuery(this).next('.confirm-submit');
                  
                    var editText = encodeURIComponent($(".data-val-edit-copy").val());
                    btn.html(editText);
                    f.removeAttr("data-val-editing");
                    jQuery('.health-risk').prop('disabled', true);
                    return false;
                });
            }
        };
    })();
})(jQuery);;
var Site = window.Site || {};


/*
 * Confirm Container handles javascript tech for the final confirm and sign
 * button at the bottom of the page. This form needs to check for confirm and sign
 * edit forms that might be open or in an error state before moving to sign and submit.
 */
(function (jQuery, undefined) {
    Site.ApplicationConfirmContainer = (function () {
        var genericFormExperienceScript = new Site.Form();
        const MAX_SUBMISSION_ATTEMPTS = 150;
        let submissionAttempt = 0;
        let submissionIntervalId = undefined;
        let openForms = [];
        
        return {
            Initialize: function (formSelector) {
                form = formSelector;
                if (typeof _SC_EXPERIENCE_EDITOR_EDITING !== undefined) {
                    _editMode = _SC_EXPERIENCE_EDITOR_EDITING;
                    if (_editMode) {
                        return;
                    }
                }

                if (form == "#f-confirm-health") Site.ApplicationForm.SetupStatementOfHealth();
                Site.ApplicationConfirmContainer.SetupCTA();
                Site.ApplicationForm.SetupQuote();
                Site.ApplicationForm.SetupRateChart();
                jQuery(document).ajaxComplete(function(evt, xhr, settings) {
                    const data = decodeURIComponent(settings.data);
                    const actionKey = data.match(/scAction=(.+?)&/i);
                    if (actionKey) {
                        delete openForms[actionKey[1]];
                    }
                });
            },
            /**
             * *
             * Scrolls to the form top in case the user has a form in edit mode and attempts to submit and continue
             * 
             * @param {any} form
             */
            ScrolltoForm: function (form) {
                let y = form.offset().top;
                if (y > 50) // add a little top margin to the scroll position if available
                    y = y - 50;
                jQuery("html,body").animate({ scrollTop: y }, 500);
            },
            /*
             * Submit handler which checks if other forms are in an error state
             *
             * It will loop through all forms.  If the form is in "edit mode" it
             * checks to see if it's invalid.  If so, stop processing and scroll back
             * up to the error.  If it's valid, attempt to submit it before continuing.
             *
             */
            SetupCTA: function () {
                jQuery('.app-submit').on('click', function (e) {
                    Site.ApplicationConfirmContainer.ToggleButtonProcessing();
                    const forms = jQuery('.editable-form');

                    // loop through forms to determine if any are in edit mode and invalid
                    for (let i = 0; i < forms.length; i++) {
                        const form = jQuery(forms[i]);
                        const editMode = form.attr('data-val-editing');
                        if (editMode !== undefined && editMode === "true") {
                            // one of the confirm forms is in edit mode
                            if (!form.validate().form()) {
                                _log("Confirm Form " + form.attr('id') + " is not valid.");
                                form.trigger("invalid");
                                Site.ApplicationForm.ScrollToError();
                            }
                            else {
                                // form is still in edit mode
                                Site.ApplicationConfirmContainer.ScrolltoForm(form);
                            }

                            Site.ApplicationConfirmContainer.ToggleButtonProcessing();
                            e.preventDefault();
                            return false;
                        }
                    }

                    // loop through forms again to submit any that are left open
                    // assumption here is that they're valid
                    submissionAttempt = 0; // reset number of submission attempts 
                    for (let i = 0; i < forms.length; i++) {
                        const form = jQuery(forms[i]);
                        const editMode = form.attr('data-val-editing');
                        
                        if (editMode !== undefined && editMode === "true") {
                            openForms[form.find("[name='scAction']").val()] = "processing";
                            form.submit();
                            _log("Adding form to submission table...");
                        }
                    }
                    //Site.ApplicationConfirmContainer.ToggleButtonProcessing();

                    submissionIntervalId = window.setInterval(Site.ApplicationConfirmContainer.SubmitConfirmForm, 100);
                });
            },

            SubmitConfirmForm: function () {
                if (submissionAttempt > MAX_SUBMISSION_ATTEMPTS) {
                    _log("Reached max submission attempts.  Stopping interval " + submissionIntervalId);
                    window.clearInterval(submissionIntervalId);
                }
                submissionAttempt++;
                let arrayCount = Object.keys(openForms).length;

                _log("Attempt " + submissionAttempt + " of " + MAX_SUBMISSION_ATTEMPTS);
                _log("Open Forms array: " + arrayCount);


                if (arrayCount === 0) {
                    _log("All forms submitting through ajax have completed. Submitting page");
                    window.clearInterval(submissionIntervalId);
                    submissionAttempt = 0;
                    jQuery('#f-confirm-app').submit();
                } else {
                    _log("Waiting on " + arrayCount + " more form(s) to finish processing.");
                }

            },

            ToggleButtonProcessing: function () {
                const btn = jQuery('.app-submit');
                Site.ApplicationForm.ToggleButtonProcessing(btn);
            }
        };
    })();
})(jQuery);;
var Site = window.Site || {};

(function(jQuery, undefined) {
    Site.ApplicationSign = (function () {
        var genericFormExperienceScript = new Site.Form();
        var form;

        return {
            Initialize: function (formSelector) {
                _log(">> Initializing Sign and Submit form page");

                form = formSelector;
                Site.ApplicationForm.HighlightNavigation(jQuery('.nav-link').length - 1);
                Site.ApplicationSign.ToggleSubmitButton(false);
                Site.ApplicationSign.BindElements();

                jQuery('.app-submit').on('click', function(e) {
                    Site.ApplicationForm.ToggleButtonProcessing(jQuery(this));
                    e.preventDefault();
                });
            },

            /*
             * Generic element binding for sign and submit form:
             *  - Set up icertify checkbox to toggle the submit button on and off
             *  - Bind form submit to CTA
             */
            BindElements: function() {
                jQuery("#ICertify").on("change", function () {
                    Site.ApplicationSign.ToggleSubmitButton(jQuery(this).is(":checked"));
                });

                jQuery('.app-submit').on('click', function (e) {
                    jQuery(form).submit();
                });
            },

            ToggleSubmitButton: function (enable) {
                const btn = jQuery(".lf-submit").find("button");

                if (enable) {
                    btn.removeClass("btn-secondary").addClass("btn-primary");
                    btn.removeAttr("disabled");
                } else {
                    btn.removeClass("btn-primary").addClass("btn-secondary");
                    btn.attr("disabled", "disabled");
                }
            }
        };
    })();
})(jQuery);
;
var Site = window.Site || {};

(function(jQuery, undefined) {
    Site.ApplicationVerify = (function () {
        var genericFormExperienceScript = new Site.Form();
        var form;

        return {
            Initialize: function (formSelector) {
                form = formSelector;
                if (typeof _SC_EXPERIENCE_EDITOR_EDITING !== undefined) {
                    _editMode = _SC_EXPERIENCE_EDITOR_EDITING;
                    if (_editMode) {
                        return;
                    }
                }

                _log(">> Initializing the verify form: " + formSelector);
                jQuery('[data-toggle="tooltip"]').tooltip({ delay: { "hide": 2000 } });

                
                jQuery('span.field-validation-error').show();

                Site.ApplicationForm.SecurePersonalInfo();
                Site.ApplicationForm.SetupMasks();
                Site.ApplicationForm.HighlightNavigation(jQuery('.nav-link').length);
                $('#AarpMemberYes, #AarpMemberNo').click(function () {
                    Site.ApplicationVerify.ToggleMembershipConsent();
                });
                genericFormExperienceScript.Initialize(formSelector, {});

                jQuery(".app-submit").on("click", function () {
                    jQuery(form).validate().form();
                    if (!jQuery(form).valid()) {
                        Site.ApplicationForm.ScrollToError();
                        return false;
                    }
                    jQuery("#f-verify-app").submit();
                });
            },
            ToggleMembershipConsent: function (control) {
                let _val = $("input[name='AarpMember']:checked").val();
                let nonMembertext = $('#nonmembertext').val();
                let membertext = $('#membertext').val();
                
                if (_val === 'Y') {
                    $('#IsNotAarpMember').hide();
                    $(":button").text(membertext);     
                }
                else {
                    $('#IsNotAarpMember').show();
                    $(":button").text(nonMembertext);  
                }
            }
        };

       

    })();
})(jQuery);
;
var Site = window.Site || {};

(function (jQuery, undefined) {

    Site.SingleStep = (function () {
        var genericFormExperienceScript = new Site.Form();
        var form;

        return {
            Initialize: function (formSelector) {
                form = formSelector;

                if (typeof _SC_EXPERIENCE_EDITOR_EDITING !== undefined) {
                    _editMode = _SC_EXPERIENCE_EDITOR_EDITING;
                    if (_editMode) {
                        Site.ApplicationForm.InitializeForPageEditor();
                        return;
                    }
                }

                genericFormExperienceScript.Initialize(formSelector, {});

                jQuery('[data-toggle="tooltip"]').tooltip({ delay: { "hide": 2000 } });
                jQuery('span.field-validation-error').show();

                Site.ApplicationForm.SetupSessionExpiration();
                Site.ApplicationForm.SetupMasks();
                Site.ApplicationForm.SetupNavigationLinks();
                Site.ApplicationForm.SecurePersonalInfo();
                Site.ApplicationForm.SetupStatementOfHealth();

                Site.SingleStep.SetupRiderListeners();


                jQuery('.app-submit').on('click', function (e) {
                    _log("CTA Click...");
                    toggleSpinner(form);
                    jQuery(form).validate().form();
                    if (!jQuery(form).valid()) {
                        Site.ApplicationForm.ScrollToError();
                        deactivateSpinner();
                        return false
                    }
                    jQuery(form).submit();
                });
            },
            /*
             * Establish events bound to listeners from other
             * form inputs.
             */
            SetupRiderListeners: function () {
                jQuery("input[name='TobaccoQuestion']").change(function () {
                    var smoker = jQuery("input[name='TobaccoQuestion']:checked").val();
                    Site.SingleStep.RateUpdate(smoker);
                    if (window.formEventData) {
                        window.formEventData[0].form.attributes["smoker"] = smoker;
                    }
                });
            },
            RateUpdate: function (smk) {
                var ur = '/ddk/ApplicationQuote/GetRiderPremium?smk=' + smk;
                setLoading();
                jQuery.ajax({ url: ur }).then(function (result) {

                    var data = '($' + result.selectedPremiumAmount;
                    jQuery(".premiumIncrease").text(data);
                    var i = 0;
                    jQuery.each(result.riders, function (i, item) {
                        var classp = ".premiumIncrease-" + i;
                        data = '($' + result.riders[i].Premium;
                        jQuery(classp).text(data);
                    });
                    
                }

                );
            }

        }
       
        function setLoading() {
            jQuery("[class^='premiumIncrease']")
                .html(
                    "<div class=\"spinner-border spinner-border-sm\" role=\"status\"><span class=\"sr-only\">Loading...</span></div>");
                
        }
    })();
})(jQuery);
var Site = window.Site || {};

(function (jQuery, undefined) {
    Site.NotInGoodOrderForm = (function () {
        var genericFormExperienceScript = new Site.Form();
        var form;

        return {
            Initialize: function (formSelector) {
                form = formSelector;

                genericFormExperienceScript.Initialize(formSelector, {});
                jQuery('.data-gather-step').show();
                jQuery('[data-toggle="tooltip"]').tooltip({ delay: { "hide": 2000 } });
                jQuery('span.field-validation-error').show();
                Site.ApplicationForm.SetupMasks();
                jQuery('.app-submit').on('click', function (e) {
                    _log("CTA Click...");
                    jQuery(form).submit(function (event) {
                        if (!$(this).valid()) {
                            return false;
                        }
                        return true;
                    });
                   
                    jQuery(form).submit();
                });
            },
            /*Hide if value passed in*/
            ToggleSmoker: function () {
                if (jQuery('#TobaccoAnswerNotRequired').val() === "X") {
                    jQuery('.smoker-tappies').hide();
                } else {
                    jQuery('.smoker-tappies').show();
                }
            }

        };



    })();
})(jQuery);
;
var Site = window.Site || {};

(function(jQuery, undefined) {
    Site.LightVerification = (function () {
        var genericFormExperienceScript = new Site.Form();
        var form;

        return {
            Initialize: function (formSelector) {
                form = formSelector;
                if (typeof _SC_EXPERIENCE_EDITOR_EDITING !== undefined) {
                    _editMode = _SC_EXPERIENCE_EDITOR_EDITING;
                    if (_editMode) {
                        return;
                    }
                }

                _log(">> Initializing the verify form: " + formSelector);
                jQuery('[data-toggle="tooltip"]').tooltip({ delay: { "hide": 2000 } });

                
                jQuery('span.field-validation-error').show();

                Site.ApplicationForm.SecurePersonalInfo();
                Site.ApplicationForm.SetupMasks();
                genericFormExperienceScript.Initialize(formSelector, { onSubmitOverride: onVerifySubmit });
            },
        };

        function onVerifySubmit(formSelector) {
            _log(">> onVerifySubmit [" + formSelector + "]");
            $(formSelector).submit(function (event) {
                $("span.field-validation-error").show();


                if ($(this).valid()) {
                    if ($('#lightVerificationModal').length) {
                        $('#lightVerificationModal').modal({ show: true });
                    }
                    Site.ApplicationForm.ToggleButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));
                    Site.Form().toggleSpinner();
                    return true;
                }
            });
        }

    })();
})(jQuery);
;


jQuery.validator.addMethod("typeaheadrequired", function (value, element) {
    _log(">> Type Ahead Required Validator");
    let typeAheadItemCount = $('#typeAheadSelectionList li[data-val-typeahead-key]').length;
    _log(">> Found " + typeAheadItemCount + " selected items");
    return typeAheadItemCount > 0;
});

jQuery.validator.unobtrusive.adapters.add("typeaheadrequired", [], function (options) {
    options.rules["typeaheadrequired"] = options.params;
    options.messages["typeaheadrequired"] = options.message;
});
$.validator.addMethod('requiredifnotchecked', function (value, element, parameters) {
    var controlType = $(":input[name$='" + parameters.dependentproperty + "']").attr("type");
    if((controlType == "checkbox")|| (controlType ==undefined ) ){
        var control = $("input[name$='" + parameters.dependentproperty + "']:checked");
        var actualValue = control.val();
        if (actualValue == undefined || actualValue === false) {
            var isValid = $.validator.methods.required.call(this, value, element, parameters);
            return isValid;
        }
    }
    return true;
});
$.validator.unobtrusive.adapters.add('requiredifnotchecked', ['dependentproperty'], function (options) {
    options.rules['requiredifnotchecked'] = options.params;
    options.messages['requiredifnotchecked'] = options.message;
});
jQuery.validator.unobtrusive.adapters.add("dynamicrange", ['minvalueproperty', 'maxvalueproperty'], function (options) {
    options.rules["dynamicrange"] = options.params;
    if (options.message != null) {
        $.validator.messages.dynamicrange = options.message;
    }
});
jQuery.validator.addMethod("dynamicrange", function (value, element, params) {
    _log(">> Dynamic Range Field Validator");
    var prefix = '';
    if (/[.]/.test(element.name)) {
        prefix = element.name.split('.')[0] + ".";
    }
    if ($(element).val().length == 0)
        return true;
    if (($("#QuestionType").length > 0) && ($("#QuestionType").val() === 'DATE')) {

        var y = $('#YearSelection').val() + "-" + $('#MonthSelection').val() + "-" + '01';
        var selectedDate = new Date(y);
        var minDate = new Date($('#MinDate').val());
        var maxDate = new Date($('#MaxDate').val());
        if ((selectedDate < minDate) || (selectedDate > maxDate)) {
            var message = $(element).attr('data-val-dynamicrange');
            $.validator.messages.dynamicrange = $.validator.format(message,
                minDate.getMonth() + 1 + "-" + minDate.getFullYear(),
                maxDate.getMonth() + 1 + "-" + maxDate.getFullYear());
            return false;
        }  
            return true;
        
    }
    if (($("#QuestionType").length > 0) && ($("#QuestionType").val() === 'UNITIZED')) {

        var minValue = parseFloat($('input[name="' + prefix + params.minvalueproperty + '"]').val(), 10);
        var maxValue = parseFloat($('input[name="' + prefix + params.maxvalueproperty + '"]').val(), 10);
        var currentValue = parseFloat(value, 10);
        if (isNaN(minValue) ||
            isNaN(maxValue) ||
            isNaN(currentValue) ||
            minValue > currentValue ||
            currentValue > maxValue) {
            var message = $(element).attr('data-val-dynamicrange');
            $.validator.messages.dynamicrange = $.validator.format(message, minValue, maxValue);
            return false;
        }
        return true;
    } else {
        var minValue = parseInt($('input[name="' + prefix + params.minvalueproperty + '"]').val(), 10);
        var maxValue = parseInt($('input[name="' + prefix + params.maxvalueproperty + '"]').val(), 10);
        var currentValue = parseInt(value, 10);
        if (isNaN(minValue) ||
            isNaN(maxValue) ||
            isNaN(currentValue) ||
            minValue > currentValue ||
            currentValue > maxValue) {
            var message = $(element).attr('data-val-dynamicrange');
            $.validator.messages.dynamicrange = $.validator.format(message, minValue, maxValue);
            return false;
        }
        return true;
    }

    return true;
});

jQuery.validator.addMethod("requirednotempty", function (value, element) {
    if ($.trim(value) == "") {
        return false;
    }
    return true;
});

jQuery.validator.unobtrusive.adapters.add("requirednotempty", [], function (options) {
    options.rules["requirednotempty"] = options.params;
    options.messages["requirednotempty"] = options.message;
});



(function ($) {
    Site.ApplicationInterview = (function () {
        var _debug = !/^www/.test($(location).attr('hostname'));
        var genericFormExperienceScript = new Site.Form();

        let typeaheadds = [];

        return {
            InitializeAjax: function (formSelector) {
                genericFormExperienceScript.Initialize(formSelector, { onSubmitOverride: onAjaxApplicationInterviewFormSubmit });
                $(formSelector).validate({ ignore: [] });
                jQuery('[data-toggle="tooltip"]').tooltip();
                jQuery('span.field-validation-error').show();

                $("#saveHref").click(function () {
                    $("#saveinterviewmodal").modal();

                });

                Site.ApplicationInterview.ScrollToError();
                Site.ApplicationInterview.InitTappies(formSelector);
                Site.ApplicationInterview.InitDropdownChange();
            
                $('.multiChoice:checkbox').change(function () {
                    //if none of the above exists then add logic for deselecting others when clicked.
                    if ($('#NONE_OF_ABOVE_CHOICE_CODE').length) {
                        if (($(this).attr('id') == "NONE_OF_ABOVE_CHOICE_CODE")) {
                            $('.multiChoice:checkbox').not(this).prop('checked', false);
                        } else {
                            $('#NONE_OF_ABOVE_CHOICE_CODE').prop('checked', false);
                        }
                    }     
                    if ($('#ANSWER_IS_UNKNOWN_CODE').length) {
                        if (($(this).attr('id') == "ANSWER_IS_UNKNOWN_CODE")) {
                            $('.multiChoice:checkbox').not(this).prop('checked', false);
                        } else {
                            $('#ANSWER_IS_UNKNOWN_CODE').prop('checked', false);
                        }
                    } 
                    if ($('.multiChoice:checkbox:checked').length >= 1) {
                        $('.multiChoice:checkbox').removeClass('input-validation-error');
                    }
                  
                });
                $('#TextAnswer').bind("keyup blur", function () {
                    Site.ApplicationInterview.UpdateCount($('#TextAnswer'));
                });
                $('#UnitAnswer').bind("keyup blur", function () {
                    var lengthCount = $(this).val().length;
                    if ($.trim(lengthCount)>0)
                        $('#UnknownAnswer').prop('checked', false);
                });
                $('#UnknownAnswer').change(function () {
                    if (this.checked) {
                        var form = $(formSelector);
                        // get validator object
                        var $validator = $(form).validate();

                        // get errors that were created using jQuery.validate.unobtrusive
                        var $errors = $(form).find(".field-validation-error span");
                        $errors.each(function() { $validator.settings.success($(this)); });
                        $validator.resetForm();
                    }

                });
                $('#TypeAheadSearch').keypress(function (e) {
                    if (e.which == 13) {
                        return false;
                    }
                });
               
            },

            CopyToClipboard: function (element) {
                var $temp = $("<input>");
                var $url = $(('#' + element)).attr('href');

                $("body").append($temp);
                $temp.val($url).select();
                document.execCommand("copy");
                navigator.clipboard.writeText($url);
                $temp.remove();
            },
            UpdateCount: function (element) {
                var lengthCount = $(element).val().length;
              
                var charactersLeft = 500 - lengthCount;
                if (lengthCount >= 350 && lengthCount <= 449)     
                {
                    $('#characters').attr("class", "text-md-gold");
                }
                if (lengthCount >= 450) {
                    $('#characters').attr("class", "text-md-garnet");
                }

                $('#characters').text(charactersLeft + '/500 Characters left');
              
            },
            ScrollToError: function () {
                const firstError = jQuery('.input-validation-error').first();
                if (firstError !== undefined && firstError.length > 0) {
                    let y = firstError.closest('form').offset().top - 175;
                    jQuery("html,body").animate({ scrollTop: y }, 500);
                }
            },
            ScrollToTopofPage: function () {
                $("html, body").animate({ scrollTop: 0 }, "slow");
            },
            LoadPreviousQuestion: function () {
                var formSelector = $('#interview-question-form');
                const resultContainer = formSelector.attr("data-ajax-update");
                Site.Form().ToggleButtonProcessing($("#btnpreviousQuestion"));
                Site.Form().toggleSpinner();
                $("#scAction-interviewquestion").val("LoadPreviousInterviewQuestion");
                $.ajax({
                    type: "POST",     
                    data: formSelector.serialize(),
                    success: function (data) {
                        jQuery(resultContainer).replaceWith(data);
                        rebindvalidators();
                        Site.ApplicationInterview.ScrollToTopofPage();
                        dataLayerPageLoad();
                    },
                    error: function (data) {
                        Site.Form().ToggleButtonProcessing(jQuery("#btnpreviousQuestion"));
                        Site.Form().toggleSpinner();
                        document.location.href = '/Apply/Interview/Invalid?Reason=Error';
                    }
                });
            },
            InitTappies: function (formId) {
                $("form input[type = radio]").each(function () {
                    var selectedValue = $("input[name='" + this.name + "']:checked").val();
                    if ($("#" + this.id).val() == selectedValue) {
                        $('label[for=' + this.id + ']').addClass('active');
                    }
                    else {
                        $('label[for=' + this.id + ']').removeClass('active');
                    }
                });
            },
            InitDropdownChange: function () {
                $("#MonthSelection").change(function () {
                    $('#UnknownAnswer').prop('checked', false);
                });
                $("#YearSelection").change(function () {
                    $('#UnknownAnswer').prop('checked', false);
                });
            },

            InitTypeAhead: function(typeAheadId) {
                $(typeAheadId).typeahead({
                    hint: true,
                    highlight: true,
                    minLength: 2
                },
                {
                    limit: Number.MAX_VALUE,
                    name: "typeaheadds",
                    source: function(query, sync, async) {
                        Site.ApplicationInterview.CallTypeAheadService(query, async);
                    },
                    display: function(data) {
                        return data.Text;
                    },
                    templates: {
                        suggestion: function(data) {
                            return "<div>" + data.Text + "</div>";
                        },
                        pending: '<div class="p-2 text-steel border bg-white">Loading... <span class="spinner-border spinner-border-sm ml-2" role="status" aria-hidden="true"></span></div>',
                        notFound: '<div class="p-2 text-steel h5 border bg-white">No Results Found</div>'
                    }
                }).bind('typeahead:select', function (obj, suggestion) {
                    _log("EVT captured: [typeahead:select]");
                    Site.ApplicationInterview.TypeAheadResult(obj, suggestion);
                    $(typeAheadId).typeahead('val', '');
                }).bind('typeahead:autocomplete', function (obj, suggestion) {
                    _log("EVT captured: [typeahead:autocomplete]");
                    Site.ApplicationInterview.TypeAheadResult(obj, suggestion);
                    $(typeAheadId).typeahead('val', '');
                }).bind('typeahead:close', function () {
                    _log("EVT captured: [typeahead:close]");
                    $(typeAheadId).typeahead('val', '');
                });
            },

            RemoveTypeAheadItem: function (key) {
                _log("Removing type ahead item with key: " + key);
                $("li[data-val-typeahead-key='" + key + "']").remove();
            },

            TypeAheadResult: function(evt, data) {
                const _txt = data.Text.replace("'", "\\'");
                $('#typeAheadSelectionList').parent().removeClass('d-none').show();
                $('#typeAheadSelectionList').append(
                    "<li class=\"list-inline-item bg-rock alert alert-secondary alert-dismissible vivify popInLeft duration-1500 fade show px-4 py-2 m-0 mb-2 border-0 mr-2\" role=\"alert\" data-val-typeahead-key=\"" + data.Value + "\"><span class=\"typeahead-text text-white fs-mask pr-4\">" + data.Text + "</span><button type=\"button\" class=\"close\" style=\"top: -2px;\" aria-label=\"Close\" data-dismiss=\"list-inline-item\" onclick=\"Site.ApplicationInterview.RemoveTypeAheadItem('" + data.Value + "')\"><span class=\"text-white\" aria-hidden=\"true\">&times;</span></button></li>");
            },

            CallTypeAheadService: function (query, async) {
                const questionId = $('#QuestionID').val();
                $.getJSON(
                    "/aarp_api/typeahead/search",
                    { q: query, qid: questionId },
                    function (data) {
                        _log("API Response Time: " + data.ResponseTime);
                        typeaheadds = [];
                        $.each(data.Options, function (idx, obj) {
                            typeaheadds.push(obj);
                        });
                        return async(typeaheadds);
                    }
                );
            },
            ShowSuccessModal:function() {
                if ($('#interviewQuestionModal').length) {
                    $('#interviewQuestionModal').show();
                    setTimeout(function () {
                        $('#interviewQuestionModal').hide();
                    }, 3000);
                }
            },
            BookmarkSite: function (element, bTitle) {
                var $url = $(('#' + element)).attr('href');

                if (window.sidebar) { // For Mozilla Firefox
                    $("a#bm").attr("href", $url);
                    $("a#bm").attr("title", bTitle);
                    $("a#bm").attr("rel", "sidebar");
                } else if (window.navigator.userAgent.indexOf("MSIE") > 0) {  // For IE
                    window.external.AddFavorite(bLink, bTitle);
                } else {
                    alert("Press CTRL + D or Command + D to bookmark!");
                }
                return false;
            }
        };

        function _log(s) {
            if (_debug && /chrom(e|ium)/.test(navigator.userAgent.toLowerCase()))
                console.log(s);
        }
        function rebindvalidators() {
            var form = $('#interview-question-form');
            form.unbind();
            form.data("validator", null);
            $.validator.unobtrusive.parse(form);
            form.validate(form.data("unobtrusiveValidation").options);
            Site.ApplicationInterview.InitTappies(form);
            Site.ApplicationInterview.InitDropdownChange();
        }
        function onAjaxApplicationInterviewFormSubmit(formSelector) {
            _log(">> onAjaxApplicationInterviewFormSubmit [" + formSelector + "]");
            $(formSelector).submit(function (event) {
                event.preventDefault();
                if ($(this).valid()) {
                    Site.Form().ToggleButtonProcessing($(formSelector + " .btn[type='submit']"));
                    Site.Form().toggleSpinner();
                    var form = $(formSelector);
                    $("#scAction-interviewquestion").val("InterviewQuestion");
                    const resultContainer = form.attr("data-ajax-update");
                    if ($('input[name="SingleChoiceAnswer"]').length) {
                        $('input[name="Answer"]').val($('input[name="SingleChoiceAnswer"]:checked').val());
                    }

                    var valuesArray = $("input[id^='UnitAnswer']").map(function (i, opt) {
                        return $(opt).val();
                    }).get().join("|");
                    if (valuesArray.length > 0)
                        $('#Answer').val(valuesArray);

                    if ($('#QuestionType').val() === "SEARCH") {
                        let typeAheadAnswers = '';
                        $('#typeAheadSelectionList li').each(function(idx,elem) {
                            typeAheadAnswers += $(this).children('.typeahead-text').html() + "~" + $(elem).attr('data-val-typeahead-key') + "|";
                        });

                        _log("Created answer for SEARCH submission: " + typeAheadAnswers);
                        $('input[name="Answer"]').val(typeAheadAnswers);
                    }

                    var multiChoiceArray = $('.multiChoice:checkbox:checked').map(function () {
                        return this.id;
                    }).get().join("|");
                    if (multiChoiceArray.length >0)
                        $('#Answer').val(multiChoiceArray);

                    if ($('#TextAnswer').length > 0)
                        $('#Answer').val($('#TextAnswer').val());
                    if ($('#MonthSelection').length > 0 && $('#YearSelection').length > 0) {
                        var dateMonth = $('#MonthSelection').val() + "|" + $('#YearSelection').val();
                        $('#Answer').val(dateMonth);
                    }
                    if ($("input[name$='UnknownAnswer']:checked").length > 0) {
                        var actualValue = $("input[name$='UnknownAnswer']:checked").val();
                        if (actualValue != undefined && actualValue != false) {
                            var answer = 'REFLEXIVE_NOT_KNOWN' + '|' + $('#UnknownAnswer').val();
                            $('#Answer').val(answer);
                        }
                    }
                    
                    $.ajax({
                        type: "POST",
                        data: form.serialize(),
                        success: function (result) {
                            jQuery(resultContainer).replaceWith(result);
                            rebindvalidators();
                            Site.ApplicationInterview.ScrollToTopofPage();
                            Site.ApplicationInterview.ShowSuccessModal();
                            dataLayerPageLoad();
                        },
                        error: function (result) {
                            Site.Form().ToggleButtonProcessing(jQuery(formSelector + " .btn[type='submit']"));
                            Site.Form().toggleSpinner();
                            document.location.href = '/Apply/Interview/Invalid?Reason=Error';
                        }
                    });
                }
            });
        }

    })();
})(jQuery);

function ShakeTextboxReflexive() {
    $('#type-ahead-add').click(function (e) {
        e.preventDefault();
        $('#TypeAheadSearch').focus();
        $('#type-ahead-search').addClass('pulsate').on(
            'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend',
            function () {
                $('#type-ahead-search').removeClass('pulsate');
            });
    });
}
;
