/* Minification failed. Returning unminified contents.
(3477,5-8): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: val
(3448,5-8): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: val
(3390,5-8): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: val
 */
/**
 * jquery.mask.js
 * @version: v1.14.10
 * @author: Igor Escobar
 *
 * Created by Igor Escobar on 2012-03-10. Please report any bug at http://blog.igorescobar.com
 *
 * Copyright (c) 2012 Igor Escobar http://blog.igorescobar.com
 *
 * The MIT License (http://www.opensource.org/licenses/mit-license.php)
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

/* jshint laxbreak: true */
/* jshint maxcomplexity:17 */
/* global define */

'use strict';

// UMD (Universal Module Definition) patterns for JavaScript modules that work everywhere.
// https://github.com/umdjs/umd/blob/master/jqueryPluginCommonjs.js
(function (factory, jQuery, Zepto) {

    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory(require('jquery'));
    } else {
        factory(jQuery || Zepto);
    }

}(function ($) {

    var Mask = function (el, mask, options) {

        var p = {
            invalid: [],
            getCaret: function () {
                try {
                    var sel,
                        pos = 0,
                        ctrl = el.get(0),
                        dSel = document.selection,
                        cSelStart = ctrl.selectionStart;

                    // IE Support
                    if (dSel && navigator.appVersion.indexOf('MSIE 10') === -1) {
                        sel = dSel.createRange();
                        sel.moveStart('character', -p.val().length);
                        pos = sel.text.length;
                    }
                    // Firefox support
                    else if (cSelStart || cSelStart === '0') {
                        pos = cSelStart;
                    }

                    return pos;
                } catch (e) {}
            },
            setCaret: function(pos) {
                try {
                    if (el.is(':focus')) {
                        var range, ctrl = el.get(0);

                        // Firefox, WebKit, etc..
                        if (ctrl.setSelectionRange) {
                            ctrl.setSelectionRange(pos, pos);
                        } else { // IE
                            range = ctrl.createTextRange();
                            range.collapse(true);
                            range.moveEnd('character', pos);
                            range.moveStart('character', pos);
                            range.select();
                        }
                    }
                } catch (e) {}
            },
            events: function() {
                el
                .on('keydown.mask', function(e) {
                    el.data('mask-keycode', e.keyCode || e.which);
                    el.data('mask-previus-value', el.val());
                })
                .on($.jMaskGlobals.useInput ? 'input.mask' : 'keyup.mask', p.behaviour)
                .on('paste.mask drop.mask', function() {
                    setTimeout(function() {
                        el.keydown().keyup();
                    }, 100);
                })
                .on('change.mask', function(){
                    el.data('changed', true);
                })
                .on('blur.mask', function(){
                    if (oldValue !== p.val() && !el.data('changed')) {
                        el.trigger('change');
                    }
                    el.data('changed', false);
                })
                // it's very important that this callback remains in this position
                // otherwhise oldValue it's going to work buggy
                .on('blur.mask', function() {
                    oldValue = p.val();
                })
                // select all text on focus
                .on('focus.mask', function (e) {
                    if (options.selectOnFocus === true) {
                        $(e.target).select();
                    }
                })
                // clear the value if it not complete the mask
                .on('focusout.mask', function() {
                    if (options.clearIfNotMatch && !regexMask.test(p.val())) {
                       p.val('');
                   }
                });
            },
            getRegexMask: function() {
                var maskChunks = [], translation, pattern, optional, recursive, oRecursive, r;

                for (var i = 0; i < mask.length; i++) {
                    translation = jMask.translation[mask.charAt(i)];

                    if (translation) {

                        pattern = translation.pattern.toString().replace(/.{1}$|^.{1}/g, '');
                        optional = translation.optional;
                        recursive = translation.recursive;

                        if (recursive) {
                            maskChunks.push(mask.charAt(i));
                            oRecursive = {digit: mask.charAt(i), pattern: pattern};
                        } else {
                            maskChunks.push(!optional && !recursive ? pattern : (pattern + '?'));
                        }

                    } else {
                        maskChunks.push(mask.charAt(i).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));
                    }
                }

                r = maskChunks.join('');

                if (oRecursive) {
                    r = r.replace(new RegExp('(' + oRecursive.digit + '(.*' + oRecursive.digit + ')?)'), '($1)?')
                         .replace(new RegExp(oRecursive.digit, 'g'), oRecursive.pattern);
                }

                return new RegExp(r);
            },
            destroyEvents: function() {
                el.off(['input', 'keydown', 'keyup', 'paste', 'drop', 'blur', 'focusout', ''].join('.mask '));
            },
            val: function(v) {
                var isInput = el.is('input'),
                    method = isInput ? 'val' : 'text',
                    r;

                if (arguments.length > 0) {
                    if (el[method]() !== v) {
                        el[method](v);
                    }
                    r = el;
                } else {
                    r = el[method]();
                }

                return r;
            },
            calculateCaretPosition: function(caretPos, newVal) {
                var newValL = newVal.length,
                    oValue  = el.data('mask-previus-value') || '',
                    oValueL = oValue.length;

                // edge cases when erasing digits
                if (el.data('mask-keycode') === 8 && oValue !== newVal) {
                    caretPos = caretPos - (newVal.slice(0, caretPos).length - oValue.slice(0, caretPos).length);

                // edge cases when typing new digits
                } else if (oValue !== newVal) {
                    // if the cursor is at the end keep it there
                    if (caretPos >= oValueL) {
                        caretPos = newValL;
                    } else {
                        caretPos = caretPos + (newVal.slice(0, caretPos).length - oValue.slice(0, caretPos).length);
                    }
                }

                return caretPos;
            },
            behaviour: function(e) {
                e = e || window.event;
                p.invalid = [];

                var keyCode = el.data('mask-keycode');

                if ($.inArray(keyCode, jMask.byPassKeys) === -1) {
                    var newVal   = p.getMasked(),
                        caretPos = p.getCaret();

                    setTimeout(function(caretPos, newVal) {
                      p.setCaret(p.calculateCaretPosition(caretPos, newVal));
                    }, 10, caretPos, newVal);

                    p.val(newVal);
                    p.setCaret(caretPos);
                    return p.callbacks(e);
                }
            },
            getMasked: function(skipMaskChars, val) {
                var buf = [],
                    value = val === undefined ? p.val() : val + '',
                    m = 0, maskLen = mask.length,
                    v = 0, valLen = value.length,
                    offset = 1, addMethod = 'push',
                    resetPos = -1,
                    lastMaskChar,
                    check;

                if (options.reverse) {
                    addMethod = 'unshift';
                    offset = -1;
                    lastMaskChar = 0;
                    m = maskLen - 1;
                    v = valLen - 1;
                    check = function () {
                        return m > -1 && v > -1;
                    };
                } else {
                    lastMaskChar = maskLen - 1;
                    check = function () {
                        return m < maskLen && v < valLen;
                    };
                }

                var lastUntranslatedMaskChar;
                while (check()) {
                    var maskDigit = mask.charAt(m),
                        valDigit = value.charAt(v),
                        translation = jMask.translation[maskDigit];

                    if (translation) {
                        if (valDigit.match(translation.pattern)) {
                            buf[addMethod](valDigit);
                             if (translation.recursive) {
                                if (resetPos === -1) {
                                    resetPos = m;
                                } else if (m === lastMaskChar) {
                                    m = resetPos - offset;
                                }

                                if (lastMaskChar === resetPos) {
                                    m -= offset;
                                }
                            }
                            m += offset;
                        } else if (valDigit === lastUntranslatedMaskChar) {
                            // matched the last untranslated (raw) mask character that we encountered
                            // likely an insert offset the mask character from the last entry; fall
                            // through and only increment v
                            lastUntranslatedMaskChar = undefined;
                        } else if (translation.optional) {
                            m += offset;
                            v -= offset;
                        } else if (translation.fallback) {
                            buf[addMethod](translation.fallback);
                            m += offset;
                            v -= offset;
                        } else {
                          p.invalid.push({p: v, v: valDigit, e: translation.pattern});
                        }
                        v += offset;
                    } else {
                        if (!skipMaskChars) {
                            buf[addMethod](maskDigit);
                        }

                        if (valDigit === maskDigit) {
                            v += offset;
                        } else {
                            lastUntranslatedMaskChar = maskDigit;
                        }

                        m += offset;
                    }
                }

                var lastMaskCharDigit = mask.charAt(lastMaskChar);
                if (maskLen === valLen + 1 && !jMask.translation[lastMaskCharDigit]) {
                    buf.push(lastMaskCharDigit);
                }

                return buf.join('');
            },
            callbacks: function (e) {
                var val = p.val(),
                    changed = val !== oldValue,
                    defaultArgs = [val, e, el, options],
                    callback = function(name, criteria, args) {
                        if (typeof options[name] === 'function' && criteria) {
                            options[name].apply(this, args);
                        }
                    };

                callback('onChange', changed === true, defaultArgs);
                callback('onKeyPress', changed === true, defaultArgs);
                callback('onComplete', val.length === mask.length, defaultArgs);
                callback('onInvalid', p.invalid.length > 0, [val, e, el, p.invalid, options]);
            }
        };

        el = $(el);
        var jMask = this, oldValue = p.val(), regexMask;

        mask = typeof mask === 'function' ? mask(p.val(), undefined, el,  options) : mask;

        // public methods
        jMask.mask = mask;
        jMask.options = options;
        jMask.remove = function() {
            var caret = p.getCaret();
            p.destroyEvents();
            p.val(jMask.getCleanVal());
            p.setCaret(caret);
            return el;
        };

        // get value without mask
        jMask.getCleanVal = function() {
           return p.getMasked(true);
        };

        // get masked value without the value being in the input or element
        jMask.getMaskedVal = function(val) {
           return p.getMasked(false, val);
        };

       jMask.init = function(onlyMask) {
            onlyMask = onlyMask || false;
            options = options || {};

            jMask.clearIfNotMatch  = $.jMaskGlobals.clearIfNotMatch;
            jMask.byPassKeys       = $.jMaskGlobals.byPassKeys;
            jMask.translation      = $.extend({}, $.jMaskGlobals.translation, options.translation);

            jMask = $.extend(true, {}, jMask, options);

            regexMask = p.getRegexMask();

            if (onlyMask) {
                p.events();
                p.val(p.getMasked());
            } else {
                if (options.placeholder) {
                    el.attr('placeholder' , options.placeholder);
                }

                // this is necessary, otherwise if the user submit the form
                // and then press the "back" button, the autocomplete will erase
                // the data. Works fine on IE9+, FF, Opera, Safari.
                if (el.data('mask')) {
                  el.attr('autocomplete', 'off');
                }

                // detect if is necessary let the user type freely.
                // for is a lot faster than forEach.
                for (var i = 0, maxlength = true; i < mask.length; i++) {
                    var translation = jMask.translation[mask.charAt(i)];
                    if (translation && translation.recursive) {
                        maxlength = false;
                        break;
                    }
                }

                //DW: Removing this, messing up some stuff
                //if (maxlength) {
                //    el.attr('maxlength', mask.length);
                //}

                p.destroyEvents();
                p.events();

                var caret = p.getCaret();
                p.val(p.getMasked());
                p.setCaret(caret);
            }
        };

        jMask.init(!el.is('input'));
    };

    $.maskWatchers = {};
    var HTMLAttributes = function () {
        var input = $(this),
            options = {},
            prefix = 'data-mask-',
            mask = input.attr('data-mask');

        if (input.attr(prefix + 'reverse')) {
            options.reverse = true;
        }

        if (input.attr(prefix + 'clearifnotmatch')) {
            options.clearIfNotMatch = true;
        }

        if (input.attr(prefix + 'selectonfocus') === 'true') {
           options.selectOnFocus = true;
        }

        if (notSameMaskObject(input, mask, options)) {
            return input.data('mask', new Mask(this, mask, options));
        }
    },
    notSameMaskObject = function(field, mask, options) {
        options = options || {};
        var maskObject = $(field).data('mask'),
            stringify = JSON.stringify,
            value = $(field).val() || $(field).text();
        try {
            if (typeof mask === 'function') {
                mask = mask(value);
            }
            return typeof maskObject !== 'object' || stringify(maskObject.options) !== stringify(options) || maskObject.mask !== mask;
        } catch (e) {}
    },
    eventSupported = function(eventName) {
        var el = document.createElement('div'), isSupported;

        eventName = 'on' + eventName;
        isSupported = (eventName in el);

        if ( !isSupported ) {
            el.setAttribute(eventName, 'return;');
            isSupported = typeof el[eventName] === 'function';
        }
        el = null;

        return isSupported;
    };

    $.fn.mask = function(mask, options) {
        options = options || {};
        var selector = this.selector,
            globals = $.jMaskGlobals,
            interval = globals.watchInterval,
            watchInputs = options.watchInputs || globals.watchInputs,
            maskFunction = function() {
                if (notSameMaskObject(this, mask, options)) {
                    return $(this).data('mask', new Mask(this, mask, options));
                }
            };

        $(this).each(maskFunction);

        if (selector && selector !== '' && watchInputs) {
            clearInterval($.maskWatchers[selector]);
            $.maskWatchers[selector] = setInterval(function(){
                $(document).find(selector).each(maskFunction);
            }, interval);
        }
        return this;
    };

    $.fn.masked = function(val) {
        return this.data('mask').getMaskedVal(val);
    };

    $.fn.unmask = function() {
        clearInterval($.maskWatchers[this.selector]);
        delete $.maskWatchers[this.selector];
        return this.each(function() {
            var dataMask = $(this).data('mask');
            if (dataMask) {
                dataMask.remove().removeData('mask');
            }
        });
    };

    $.fn.cleanVal = function() {
        return this.data('mask').getCleanVal();
    };

    $.applyDataMask = function(selector) {
        selector = selector || $.jMaskGlobals.maskElements;
        var $selector = (selector instanceof $) ? selector : $(selector);
        $selector.filter($.jMaskGlobals.dataMaskAttr).each(HTMLAttributes);
    };

    var globals = {
        maskElements: 'input,td,span,div',
        dataMaskAttr: '*[data-mask]',
        dataMask: true,
        watchInterval: 300,
        watchInputs: true,
        // old versions of chrome dont work great with input event
        useInput: !/Chrome\/[2-4][0-9]|SamsungBrowser/.test(window.navigator.userAgent) && eventSupported('input'),
        watchDataMask: false,
        byPassKeys: [9, 16, 17, 18, 36, 37, 38, 39, 40, 91],
        translation: {
            '0': {pattern: /\d/},
            '9': {pattern: /\d/, optional: true},
            '#': {pattern: /\d/, recursive: true},
            'A': {pattern: /[a-zA-Z0-9]/},
            'S': {pattern: /[a-zA-Z]/}
        }
    };

    $.jMaskGlobals = $.jMaskGlobals || {};
    globals = $.jMaskGlobals = $.extend(true, {}, globals, $.jMaskGlobals);

    // looking for inputs with data-mask attribute
    if (globals.dataMask) {
        $.applyDataMask();
    }

    setInterval(function() {
        if ($.jMaskGlobals.watchDataMask) {
            $.applyDataMask();
        }
    }, globals.watchInterval);
}, window.jQuery, window.Zepto));

;
/*!
 * Bootstrap v3.4.1 (https://getbootstrap.com/)
 * Copyright 2011-2019 Twitter, Inc.
 * Licensed under the MIT license
 */
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");!function(t){"use strict";var e=jQuery.fn.jquery.split(" ")[0].split(".");if(e[0]<2&&e[1]<9||1==e[0]&&9==e[1]&&e[2]<1||3<e[0])throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4")}(),function(n){"use strict";n.fn.emulateTransitionEnd=function(t){var e=!1,i=this;n(this).one("bsTransitionEnd",function(){e=!0});return setTimeout(function(){e||n(i).trigger(n.support.transition.end)},t),this},n(function(){n.support.transition=function o(){var t=document.createElement("bootstrap"),e={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var i in e)if(t.style[i]!==undefined)return{end:e[i]};return!1}(),n.support.transition&&(n.event.special.bsTransitionEnd={bindType:n.support.transition.end,delegateType:n.support.transition.end,handle:function(t){if(n(t.target).is(this))return t.handleObj.handler.apply(this,arguments)}})})}(jQuery),function(s){"use strict";var e='[data-dismiss="alert"]',a=function(t){s(t).on("click",e,this.close)};a.VERSION="3.4.1",a.TRANSITION_DURATION=150,a.prototype.close=function(t){var e=s(this),i=e.attr("data-target");i||(i=(i=e.attr("href"))&&i.replace(/.*(?=#[^\s]*$)/,"")),i="#"===i?[]:i;var o=s(document).find(i);function n(){o.detach().trigger("closed.bs.alert").remove()}t&&t.preventDefault(),o.length||(o=e.closest(".alert")),o.trigger(t=s.Event("close.bs.alert")),t.isDefaultPrevented()||(o.removeClass("in"),s.support.transition&&o.hasClass("fade")?o.one("bsTransitionEnd",n).emulateTransitionEnd(a.TRANSITION_DURATION):n())};var t=s.fn.alert;s.fn.alert=function o(i){return this.each(function(){var t=s(this),e=t.data("bs.alert");e||t.data("bs.alert",e=new a(this)),"string"==typeof i&&e[i].call(t)})},s.fn.alert.Constructor=a,s.fn.alert.noConflict=function(){return s.fn.alert=t,this},s(document).on("click.bs.alert.data-api",e,a.prototype.close)}(jQuery),function(s){"use strict";var n=function(t,e){this.$element=s(t),this.options=s.extend({},n.DEFAULTS,e),this.isLoading=!1};function i(o){return this.each(function(){var t=s(this),e=t.data("bs.button"),i="object"==typeof o&&o;e||t.data("bs.button",e=new n(this,i)),"toggle"==o?e.toggle():o&&e.setState(o)})}n.VERSION="3.4.1",n.DEFAULTS={loadingText:"loading..."},n.prototype.setState=function(t){var e="disabled",i=this.$element,o=i.is("input")?"val":"html",n=i.data();t+="Text",null==n.resetText&&i.data("resetText",i[o]()),setTimeout(s.proxy(function(){i[o](null==n[t]?this.options[t]:n[t]),"loadingText"==t?(this.isLoading=!0,i.addClass(e).attr(e,e).prop(e,!0)):this.isLoading&&(this.isLoading=!1,i.removeClass(e).removeAttr(e).prop(e,!1))},this),0)},n.prototype.toggle=function(){var t=!0,e=this.$element.closest('[data-toggle="buttons"]');if(e.length){var i=this.$element.find("input");"radio"==i.prop("type")?(i.prop("checked")&&(t=!1),e.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==i.prop("type")&&(i.prop("checked")!==this.$element.hasClass("active")&&(t=!1),this.$element.toggleClass("active")),i.prop("checked",this.$element.hasClass("active")),t&&i.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var t=s.fn.button;s.fn.button=i,s.fn.button.Constructor=n,s.fn.button.noConflict=function(){return s.fn.button=t,this},s(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(t){var e=s(t.target).closest(".btn");i.call(e,"toggle"),s(t.target).is('input[type="radio"], input[type="checkbox"]')||(t.preventDefault(),e.is("input,button")?e.trigger("focus"):e.find("input:visible,button:visible").first().trigger("focus"))}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(t){s(t.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(t.type))})}(jQuery),function(p){"use strict";var c=function(t,e){this.$element=p(t),this.$indicators=this.$element.find(".carousel-indicators"),this.options=e,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",p.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",p.proxy(this.pause,this)).on("mouseleave.bs.carousel",p.proxy(this.cycle,this))};function r(n){return this.each(function(){var t=p(this),e=t.data("bs.carousel"),i=p.extend({},c.DEFAULTS,t.data(),"object"==typeof n&&n),o="string"==typeof n?n:i.slide;e||t.data("bs.carousel",e=new c(this,i)),"number"==typeof n?e.to(n):o?e[o]():i.interval&&e.pause().cycle()})}c.VERSION="3.4.1",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(t){if(!/input|textarea/i.test(t.target.tagName)){switch(t.which){case 37:this.prev();break;case 39:this.next();break;default:return}t.preventDefault()}},c.prototype.cycle=function(t){return t||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(p.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(t){return this.$items=t.parent().children(".item"),this.$items.index(t||this.$active)},c.prototype.getItemForDirection=function(t,e){var i=this.getItemIndex(e);if(("prev"==t&&0===i||"next"==t&&i==this.$items.length-1)&&!this.options.wrap)return e;var o=(i+("prev"==t?-1:1))%this.$items.length;return this.$items.eq(o)},c.prototype.to=function(t){var e=this,i=this.getItemIndex(this.$active=this.$element.find(".item.active"));if(!(t>this.$items.length-1||t<0))return this.sliding?this.$element.one("slid.bs.carousel",function(){e.to(t)}):i==t?this.pause().cycle():this.slide(i<t?"next":"prev",this.$items.eq(t))},c.prototype.pause=function(t){return t||(this.paused=!0),this.$element.find(".next, .prev").length&&p.support.transition&&(this.$element.trigger(p.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){if(!this.sliding)return this.slide("next")},c.prototype.prev=function(){if(!this.sliding)return this.slide("prev")},c.prototype.slide=function(t,e){var i=this.$element.find(".item.active"),o=e||this.getItemForDirection(t,i),n=this.interval,s="next"==t?"left":"right",a=this;if(o.hasClass("active"))return this.sliding=!1;var r=o[0],l=p.Event("slide.bs.carousel",{relatedTarget:r,direction:s});if(this.$element.trigger(l),!l.isDefaultPrevented()){if(this.sliding=!0,n&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var h=p(this.$indicators.children()[this.getItemIndex(o)]);h&&h.addClass("active")}var d=p.Event("slid.bs.carousel",{relatedTarget:r,direction:s});return p.support.transition&&this.$element.hasClass("slide")?(o.addClass(t),"object"==typeof o&&o.length&&o[0].offsetWidth,i.addClass(s),o.addClass(s),i.one("bsTransitionEnd",function(){o.removeClass([t,s].join(" ")).addClass("active"),i.removeClass(["active",s].join(" ")),a.sliding=!1,setTimeout(function(){a.$element.trigger(d)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(i.removeClass("active"),o.addClass("active"),this.sliding=!1,this.$element.trigger(d)),n&&this.cycle(),this}};var t=p.fn.carousel;p.fn.carousel=r,p.fn.carousel.Constructor=c,p.fn.carousel.noConflict=function(){return p.fn.carousel=t,this};var e=function(t){var e=p(this),i=e.attr("href");i&&(i=i.replace(/.*(?=#[^\s]+$)/,""));var o=e.attr("data-target")||i,n=p(document).find(o);if(n.hasClass("carousel")){var s=p.extend({},n.data(),e.data()),a=e.attr("data-slide-to");a&&(s.interval=!1),r.call(n,s),a&&n.data("bs.carousel").to(a),t.preventDefault()}};p(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),p(window).on("load",function(){p('[data-ride="carousel"]').each(function(){var t=p(this);r.call(t,t.data())})})}(jQuery),function(a){"use strict";var r=function(t,e){this.$element=a(t),this.options=a.extend({},r.DEFAULTS,e),this.$trigger=a('[data-toggle="collapse"][href="#'+t.id+'"],[data-toggle="collapse"][data-target="#'+t.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};function n(t){var e,i=t.attr("data-target")||(e=t.attr("href"))&&e.replace(/.*(?=#[^\s]+$)/,"");return a(document).find(i)}function l(o){return this.each(function(){var t=a(this),e=t.data("bs.collapse"),i=a.extend({},r.DEFAULTS,t.data(),"object"==typeof o&&o);!e&&i.toggle&&/show|hide/.test(o)&&(i.toggle=!1),e||t.data("bs.collapse",e=new r(this,i)),"string"==typeof o&&e[o]()})}r.VERSION="3.4.1",r.TRANSITION_DURATION=350,r.DEFAULTS={toggle:!0},r.prototype.dimension=function(){return this.$element.hasClass("width")?"width":"height"},r.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var t,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(t=e.data("bs.collapse"))&&t.transitioning)){var i=a.Event("show.bs.collapse");if(this.$element.trigger(i),!i.isDefaultPrevented()){e&&e.length&&(l.call(e,"hide"),t||e.data("bs.collapse",null));var o=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[o](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var n=function(){this.$element.removeClass("collapsing").addClass("collapse in")[o](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return n.call(this);var s=a.camelCase(["scroll",o].join("-"));this.$element.one("bsTransitionEnd",a.proxy(n,this)).emulateTransitionEnd(r.TRANSITION_DURATION)[o](this.$element[0][s])}}}},r.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var t=a.Event("hide.bs.collapse");if(this.$element.trigger(t),!t.isDefaultPrevented()){var e=this.dimension();this.$element[e](this.$element[e]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var i=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};if(!a.support.transition)return i.call(this);this.$element[e](0).one("bsTransitionEnd",a.proxy(i,this)).emulateTransitionEnd(r.TRANSITION_DURATION)}}},r.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},r.prototype.getParent=function(){return a(document).find(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(t,e){var i=a(e);this.addAriaAndCollapsedClass(n(i),i)},this)).end()},r.prototype.addAriaAndCollapsedClass=function(t,e){var i=t.hasClass("in");t.attr("aria-expanded",i),e.toggleClass("collapsed",!i).attr("aria-expanded",i)};var t=a.fn.collapse;a.fn.collapse=l,a.fn.collapse.Constructor=r,a.fn.collapse.noConflict=function(){return a.fn.collapse=t,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(t){var e=a(this);e.attr("data-target")||t.preventDefault();var i=n(e),o=i.data("bs.collapse")?"toggle":e.data();l.call(i,o)})}(jQuery),function(a){"use strict";var r='[data-toggle="dropdown"]',o=function(t){a(t).on("click.bs.dropdown",this.toggle)};function l(t){var e=t.attr("data-target");e||(e=(e=t.attr("href"))&&/#[A-Za-z]/.test(e)&&e.replace(/.*(?=#[^\s]*$)/,""));var i="#"!==e?a(document).find(e):null;return i&&i.length?i:t.parent()}function s(o){o&&3===o.which||(a(".dropdown-backdrop").remove(),a(r).each(function(){var t=a(this),e=l(t),i={relatedTarget:this};e.hasClass("open")&&(o&&"click"==o.type&&/input|textarea/i.test(o.target.tagName)&&a.contains(e[0],o.target)||(e.trigger(o=a.Event("hide.bs.dropdown",i)),o.isDefaultPrevented()||(t.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",i)))))}))}o.VERSION="3.4.1",o.prototype.toggle=function(t){var e=a(this);if(!e.is(".disabled, :disabled")){var i=l(e),o=i.hasClass("open");if(s(),!o){"ontouchstart"in document.documentElement&&!i.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",s);var n={relatedTarget:this};if(i.trigger(t=a.Event("show.bs.dropdown",n)),t.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),i.toggleClass("open").trigger(a.Event("shown.bs.dropdown",n))}return!1}},o.prototype.keydown=function(t){if(/(38|40|27|32)/.test(t.which)&&!/input|textarea/i.test(t.target.tagName)){var e=a(this);if(t.preventDefault(),t.stopPropagation(),!e.is(".disabled, :disabled")){var i=l(e),o=i.hasClass("open");if(!o&&27!=t.which||o&&27==t.which)return 27==t.which&&i.find(r).trigger("focus"),e.trigger("click");var n=i.find(".dropdown-menu li:not(.disabled):visible a");if(n.length){var s=n.index(t.target);38==t.which&&0<s&&s--,40==t.which&&s<n.length-1&&s++,~s||(s=0),n.eq(s).trigger("focus")}}}};var t=a.fn.dropdown;a.fn.dropdown=function e(i){return this.each(function(){var t=a(this),e=t.data("bs.dropdown");e||t.data("bs.dropdown",e=new o(this)),"string"==typeof i&&e[i].call(t)})},a.fn.dropdown.Constructor=o,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=t,this},a(document).on("click.bs.dropdown.data-api",s).on("click.bs.dropdown.data-api",".dropdown form",function(t){t.stopPropagation()}).on("click.bs.dropdown.data-api",r,o.prototype.toggle).on("keydown.bs.dropdown.data-api",r,o.prototype.keydown).on("keydown.bs.dropdown.data-api",".dropdown-menu",o.prototype.keydown)}(jQuery),function(a){"use strict";var s=function(t,e){this.options=e,this.$body=a(document.body),this.$element=a(t),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.fixedContent=".navbar-fixed-top, .navbar-fixed-bottom",this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};function r(o,n){return this.each(function(){var t=a(this),e=t.data("bs.modal"),i=a.extend({},s.DEFAULTS,t.data(),"object"==typeof o&&o);e||t.data("bs.modal",e=new s(this,i)),"string"==typeof o?e[o](n):i.show&&e.show(n)})}s.VERSION="3.4.1",s.TRANSITION_DURATION=300,s.BACKDROP_TRANSITION_DURATION=150,s.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},s.prototype.toggle=function(t){return this.isShown?this.hide():this.show(t)},s.prototype.show=function(i){var o=this,t=a.Event("show.bs.modal",{relatedTarget:i});this.$element.trigger(t),this.isShown||t.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.$dialog.on("mousedown.dismiss.bs.modal",function(){o.$element.one("mouseup.dismiss.bs.modal",function(t){a(t.target).is(o.$element)&&(o.ignoreBackdropClick=!0)})}),this.backdrop(function(){var t=a.support.transition&&o.$element.hasClass("fade");o.$element.parent().length||o.$element.appendTo(o.$body),o.$element.show().scrollTop(0),o.adjustDialog(),t&&o.$element[0].offsetWidth,o.$element.addClass("in"),o.enforceFocus();var e=a.Event("shown.bs.modal",{relatedTarget:i});t?o.$dialog.one("bsTransitionEnd",function(){o.$element.trigger("focus").trigger(e)}).emulateTransitionEnd(s.TRANSITION_DURATION):o.$element.trigger("focus").trigger(e)}))},s.prototype.hide=function(t){t&&t.preventDefault(),t=a.Event("hide.bs.modal"),this.$element.trigger(t),this.isShown&&!t.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"),this.$dialog.off("mousedown.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(s.TRANSITION_DURATION):this.hideModal())},s.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(t){document===t.target||this.$element[0]===t.target||this.$element.has(t.target).length||this.$element.trigger("focus")},this))},s.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(t){27==t.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},s.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},s.prototype.hideModal=function(){var t=this;this.$element.hide(),this.backdrop(function(){t.$body.removeClass("modal-open"),t.resetAdjustments(),t.resetScrollbar(),t.$element.trigger("hidden.bs.modal")})},s.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},s.prototype.backdrop=function(t){var e=this,i=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var o=a.support.transition&&i;if(this.$backdrop=a(document.createElement("div")).addClass("modal-backdrop "+i).appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(t){this.ignoreBackdropClick?this.ignoreBackdropClick=!1:t.target===t.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide())},this)),o&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!t)return;o?this.$backdrop.one("bsTransitionEnd",t).emulateTransitionEnd(s.BACKDROP_TRANSITION_DURATION):t()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var n=function(){e.removeBackdrop(),t&&t()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",n).emulateTransitionEnd(s.BACKDROP_TRANSITION_DURATION):n()}else t&&t()},s.prototype.handleUpdate=function(){this.adjustDialog()},s.prototype.adjustDialog=function(){var t=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&t?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!t?this.scrollbarWidth:""})},s.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},s.prototype.checkScrollbar=function(){var t=window.innerWidth;if(!t){var e=document.documentElement.getBoundingClientRect();t=e.right-Math.abs(e.left)}this.bodyIsOverflowing=document.body.clientWidth<t,this.scrollbarWidth=this.measureScrollbar()},s.prototype.setScrollbar=function(){var t=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"";var n=this.scrollbarWidth;this.bodyIsOverflowing&&(this.$body.css("padding-right",t+n),a(this.fixedContent).each(function(t,e){var i=e.style.paddingRight,o=a(e).css("padding-right");a(e).data("padding-right",i).css("padding-right",parseFloat(o)+n+"px")}))},s.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad),a(this.fixedContent).each(function(t,e){var i=a(e).data("padding-right");a(e).removeData("padding-right"),e.style.paddingRight=i||""})},s.prototype.measureScrollbar=function(){var t=document.createElement("div");t.className="modal-scrollbar-measure",this.$body.append(t);var e=t.offsetWidth-t.clientWidth;return this.$body[0].removeChild(t),e};var t=a.fn.modal;a.fn.modal=r,a.fn.modal.Constructor=s,a.fn.modal.noConflict=function(){return a.fn.modal=t,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(t){var e=a(this),i=e.attr("href"),o=e.attr("data-target")||i&&i.replace(/.*(?=#[^\s]+$)/,""),n=a(document).find(o),s=n.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(i)&&i},n.data(),e.data());e.is("a")&&t.preventDefault(),n.one("show.bs.modal",function(t){t.isDefaultPrevented()||n.one("hidden.bs.modal",function(){e.is(":visible")&&e.trigger("focus")})}),r.call(n,s,this)})}(jQuery),function(g){"use strict";var o=["sanitize","whiteList","sanitizeFn"],a=["background","cite","href","itemtype","longdesc","poster","src","xlink:href"],t={"*":["class","dir","id","lang","role",/^aria-[\w-]*$/i],a:["target","href","title","rel"],area:[],b:[],br:[],col:[],code:[],div:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:["src","alt","title","width","height"],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]},r=/^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi,l=/^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+/]+=*$/i;function u(t,e){var i=t.nodeName.toLowerCase();if(-1!==g.inArray(i,e))return-1===g.inArray(i,a)||Boolean(t.nodeValue.match(r)||t.nodeValue.match(l));for(var o=g(e).filter(function(t,e){return e instanceof RegExp}),n=0,s=o.length;n<s;n++)if(i.match(o[n]))return!0;return!1}function n(t,e,i){if(0===t.length)return t;if(i&&"function"==typeof i)return i(t);if(!document.implementation||!document.implementation.createHTMLDocument)return t;var o=document.implementation.createHTMLDocument("sanitization");o.body.innerHTML=t;for(var n=g.map(e,function(t,e){return e}),s=g(o.body).find("*"),a=0,r=s.length;a<r;a++){var l=s[a],h=l.nodeName.toLowerCase();if(-1!==g.inArray(h,n))for(var d=g.map(l.attributes,function(t){return t}),p=[].concat(e["*"]||[],e[h]||[]),c=0,f=d.length;c<f;c++)u(d[c],p)||l.removeAttribute(d[c].nodeName);else l.parentNode.removeChild(l)}return o.body.innerHTML}var m=function(t,e){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.inState=null,this.init("tooltip",t,e)};m.VERSION="3.4.1",m.TRANSITION_DURATION=150,m.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0},sanitize:!0,sanitizeFn:null,whiteList:t},m.prototype.init=function(t,e,i){if(this.enabled=!0,this.type=t,this.$element=g(e),this.options=this.getOptions(i),this.$viewport=this.options.viewport&&g(document).find(g.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var o=this.options.trigger.split(" "),n=o.length;n--;){var s=o[n];if("click"==s)this.$element.on("click."+this.type,this.options.selector,g.proxy(this.toggle,this));else if("manual"!=s){var a="hover"==s?"mouseenter":"focusin",r="hover"==s?"mouseleave":"focusout";this.$element.on(a+"."+this.type,this.options.selector,g.proxy(this.enter,this)),this.$element.on(r+"."+this.type,this.options.selector,g.proxy(this.leave,this))}}this.options.selector?this._options=g.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},m.prototype.getDefaults=function(){return m.DEFAULTS},m.prototype.getOptions=function(t){var e=this.$element.data();for(var i in e)e.hasOwnProperty(i)&&-1!==g.inArray(i,o)&&delete e[i];return(t=g.extend({},this.getDefaults(),e,t)).delay&&"number"==typeof t.delay&&(t.delay={show:t.delay,hide:t.delay}),t.sanitize&&(t.template=n(t.template,t.whiteList,t.sanitizeFn)),t},m.prototype.getDelegateOptions=function(){var i={},o=this.getDefaults();return this._options&&g.each(this._options,function(t,e){o[t]!=e&&(i[t]=e)}),i},m.prototype.enter=function(t){var e=t instanceof this.constructor?t:g(t.currentTarget).data("bs."+this.type);if(e||(e=new this.constructor(t.currentTarget,this.getDelegateOptions()),g(t.currentTarget).data("bs."+this.type,e)),t instanceof g.Event&&(e.inState["focusin"==t.type?"focus":"hover"]=!0),e.tip().hasClass("in")||"in"==e.hoverState)e.hoverState="in";else{if(clearTimeout(e.timeout),e.hoverState="in",!e.options.delay||!e.options.delay.show)return e.show();e.timeout=setTimeout(function(){"in"==e.hoverState&&e.show()},e.options.delay.show)}},m.prototype.isInStateTrue=function(){for(var t in this.inState)if(this.inState[t])return!0;return!1},m.prototype.leave=function(t){var e=t instanceof this.constructor?t:g(t.currentTarget).data("bs."+this.type);if(e||(e=new this.constructor(t.currentTarget,this.getDelegateOptions()),g(t.currentTarget).data("bs."+this.type,e)),t instanceof g.Event&&(e.inState["focusout"==t.type?"focus":"hover"]=!1),!e.isInStateTrue()){if(clearTimeout(e.timeout),e.hoverState="out",!e.options.delay||!e.options.delay.hide)return e.hide();e.timeout=setTimeout(function(){"out"==e.hoverState&&e.hide()},e.options.delay.hide)}},m.prototype.show=function(){var t=g.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(t);var e=g.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(t.isDefaultPrevented()||!e)return;var i=this,o=this.tip(),n=this.getUID(this.type);this.setContent(),o.attr("id",n),this.$element.attr("aria-describedby",n),this.options.animation&&o.addClass("fade");var s="function"==typeof this.options.placement?this.options.placement.call(this,o[0],this.$element[0]):this.options.placement,a=/\s?auto?\s?/i,r=a.test(s);r&&(s=s.replace(a,"")||"top"),o.detach().css({top:0,left:0,display:"block"}).addClass(s).data("bs."+this.type,this),this.options.container?o.appendTo(g(document).find(this.options.container)):o.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var l=this.getPosition(),h=o[0].offsetWidth,d=o[0].offsetHeight;if(r){var p=s,c=this.getPosition(this.$viewport);s="bottom"==s&&l.bottom+d>c.bottom?"top":"top"==s&&l.top-d<c.top?"bottom":"right"==s&&l.right+h>c.width?"left":"left"==s&&l.left-h<c.left?"right":s,o.removeClass(p).addClass(s)}var f=this.getCalculatedOffset(s,l,h,d);this.applyPlacement(f,s);var u=function(){var t=i.hoverState;i.$element.trigger("shown.bs."+i.type),i.hoverState=null,"out"==t&&i.leave(i)};g.support.transition&&this.$tip.hasClass("fade")?o.one("bsTransitionEnd",u).emulateTransitionEnd(m.TRANSITION_DURATION):u()}},m.prototype.applyPlacement=function(t,e){var i=this.tip(),o=i[0].offsetWidth,n=i[0].offsetHeight,s=parseInt(i.css("margin-top"),10),a=parseInt(i.css("margin-left"),10);isNaN(s)&&(s=0),isNaN(a)&&(a=0),t.top+=s,t.left+=a,g.offset.setOffset(i[0],g.extend({using:function(t){i.css({top:Math.round(t.top),left:Math.round(t.left)})}},t),0),i.addClass("in");var r=i[0].offsetWidth,l=i[0].offsetHeight;"top"==e&&l!=n&&(t.top=t.top+n-l);var h=this.getViewportAdjustedDelta(e,t,r,l);h.left?t.left+=h.left:t.top+=h.top;var d=/top|bottom/.test(e),p=d?2*h.left-o+r:2*h.top-n+l,c=d?"offsetWidth":"offsetHeight";i.offset(t),this.replaceArrow(p,i[0][c],d)},m.prototype.replaceArrow=function(t,e,i){this.arrow().css(i?"left":"top",50*(1-t/e)+"%").css(i?"top":"left","")},m.prototype.setContent=function(){var t=this.tip(),e=this.getTitle();this.options.html?(this.options.sanitize&&(e=n(e,this.options.whiteList,this.options.sanitizeFn)),t.find(".tooltip-inner").html(e)):t.find(".tooltip-inner").text(e),t.removeClass("fade in top bottom left right")},m.prototype.hide=function(t){var e=this,i=g(this.$tip),o=g.Event("hide.bs."+this.type);function n(){"in"!=e.hoverState&&i.detach(),e.$element&&e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),t&&t()}if(this.$element.trigger(o),!o.isDefaultPrevented())return i.removeClass("in"),g.support.transition&&i.hasClass("fade")?i.one("bsTransitionEnd",n).emulateTransitionEnd(m.TRANSITION_DURATION):n(),this.hoverState=null,this},m.prototype.fixTitle=function(){var t=this.$element;(t.attr("title")||"string"!=typeof t.attr("data-original-title"))&&t.attr("data-original-title",t.attr("title")||"").attr("title","")},m.prototype.hasContent=function(){return this.getTitle()},m.prototype.getPosition=function(t){var e=(t=t||this.$element)[0],i="BODY"==e.tagName,o=e.getBoundingClientRect();null==o.width&&(o=g.extend({},o,{width:o.right-o.left,height:o.bottom-o.top}));var n=window.SVGElement&&e instanceof window.SVGElement,s=i?{top:0,left:0}:n?null:t.offset(),a={scroll:i?document.documentElement.scrollTop||document.body.scrollTop:t.scrollTop()},r=i?{width:g(window).width(),height:g(window).height()}:null;return g.extend({},o,a,r,s)},m.prototype.getCalculatedOffset=function(t,e,i,o){return"bottom"==t?{top:e.top+e.height,left:e.left+e.width/2-i/2}:"top"==t?{top:e.top-o,left:e.left+e.width/2-i/2}:"left"==t?{top:e.top+e.height/2-o/2,left:e.left-i}:{top:e.top+e.height/2-o/2,left:e.left+e.width}},m.prototype.getViewportAdjustedDelta=function(t,e,i,o){var n={top:0,left:0};if(!this.$viewport)return n;var s=this.options.viewport&&this.options.viewport.padding||0,a=this.getPosition(this.$viewport);if(/right|left/.test(t)){var r=e.top-s-a.scroll,l=e.top+s-a.scroll+o;r<a.top?n.top=a.top-r:l>a.top+a.height&&(n.top=a.top+a.height-l)}else{var h=e.left-s,d=e.left+s+i;h<a.left?n.left=a.left-h:d>a.right&&(n.left=a.left+a.width-d)}return n},m.prototype.getTitle=function(){var t=this.$element,e=this.options;return t.attr("data-original-title")||("function"==typeof e.title?e.title.call(t[0]):e.title)},m.prototype.getUID=function(t){for(;t+=~~(1e6*Math.random()),document.getElementById(t););return t},m.prototype.tip=function(){if(!this.$tip&&(this.$tip=g(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},m.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},m.prototype.enable=function(){this.enabled=!0},m.prototype.disable=function(){this.enabled=!1},m.prototype.toggleEnabled=function(){this.enabled=!this.enabled},m.prototype.toggle=function(t){var e=this;t&&((e=g(t.currentTarget).data("bs."+this.type))||(e=new this.constructor(t.currentTarget,this.getDelegateOptions()),g(t.currentTarget).data("bs."+this.type,e))),t?(e.inState.click=!e.inState.click,e.isInStateTrue()?e.enter(e):e.leave(e)):e.tip().hasClass("in")?e.leave(e):e.enter(e)},m.prototype.destroy=function(){var t=this;clearTimeout(this.timeout),this.hide(function(){t.$element.off("."+t.type).removeData("bs."+t.type),t.$tip&&t.$tip.detach(),t.$tip=null,t.$arrow=null,t.$viewport=null,t.$element=null})},m.prototype.sanitizeHtml=function(t){return n(t,this.options.whiteList,this.options.sanitizeFn)};var e=g.fn.tooltip;g.fn.tooltip=function i(o){return this.each(function(){var t=g(this),e=t.data("bs.tooltip"),i="object"==typeof o&&o;!e&&/destroy|hide/.test(o)||(e||t.data("bs.tooltip",e=new m(this,i)),"string"==typeof o&&e[o]())})},g.fn.tooltip.Constructor=m,g.fn.tooltip.noConflict=function(){return g.fn.tooltip=e,this}}(jQuery),function(n){"use strict";var s=function(t,e){this.init("popover",t,e)};if(!n.fn.tooltip)throw new Error("Popover requires tooltip.js");s.VERSION="3.4.1",s.DEFAULTS=n.extend({},n.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),((s.prototype=n.extend({},n.fn.tooltip.Constructor.prototype)).constructor=s).prototype.getDefaults=function(){return s.DEFAULTS},s.prototype.setContent=function(){var t=this.tip(),e=this.getTitle(),i=this.getContent();if(this.options.html){var o=typeof i;this.options.sanitize&&(e=this.sanitizeHtml(e),"string"===o&&(i=this.sanitizeHtml(i))),t.find(".popover-title").html(e),t.find(".popover-content").children().detach().end()["string"===o?"html":"append"](i)}else t.find(".popover-title").text(e),t.find(".popover-content").children().detach().end().text(i);t.removeClass("fade top bottom left right in"),t.find(".popover-title").html()||t.find(".popover-title").hide()},s.prototype.hasContent=function(){return this.getTitle()||this.getContent()},s.prototype.getContent=function(){var t=this.$element,e=this.options;return t.attr("data-content")||("function"==typeof e.content?e.content.call(t[0]):e.content)},s.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var t=n.fn.popover;n.fn.popover=function e(o){return this.each(function(){var t=n(this),e=t.data("bs.popover"),i="object"==typeof o&&o;!e&&/destroy|hide/.test(o)||(e||t.data("bs.popover",e=new s(this,i)),"string"==typeof o&&e[o]())})},n.fn.popover.Constructor=s,n.fn.popover.noConflict=function(){return n.fn.popover=t,this}}(jQuery),function(s){"use strict";function n(t,e){this.$body=s(document.body),this.$scrollElement=s(t).is(document.body)?s(window):s(t),this.options=s.extend({},n.DEFAULTS,e),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",s.proxy(this.process,this)),this.refresh(),this.process()}function e(o){return this.each(function(){var t=s(this),e=t.data("bs.scrollspy"),i="object"==typeof o&&o;e||t.data("bs.scrollspy",e=new n(this,i)),"string"==typeof o&&e[o]()})}n.VERSION="3.4.1",n.DEFAULTS={offset:10},n.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},n.prototype.refresh=function(){var t=this,o="offset",n=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),s.isWindow(this.$scrollElement[0])||(o="position",n=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var t=s(this),e=t.data("target")||t.attr("href"),i=/^#./.test(e)&&s(e);return i&&i.length&&i.is(":visible")&&[[i[o]().top+n,e]]||null}).sort(function(t,e){return t[0]-e[0]}).each(function(){t.offsets.push(this[0]),t.targets.push(this[1])})},n.prototype.process=function(){var t,e=this.$scrollElement.scrollTop()+this.options.offset,i=this.getScrollHeight(),o=this.options.offset+i-this.$scrollElement.height(),n=this.offsets,s=this.targets,a=this.activeTarget;if(this.scrollHeight!=i&&this.refresh(),o<=e)return a!=(t=s[s.length-1])&&this.activate(t);if(a&&e<n[0])return this.activeTarget=null,this.clear();for(t=n.length;t--;)a!=s[t]&&e>=n[t]&&(n[t+1]===undefined||e<n[t+1])&&this.activate(s[t])},n.prototype.activate=function(t){this.activeTarget=t,this.clear();var e=this.selector+'[data-target="'+t+'"],'+this.selector+'[href="'+t+'"]',i=s(e).parents("li").addClass("active");i.parent(".dropdown-menu").length&&(i=i.closest("li.dropdown").addClass("active")),i.trigger("activate.bs.scrollspy")},n.prototype.clear=function(){s(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var t=s.fn.scrollspy;s.fn.scrollspy=e,s.fn.scrollspy.Constructor=n,s.fn.scrollspy.noConflict=function(){return s.fn.scrollspy=t,this},s(window).on("load.bs.scrollspy.data-api",function(){s('[data-spy="scroll"]').each(function(){var t=s(this);e.call(t,t.data())})})}(jQuery),function(r){"use strict";var a=function(t){this.element=r(t)};function e(i){return this.each(function(){var t=r(this),e=t.data("bs.tab");e||t.data("bs.tab",e=new a(this)),"string"==typeof i&&e[i]()})}a.VERSION="3.4.1",a.TRANSITION_DURATION=150,a.prototype.show=function(){var t=this.element,e=t.closest("ul:not(.dropdown-menu)"),i=t.data("target");if(i||(i=(i=t.attr("href"))&&i.replace(/.*(?=#[^\s]*$)/,"")),!t.parent("li").hasClass("active")){var o=e.find(".active:last a"),n=r.Event("hide.bs.tab",{relatedTarget:t[0]}),s=r.Event("show.bs.tab",{relatedTarget:o[0]});if(o.trigger(n),t.trigger(s),!s.isDefaultPrevented()&&!n.isDefaultPrevented()){var a=r(document).find(i);this.activate(t.closest("li"),e),this.activate(a,a.parent(),function(){o.trigger({type:"hidden.bs.tab",relatedTarget:t[0]}),t.trigger({type:"shown.bs.tab",relatedTarget:o[0]})})}}},a.prototype.activate=function(t,e,i){var o=e.find("> .active"),n=i&&r.support.transition&&(o.length&&o.hasClass("fade")||!!e.find("> .fade").length);function s(){o.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),t.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),n?(t[0].offsetWidth,t.addClass("in")):t.removeClass("fade"),t.parent(".dropdown-menu").length&&t.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),i&&i()}o.length&&n?o.one("bsTransitionEnd",s).emulateTransitionEnd(a.TRANSITION_DURATION):s(),o.removeClass("in")};var t=r.fn.tab;r.fn.tab=e,r.fn.tab.Constructor=a,r.fn.tab.noConflict=function(){return r.fn.tab=t,this};var i=function(t){t.preventDefault(),e.call(r(this),"show")};r(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',i).on("click.bs.tab.data-api",'[data-toggle="pill"]',i)}(jQuery),function(l){"use strict";var h=function(t,e){this.options=l.extend({},h.DEFAULTS,e);var i=this.options.target===h.DEFAULTS.target?l(this.options.target):l(document).find(this.options.target);this.$target=i.on("scroll.bs.affix.data-api",l.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",l.proxy(this.checkPositionWithEventLoop,this)),this.$element=l(t),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};function i(o){return this.each(function(){var t=l(this),e=t.data("bs.affix"),i="object"==typeof o&&o;e||t.data("bs.affix",e=new h(this,i)),"string"==typeof o&&e[o]()})}h.VERSION="3.4.1",h.RESET="affix affix-top affix-bottom",h.DEFAULTS={offset:0,target:window},h.prototype.getState=function(t,e,i,o){var n=this.$target.scrollTop(),s=this.$element.offset(),a=this.$target.height();if(null!=i&&"top"==this.affixed)return n<i&&"top";if("bottom"==this.affixed)return null!=i?!(n+this.unpin<=s.top)&&"bottom":!(n+a<=t-o)&&"bottom";var r=null==this.affixed,l=r?n:s.top;return null!=i&&n<=i?"top":null!=o&&t-o<=l+(r?a:e)&&"bottom"},h.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(h.RESET).addClass("affix");var t=this.$target.scrollTop(),e=this.$element.offset();return this.pinnedOffset=e.top-t},h.prototype.checkPositionWithEventLoop=function(){setTimeout(l.proxy(this.checkPosition,this),1)},h.prototype.checkPosition=function(){if(this.$element.is(":visible")){var t=this.$element.height(),e=this.options.offset,i=e.top,o=e.bottom,n=Math.max(l(document).height(),l(document.body).height());"object"!=typeof e&&(o=i=e),"function"==typeof i&&(i=e.top(this.$element)),"function"==typeof o&&(o=e.bottom(this.$element));var s=this.getState(n,t,i,o);if(this.affixed!=s){null!=this.unpin&&this.$element.css("top","");var a="affix"+(s?"-"+s:""),r=l.Event(a+".bs.affix");if(this.$element.trigger(r),r.isDefaultPrevented())return;this.affixed=s,this.unpin="bottom"==s?this.getPinnedOffset():null,this.$element.removeClass(h.RESET).addClass(a).trigger(a.replace("affix","affixed")+".bs.affix")}"bottom"==s&&this.$element.offset({top:n-t-o})}};var t=l.fn.affix;l.fn.affix=i,l.fn.affix.Constructor=h,l.fn.affix.noConflict=function(){return l.fn.affix=t,this},l(window).on("load",function(){l('[data-spy="affix"]').each(function(){var t=l(this),e=t.data();e.offset=e.offset||{},null!=e.offsetBottom&&(e.offset.bottom=e.offsetBottom),null!=e.offsetTop&&(e.offset.top=e.offsetTop),i.call(t,e)})})}(jQuery);;
/**
*  Ajax Autocomplete for jQuery, version 1.3.0
*  (c) 2017 Tomas Kirda
*
*  Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.
*  For details, see the web site: https://github.com/devbridge/jQuery-Autocomplete
*/

/*jslint  browser: true, white: true, single: true, this: true, multivar: true */
/*global define, window, document, jQuery, exports, require */

// Expose plugin as an AMD module if AMD loader is present:
(function (factory) {
    "use strict";
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object' && typeof require === 'function') {
        // Browserify
        factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {
    'use strict';

    var
        utils = (function () {
            return {
                escapeRegExChars: function (value) {
                    return value.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
                },
                createNode: function (containerClass) {
                    var div = document.createElement('div');
                    div.className = containerClass;
                    div.style.position = 'absolute';
                    div.style.display = 'none';
                    return div;
                }
            };
        }()),

        keys = {
            ESC: 27,
            TAB: 9,
            RETURN: 13,
            LEFT: 37,
            UP: 38,
            RIGHT: 39,
            DOWN: 40
        };

    function Autocomplete(el, options) {
        var noop = $.noop,
            that = this,
            defaults = {
                ajaxSettings: {},
                autoSelectFirst: false,
                appendTo: document.body,
                serviceUrl: null,
                lookup: null,
                onSelect: null,
                width: 'auto',
                minChars: 1,
                maxHeight: 300,
                deferRequestBy: 0,
                params: {},
                formatResult: Autocomplete.formatResult,
                formatGroup: Autocomplete.formatGroup,
                delimiter: null,
                zIndex: 9999,
                type: 'GET',
                noCache: false,
                onSearchStart: noop,
                onSearchComplete: noop,
                onSearchError: noop,
                preserveInput: false,
                containerClass: 'autocomplete-suggestions',
                tabDisabled: false,
                dataType: 'text',
                currentRequest: null,
                triggerSelectOnValidInput: true,
                preventBadQueries: true,
                lookupFilter: function (suggestion, originalQuery, queryLowerCase) {
                    return suggestion.value.toLowerCase().indexOf(queryLowerCase) !== -1;
                },
                paramName: 'query',
                transformResult: function (response) {
                    return typeof response === 'string' ? $.parseJSON(response) : response;
                },
                showNoSuggestionNotice: false,
                noSuggestionNotice: 'No results',
                orientation: 'bottom',
                forceFixPosition: false
            };

        // Shared variables:
        that.element = el;
        that.el = $(el);
        that.suggestions = [];
        that.badQueries = [];
        that.selectedIndex = -1;
        that.currentValue = that.element.value;
        that.intervalId = 0;
        that.cachedResponse = {};
        that.onChangeInterval = null;
        that.onChange = null;
        that.isLocal = false;
        that.suggestionsContainer = null;
        that.noSuggestionsContainer = null;
        that.options = $.extend({}, defaults, options);
        that.classes = {
            selected: 'autocomplete-selected',
            suggestion: 'autocomplete-suggestion'
        };
        that.hint = null;
        that.hintValue = '';
        that.selection = null;

        // Initialize and set options:
        that.initialize();
        that.setOptions(options);
    }

    Autocomplete.utils = utils;

    $.Autocomplete = Autocomplete;

    Autocomplete.formatResult = function (suggestion, currentValue) {
        // Do not replace anything if there current value is empty
        if (!currentValue) {
            return suggestion.value;
        }
        
        var pattern = '(' + utils.escapeRegExChars(currentValue) + ')';

        return suggestion.value
            .replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/&lt;(\/?strong)&gt;/g, '<$1>');
    };

    Autocomplete.formatGroup = function (suggestion, category) {
        return '<div class="autocomplete-group"><strong>' + category + '</strong></div>';
    };

    Autocomplete.prototype = {

        killerFn: null,

        initialize: function () {
            var that = this,
                suggestionSelector = '.' + that.classes.suggestion,
                selected = that.classes.selected,
                options = that.options,
                container;

            // Remove autocomplete attribute to prevent native suggestions:
            that.element.setAttribute('autocomplete', 'off');

            that.killerFn = function (e) {
                if (!$(e.target).closest('.' + that.options.containerClass).length) {
                    that.killSuggestions();
                    that.disableKillerFn();
                }
            };

            // html() deals with many types: htmlString or Element or Array or jQuery
            that.noSuggestionsContainer = $('<div class="autocomplete-no-suggestion"></div>')
                                          .html(this.options.noSuggestionNotice).get(0);

            that.suggestionsContainer = Autocomplete.utils.createNode(options.containerClass);

            container = $(that.suggestionsContainer);

            container.appendTo(options.appendTo);

            // Only set width if it was provided:
            if (options.width !== 'auto') {
                container.css('width', options.width);
            }

            // Listen for mouse over event on suggestions list:
            container.on('mouseover.autocomplete', suggestionSelector, function () {
                that.activate($(this).data('index'));
            });

            // Deselect active element when mouse leaves suggestions container:
            container.on('mouseout.autocomplete', function () {
                that.selectedIndex = -1;
                container.children('.' + selected).removeClass(selected);
            });

            // Listen for click event on suggestions list:
            container.on('click.autocomplete', suggestionSelector, function () {
                that.select($(this).data('index'));
                return false;
            });

            that.fixPositionCapture = function () {
                if (that.visible) {
                    that.fixPosition();
                }
            };

            $(window).on('resize.autocomplete', that.fixPositionCapture);

            that.el.on('keydown.autocomplete', function (e) { that.onKeyPress(e); });
            that.el.on('keyup.autocomplete', function (e) { that.onKeyUp(e); });
            that.el.on('blur.autocomplete', function () { that.onBlur(); });
            that.el.on('focus.autocomplete', function () { that.onFocus(); });
            that.el.on('change.autocomplete', function (e) { that.onKeyUp(e); });
            that.el.on('input.autocomplete', function (e) { that.onKeyUp(e); });
        },

        onFocus: function () {
            var that = this;

            that.fixPosition();

            if (that.el.val().length >= that.options.minChars) {
                that.onValueChange();
            }
        },

        onBlur: function () {
            this.enableKillerFn();
        },
        
        abortAjax: function () {
            var that = this;
            if (that.currentRequest) {
                that.currentRequest.abort();
                that.currentRequest = null;
            }
        },

        setOptions: function (suppliedOptions) {
            var that = this,
                options = that.options;

            $.extend(options, suppliedOptions);

            that.isLocal = $.isArray(options.lookup);

            if (that.isLocal) {
                options.lookup = that.verifySuggestionsFormat(options.lookup);
            }

            options.orientation = that.validateOrientation(options.orientation, 'bottom');

            // Adjust height, width and z-index:
            $(that.suggestionsContainer).css({
                'max-height': options.maxHeight + 'px',
                'width': options.width + 'px',
                'z-index': options.zIndex
            });
        },


        clearCache: function () {
            this.cachedResponse = {};
            this.badQueries = [];
        },

        clear: function () {
            this.clearCache();
            this.currentValue = '';
            this.suggestions = [];
        },

        disable: function () {
            var that = this;
            that.disabled = true;
            clearInterval(that.onChangeInterval);
            that.abortAjax();
        },

        enable: function () {
            this.disabled = false;
        },

        fixPosition: function () {
            // Use only when container has already its content

            var that = this,
                $container = $(that.suggestionsContainer),
                containerParent = $container.parent().get(0);
            // Fix position automatically when appended to body.
            // In other cases force parameter must be given.
            if (containerParent !== document.body && !that.options.forceFixPosition) {
                return;
            }

            // Choose orientation
            var orientation = that.options.orientation,
                containerHeight = $container.outerHeight(),
                height = that.el.outerHeight(),
                offset = that.el.offset(),
                styles = { 'top': offset.top, 'left': offset.left };

            if (orientation === 'auto') {
                var viewPortHeight = $(window).height(),
                    scrollTop = $(window).scrollTop(),
                    topOverflow = -scrollTop + offset.top - containerHeight,
                    bottomOverflow = scrollTop + viewPortHeight - (offset.top + height + containerHeight);

                orientation = (Math.max(topOverflow, bottomOverflow) === topOverflow) ? 'top' : 'bottom';
            }

            if (orientation === 'top') {
                styles.top += -containerHeight;
            } else {
                styles.top += height;
            }

            // If container is not positioned to body,
            // correct its position using offset parent offset
            if(containerParent !== document.body) {
                var opacity = $container.css('opacity'),
                    parentOffsetDiff;

                    if (!that.visible){
                        $container.css('opacity', 0).show();
                    }

                parentOffsetDiff = $container.offsetParent().offset();
                styles.top -= parentOffsetDiff.top;
                styles.left -= parentOffsetDiff.left;

                if (!that.visible){
                    $container.css('opacity', opacity).hide();
                }
            }

            if (that.options.width === 'auto') {
                styles.width = that.el.outerWidth() + 'px';
            }

            $container.css(styles);
        },

        enableKillerFn: function () {
            var that = this;
            $(document).on('click.autocomplete', that.killerFn);
        },

        disableKillerFn: function () {
            var that = this;
            $(document).off('click.autocomplete', that.killerFn);
        },

        killSuggestions: function () {
            var that = this;
            that.stopKillSuggestions();
            that.intervalId = window.setInterval(function () {
                if (that.visible) {
                    // No need to restore value when 
                    // preserveInput === true, 
                    // because we did not change it
                    if (!that.options.preserveInput) {
                        that.el.val(that.currentValue);
                    }

                    that.hide();
                }
                
                that.stopKillSuggestions();
            }, 50);
        },

        stopKillSuggestions: function () {
            window.clearInterval(this.intervalId);
        },

        isCursorAtEnd: function () {
            var that = this,
                valLength = that.el.val().length,
                selectionStart = that.element.selectionStart,
                range;

            if (typeof selectionStart === 'number') {
                return selectionStart === valLength;
            }
            if (document.selection) {
                range = document.selection.createRange();
                range.moveStart('character', -valLength);
                return valLength === range.text.length;
            }
            return true;
        },

        onKeyPress: function (e) {
            var that = this;

            // If suggestions are hidden and user presses arrow down, display suggestions:
            if (!that.disabled && !that.visible && e.which === keys.DOWN && that.currentValue) {
                that.suggest();
                return;
            }

            if (that.disabled || !that.visible) {
                return;
            }

            switch (e.which) {
                case keys.ESC:
                    that.el.val(that.currentValue);
                    that.hide();
                    break;
                case keys.RIGHT:
                    if (that.hint && that.options.onHint && that.isCursorAtEnd()) {
                        that.selectHint();
                        break;
                    }
                    return;
                case keys.TAB:
                    if (that.hint && that.options.onHint) {
                        that.selectHint();
                        return;
                    }
                    if (that.selectedIndex === -1) {
                        that.hide();
                        return;
                    }
                    that.select(that.selectedIndex);
                    if (that.options.tabDisabled === false) {
                        return;
                    }
                    break;
                case keys.RETURN:
                    if (that.selectedIndex === -1) {
                        that.hide();
                        return;
                    }
                    that.select(that.selectedIndex);
                    return;//break;
                case keys.UP:
                    that.moveUp();
                    break;
                case keys.DOWN:
                    that.moveDown();
                    break;
                default:
                    return;
            }

            // Cancel event if function did not return:
            e.stopImmediatePropagation();
            e.preventDefault();
        },

        onKeyUp: function (e) {
            var that = this;

            if (that.disabled) {
                return;
            }

            switch (e.which) {
                case keys.UP:
                case keys.DOWN:
                    return;
            }

            clearInterval(that.onChangeInterval);

            if (that.currentValue !== that.el.val()) {
                that.findBestHint();
                if (that.options.deferRequestBy > 0) {
                    // Defer lookup in case when value changes very quickly:
                    that.onChangeInterval = setInterval(function () {
                        that.onValueChange();
                    }, that.options.deferRequestBy);
                } else {
                    that.onValueChange();
                }
            }
        },

        onValueChange: function () {
            var that = this,
                options = that.options,
                value = that.el.val(),
                query = that.getQuery(value);

            if (that.selection && that.currentValue !== query) {
                that.selection = null;
                (options.onInvalidateSelection || $.noop).call(that.element);
            }

            clearInterval(that.onChangeInterval);
            that.currentValue = value;
            that.selectedIndex = -1;

            // Check existing suggestion for the match before proceeding:
            if (options.triggerSelectOnValidInput && that.isExactMatch(query)) {
                that.select(0);
                return;
            }

            if (query.length < options.minChars) {
                that.hide();
            } else {
                that.getSuggestions(query);
            }
        },

        isExactMatch: function (query) {
            var suggestions = this.suggestions;

            return (suggestions.length === 1 && suggestions[0].value.toLowerCase() === query.toLowerCase());
        },

        getQuery: function (value) {
            var delimiter = this.options.delimiter,
                parts;

            if (!delimiter) {
                return value;
            }
            parts = value.split(delimiter);
            return $.trim(parts[parts.length - 1]);
        },

        getSuggestionsLocal: function (query) {
            var that = this,
                options = that.options,
                queryLowerCase = query.toLowerCase(),
                filter = options.lookupFilter,
                limit = parseInt(options.lookupLimit, 10),
                data;

            data = {
                suggestions: $.grep(options.lookup, function (suggestion) {
                    return filter(suggestion, query, queryLowerCase);
                })
            };

            if (limit && data.suggestions.length > limit) {
                data.suggestions = data.suggestions.slice(0, limit);
            }

            return data;
        },

        getSuggestions: function (q) {
            var response,
                that = this,
                options = that.options,
                serviceUrl = options.serviceUrl,
                params,
                cacheKey,
                ajaxSettings;

            options.params[options.paramName] = q;
            params = options.ignoreParams ? null : options.params;

            if (options.onSearchStart.call(that.element, options.params) === false) {
                return;
            }

            if ($.isFunction(options.lookup)){
                options.lookup(q, function (data) {
                    that.suggestions = data.suggestions;
                    that.suggest();
                    options.onSearchComplete.call(that.element, q, data.suggestions);
                });
                return;
            }

            if (that.isLocal) {
                response = that.getSuggestionsLocal(q);
            } else {
                if ($.isFunction(serviceUrl)) {
                    serviceUrl = serviceUrl.call(that.element, q);
                }
                cacheKey = serviceUrl + '?' + $.param(params || {});
                response = that.cachedResponse[cacheKey];
            }

            if (response && $.isArray(response.suggestions)) {
                that.suggestions = response.suggestions;
                that.suggest();
                options.onSearchComplete.call(that.element, q, response.suggestions);
            } else if (!that.isBadQuery(q)) {
                that.abortAjax();

                ajaxSettings = {
                    url: serviceUrl,
                    data: params,
                    type: options.type,
                    dataType: options.dataType
                };

                $.extend(ajaxSettings, options.ajaxSettings);

                that.currentRequest = $.ajax(ajaxSettings).done(function (data) {
                    var result;
                    that.currentRequest = null;
                    result = options.transformResult(data, q);
                    that.processResponse(result, q, cacheKey);
                    options.onSearchComplete.call(that.element, q, result.suggestions);
                }).fail(function (jqXHR, textStatus, errorThrown) {
                    options.onSearchError.call(that.element, q, jqXHR, textStatus, errorThrown);
                });
            } else {
                options.onSearchComplete.call(that.element, q, []);
            }
        },

        isBadQuery: function (q) {
            if (!this.options.preventBadQueries){
                return false;
            }

            var badQueries = this.badQueries,
                i = badQueries.length;

            while (i--) {
                if (q.indexOf(badQueries[i]) === 0) {
                    return true;
                }
            }

            return false;
        },

        hide: function () {
            var that = this,
                container = $(that.suggestionsContainer);

            if ($.isFunction(that.options.onHide) && that.visible) {
                that.options.onHide.call(that.element, container);
            }

            that.visible = false;
            that.selectedIndex = -1;
            clearInterval(that.onChangeInterval);
            $(that.suggestionsContainer).hide();
            that.signalHint(null);
        },

        suggest: function () {
            if (!this.suggestions.length) {
                if (this.options.showNoSuggestionNotice) {
                    this.noSuggestions();
                } else {
                    this.hide();
                }
                return;
            }

            var that = this,
                options = that.options,
                groupBy = options.groupBy,
                formatResult = options.formatResult,
                value = that.getQuery(that.currentValue),
                className = that.classes.suggestion,
                classSelected = that.classes.selected,
                container = $(that.suggestionsContainer),
                noSuggestionsContainer = $(that.noSuggestionsContainer),
                beforeRender = options.beforeRender,
                html = '',
                category,
                formatGroup = function (suggestion, index) {
                        var currentCategory = suggestion.data[groupBy];

                        if (category === currentCategory){
                            return '';
                        }

                        category = currentCategory;

                        return options.formatGroup(suggestion, category);
                    };

            if (options.triggerSelectOnValidInput && that.isExactMatch(value)) {
                that.select(0);
                return;
            }

            // Build suggestions inner HTML:
            $.each(that.suggestions, function (i, suggestion) {
                if (groupBy){
                    html += formatGroup(suggestion, value, i);
                }

                html += '<div class="' + className + '" data-index="' + i + '">' + formatResult(suggestion, value, i) + '</div>';
            });

            this.adjustContainerWidth();

            noSuggestionsContainer.detach();
            container.html(html);

            if ($.isFunction(beforeRender)) {
                beforeRender.call(that.element, container, that.suggestions);
            }

            that.fixPosition();
            container.show();

            // Select first value by default:
            if (options.autoSelectFirst) {
                that.selectedIndex = 0;
                container.scrollTop(0);
                container.children('.' + className).first().addClass(classSelected);
            }

            that.visible = true;
            that.findBestHint();
        },

        noSuggestions: function() {
             var that = this,
                 container = $(that.suggestionsContainer),
                 noSuggestionsContainer = $(that.noSuggestionsContainer);

            this.adjustContainerWidth();

            // Some explicit steps. Be careful here as it easy to get
            // noSuggestionsContainer removed from DOM if not detached properly.
            noSuggestionsContainer.detach();
            container.empty(); // clean suggestions if any
            container.append(noSuggestionsContainer);

            that.fixPosition();

            container.show();
            that.visible = true;
        },

        adjustContainerWidth: function() {
            var that = this,
                options = that.options,
                width,
                container = $(that.suggestionsContainer);

            // If width is auto, adjust width before displaying suggestions,
            // because if instance was created before input had width, it will be zero.
            // Also it adjusts if input width has changed.
            if (options.width === 'auto') {
                width = that.el.outerWidth();
                container.css('width', width > 0 ? width : 300);
            } else if(options.width === 'flex') {
                // Trust the source! Unset the width property so it will be the max length
                // the containing elements.
                container.css('width', '');
            }
        },

        findBestHint: function () {
            var that = this,
                value = that.el.val().toLowerCase(),
                bestMatch = null;

            if (!value) {
                return;
            }

            $.each(that.suggestions, function (i, suggestion) {
                var foundMatch = suggestion.value.toLowerCase().indexOf(value) === 0;
                if (foundMatch) {
                    bestMatch = suggestion;
                }
                return !foundMatch;
            });

            that.signalHint(bestMatch);
        },

        signalHint: function (suggestion) {
            var hintValue = '',
                that = this;
            if (suggestion) {
                hintValue = that.currentValue + suggestion.value.substr(that.currentValue.length);
            }
            if (that.hintValue !== hintValue) {
                that.hintValue = hintValue;
                that.hint = suggestion;
                (this.options.onHint || $.noop)(hintValue);
            }
        },

        verifySuggestionsFormat: function (suggestions) {
            // If suggestions is string array, convert them to supported format:
            if (suggestions.length && typeof suggestions[0] === 'string') {
                return $.map(suggestions, function (value) {
                    return { value: value, data: null };
                });
            }

            return suggestions;
        },

        validateOrientation: function(orientation, fallback) {
            orientation = $.trim(orientation || '').toLowerCase();

            if($.inArray(orientation, ['auto', 'bottom', 'top']) === -1){
                orientation = fallback;
            }

            return orientation;
        },

        processResponse: function (result, originalQuery, cacheKey) {
            var that = this,
                options = that.options;

            result.suggestions = that.verifySuggestionsFormat(result.suggestions);

            // Cache results if cache is not disabled:
            if (!options.noCache) {
                that.cachedResponse[cacheKey] = result;
                if (options.preventBadQueries && !result.suggestions.length) {
                    that.badQueries.push(originalQuery);
                }
            }

            // Return if originalQuery is not matching current query:
            if (originalQuery !== that.getQuery(that.currentValue)) {
                return;
            }

            that.suggestions = result.suggestions;
            that.suggest();
        },

        activate: function (index) {
            var that = this,
                activeItem,
                selected = that.classes.selected,
                container = $(that.suggestionsContainer),
                children = container.find('.' + that.classes.suggestion);

            container.find('.' + selected).removeClass(selected);

            that.selectedIndex = index;

            if (that.selectedIndex !== -1 && children.length > that.selectedIndex) {
                activeItem = children.get(that.selectedIndex);
                $(activeItem).addClass(selected);
                return activeItem;
            }

            return null;
        },

        selectHint: function () {
            var that = this,
                i = $.inArray(that.hint, that.suggestions);

            that.select(i);
        },

        select: function (i) {
            var that = this;
            that.hide();
            that.onSelect(i);
            that.disableKillerFn();
        },

        moveUp: function () {
            var that = this;

            if (that.selectedIndex === -1) {
                return;
            }

            if (that.selectedIndex === 0) {
                $(that.suggestionsContainer).children().first().removeClass(that.classes.selected);
                that.selectedIndex = -1;
                that.el.val(that.currentValue);
                that.findBestHint();
                return;
            }

            that.adjustScroll(that.selectedIndex - 1);
        },

        moveDown: function () {
            var that = this;

            if (that.selectedIndex === (that.suggestions.length - 1)) {
                return;
            }

            that.adjustScroll(that.selectedIndex + 1);
        },

        adjustScroll: function (index) {
            var that = this,
                activeItem = that.activate(index);

            if (!activeItem) {
                return;
            }

            var offsetTop,
                upperBound,
                lowerBound,
                heightDelta = $(activeItem).outerHeight();

            offsetTop = activeItem.offsetTop;
            upperBound = $(that.suggestionsContainer).scrollTop();
            lowerBound = upperBound + that.options.maxHeight - heightDelta;

            if (offsetTop < upperBound) {
                $(that.suggestionsContainer).scrollTop(offsetTop);
            } else if (offsetTop > lowerBound) {
                $(that.suggestionsContainer).scrollTop(offsetTop - that.options.maxHeight + heightDelta);
            }

            if (!that.options.preserveInput) {
                that.el.val(that.getValue(that.suggestions[index].value));
            }
            that.signalHint(null);
        },

        onSelect: function (index) {
            var that = this,
                onSelectCallback = that.options.onSelect,
                suggestion = that.suggestions[index];

            that.currentValue = that.getValue(suggestion.value);

            if (that.currentValue !== that.el.val() && !that.options.preserveInput) {
                that.el.val(that.currentValue);
            }

            that.signalHint(null);
            that.suggestions = [];
            that.selection = suggestion;

            if ($.isFunction(onSelectCallback)) {
                onSelectCallback.call(that.element, suggestion);
            }
        },

        getValue: function (value) {
            var that = this,
                delimiter = that.options.delimiter,
                currentValue,
                parts;

            if (!delimiter) {
                return value;
            }

            currentValue = that.currentValue;
            parts = currentValue.split(delimiter);

            if (parts.length === 1) {
                return value;
            }

            return currentValue.substr(0, currentValue.length - parts[parts.length - 1].length) + value;
        },

        dispose: function () {
            var that = this;
            that.el.off('.autocomplete').removeData('autocomplete');
            that.disableKillerFn();
            $(window).off('resize.autocomplete', that.fixPositionCapture);
            $(that.suggestionsContainer).remove();
        }
    };

    // Create chainable jQuery plugin:
    $.fn.autocomplete = $.fn.devbridgeAutocomplete = function (options, args) {
        var dataKey = 'autocomplete';
        // If function invoked without argument return
        // instance of the first matched element:
        if (!arguments.length) {
            return this.first().data(dataKey);
        }

        return this.each(function () {
            var inputElement = $(this),
                instance = inputElement.data(dataKey);

            if (typeof options === 'string') {
                if (instance && typeof instance[options] === 'function') {
                    instance[options](args);
                }
            } else {
                // If instance already exists, destroy it:
                if (instance && instance.dispose) {
                    instance.dispose();
                }
                instance = new Autocomplete(this, options);
                inputElement.data(dataKey, instance);
            }
        });
    };
}));
;
/* NUGET: BEGIN LICENSE TEXT
 *
 * Microsoft grants you the right to use these script files for the sole
 * purpose of either: (i) interacting through your browser with the Microsoft
 * website or online service, subject to the applicable licensing or use
 * terms; or (ii) using the files as included with a Microsoft product subject
 * to that product's license terms. Microsoft reserves all other rights to the
 * files not expressly granted by Microsoft, whether by implication, estoppel
 * or otherwise. Insofar as a script file is dual licensed under GPL,
 * Microsoft neither took the code under GPL nor distributes it thereunder but
 * under the terms set out in this paragraph. All notices and licenses
 * below are for informational purposes only.
 *
 * NUGET: END LICENSE TEXT */
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
window.matchMedia=window.matchMedia||(function(e,f){var c,a=e.documentElement,b=a.firstElementChild||a.firstChild,d=e.createElement("body"),g=e.createElement("div");g.id="mq-test-1";g.style.cssText="position:absolute;top:-100em";d.style.background="none";d.appendChild(g);return function(h){g.innerHTML='&shy;<style media="'+h+'"> #mq-test-1 { width: 42px; }</style>';a.insertBefore(d,b);c=g.offsetWidth==42;a.removeChild(d);return{matches:c,media:h}}})(document);

/*! Respond.js v1.2.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs  */
(function(e){e.respond={};respond.update=function(){};respond.mediaQueriesSupported=e.matchMedia&&e.matchMedia("only all").matches;if(respond.mediaQueriesSupported){return}var w=e.document,s=w.documentElement,i=[],k=[],q=[],o={},h=30,f=w.getElementsByTagName("head")[0]||s,g=w.getElementsByTagName("base")[0],b=f.getElementsByTagName("link"),d=[],a=function(){var D=b,y=D.length,B=0,A,z,C,x;for(;B<y;B++){A=D[B],z=A.href,C=A.media,x=A.rel&&A.rel.toLowerCase()==="stylesheet";if(!!z&&x&&!o[z]){if(A.styleSheet&&A.styleSheet.rawCssText){m(A.styleSheet.rawCssText,z,C);o[z]=true}else{if((!/^([a-zA-Z:]*\/\/)/.test(z)&&!g)||z.replace(RegExp.$1,"").split("/")[0]===e.location.host){d.push({href:z,media:C})}}}}u()},u=function(){if(d.length){var x=d.shift();n(x.href,function(y){m(y,x.href,x.media);o[x.href]=true;u()})}},m=function(I,x,z){var G=I.match(/@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi),J=G&&G.length||0,x=x.substring(0,x.lastIndexOf("/")),y=function(K){return K.replace(/(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,"$1"+x+"$2$3")},A=!J&&z,D=0,C,E,F,B,H;if(x.length){x+="/"}if(A){J=1}for(;D<J;D++){C=0;if(A){E=z;k.push(y(I))}else{E=G[D].match(/@media *([^\{]+)\{([\S\s]+?)$/)&&RegExp.$1;k.push(RegExp.$2&&y(RegExp.$2))}B=E.split(",");H=B.length;for(;C<H;C++){F=B[C];i.push({media:F.split("(")[0].match(/(only\s+)?([a-zA-Z]+)\s?/)&&RegExp.$2||"all",rules:k.length-1,hasquery:F.indexOf("(")>-1,minw:F.match(/\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||""),maxw:F.match(/\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||"")})}}j()},l,r,v=function(){var z,A=w.createElement("div"),x=w.body,y=false;A.style.cssText="position:absolute;font-size:1em;width:1em";if(!x){x=y=w.createElement("body");x.style.background="none"}x.appendChild(A);s.insertBefore(x,s.firstChild);z=A.offsetWidth;if(y){s.removeChild(x)}else{x.removeChild(A)}z=p=parseFloat(z);return z},p,j=function(I){var x="clientWidth",B=s[x],H=w.compatMode==="CSS1Compat"&&B||w.body[x]||B,D={},G=b[b.length-1],z=(new Date()).getTime();if(I&&l&&z-l<h){clearTimeout(r);r=setTimeout(j,h);return}else{l=z}for(var E in i){var K=i[E],C=K.minw,J=K.maxw,A=C===null,L=J===null,y="em";if(!!C){C=parseFloat(C)*(C.indexOf(y)>-1?(p||v()):1)}if(!!J){J=parseFloat(J)*(J.indexOf(y)>-1?(p||v()):1)}if(!K.hasquery||(!A||!L)&&(A||H>=C)&&(L||H<=J)){if(!D[K.media]){D[K.media]=[]}D[K.media].push(k[K.rules])}}for(var E in q){if(q[E]&&q[E].parentNode===f){f.removeChild(q[E])}}for(var E in D){var M=w.createElement("style"),F=D[E].join("\n");M.type="text/css";M.media=E;f.insertBefore(M,G.nextSibling);if(M.styleSheet){M.styleSheet.cssText=F}else{M.appendChild(w.createTextNode(F))}q.push(M)}},n=function(x,z){var y=c();if(!y){return}y.open("GET",x,true);y.onreadystatechange=function(){if(y.readyState!=4||y.status!=200&&y.status!=304){return}z(y.responseText)};if(y.readyState==4){return}y.send(null)},c=(function(){var x=false;try{x=new XMLHttpRequest()}catch(y){x=new ActiveXObject("Microsoft.XMLHTTP")}return function(){return x}})();a();respond.update=a;function t(){j(true)}if(e.addEventListener){e.addEventListener("resize",t,false)}else{if(e.attachEvent){e.attachEvent("onresize",t)}}})(this);;
//var modalHiddenViaPop = false;  //used to tell if we are manually calling the modal hide event
var originalUrl = null, currentModalUrl = null;
var statesPushed = 0;
var oldState = null;
var modalShowing = false;

function toggleEditCriteria()
{
    if ($("#criteriaBlock").is(':visible')) {
        $("#criteriaBlock").toggle();
        $("#criteriaForm").toggleClass("hidden");

        //if had extra criteria in search then show the extra criteria block
        if ($("#Country").val() != '' || $("#County").val() != '' || $("#Relative").val() != '' || $("#DodYYYY").val() != '' || $("#DodMM").val() != '' || $("#DodDD").val() != '') $("#addCriteria").trigger("click");
        
        if (typeof ga !== 'undefined') {
            var label = getSearchTypeFromUrl(window.location.pathname);
            ga('send', 'event', 'search-edit', 'click', label);
        }
    }
    else {
        $("#criteriaForm").toggleClass("hidden");
        $("#criteriaBlock").toggle();
    }
}

//window.addEventListener("popstate", function(e) {
//    console.log('popstate called');
//    //console.log('modal showing: ' + modalShowing);
//    //console.log(statesPushed);
//    //if (e.state) {

//    //    if (e.state.treeContent && $("#treeContent") && $("#treeContent").length) {
//    //        console.log(e.state.treeContent);
//    //        $("#treeContent").html(e.state.treeContent);
//    //    }
//    //}
//    //if (e.state) {
//    //    //console.log(e.state.summaryResults);
//    //    oldState = e.state.summaryResults;
//    //    if (jQuery.isReady) {
//    //        console.log('jquery ready');
//    //        //$('#summaryResults').html(event.state.summaryResults);
//    //    }
//    //}
//    //if (originalUrl == null) return;    //some browsers call popstate on page load
//    //if (jQuery.isReady && statesPushed > 0 && modalShowing/*$("#detailModal").data('bs.modal') && $("#detailModal").data('bs.modal').isShown*/ /*$("#detailModal").data() && $("#detailModal").data()['bs.modal'] && $("#detailModal").data()['bs.modal'].isShown*/) {
//    //    //modalHiddenViaPop = true;
        
//    //    //originalUrl = document.location;
//    //    $(".modal").modal("hide");
//    //}
//    //else if (statesPushed > 0 && (!modalShowing)/*!$("#detailModal").data('bs.modal') || !$("#detailModal").data('bs.modal').isShown)*/) history.go(-statesPushed);
//    //statesPushed--;
//   // alert(statesPushed);
//});

//if we pushed state and never clicked back button we will be 1 ahead. If user then clicks a link on the page then clicks back it
//won't work so we replace state
//window.addEventListener("unload", function (e) {
//    if (history.replaceState) {
//        //console.log('onbeforeunload called');
//        if (originalUrl != null) {
//            history.replaceState(null, "", originalUrl);
//        }
//        //return null;  //ie shows alert to user if we return anything from this function
//    }
//});

//push state with detail url, now when user clicks back button it will just close the modal
//and work fine, otherwise it would actually go back a page
//$($("#detailModal").on('show.bs.modal', function (e) {
//    alert($(this).html());
//    var extraParam = '_1=1';
//    if (e.relatedTarget.toString().indexOf("?") == -1) extraParam = "?" + extraParam; else extraParam = "&" + extraParam;
//    currentModalUrl = e.relatedTarget + extraParam;
//    if (history.pushState) {
//        var state = { summaryResults: $('#summaryResults').html() };
//        if (originalUrl == null) originalUrl = document.location.toString();
//        if (statesPushed == 0) {
//            //history.replaceState(state, "", originalUrl);
//            history.pushState(state, "", e.relatedTarget + extraParam);
//            statesPushed++;
//            //console.log('pushstate called:' + state.summaryResults);
//        }
//        else history.replaceState(state, "", e.relatedTarget + extraParam);
//    }
//}));

$("[data-target='#detailModal']").on('click', function (e) {
    e.preventDefault();
    var remote = $(this).attr("href").valueOf();
    var permaLink = $(this).data("perma-link");
    
    if (remote) {
        var modalId = "detailModal" + Math.random().toString().replace(".", "");
        $("body").append("<div class='modal' id='" + modalId + "' tabindex='-1' role='dialog' aria-labelledby='detailModalLabel' aria-hidden='true'><div class='modal-dialog'><div class='modal-content'></div></div></div>");
        $("#" + modalId).find(".modal-content").load(remote);
        $("#" + modalId).modal('show');
        modalShowing = true;

        var extraParam = '_1=1';
        if (remote.indexOf("?") == -1) extraParam = "?" + extraParam; else extraParam = "&" + extraParam;
        currentModalUrl = remote + extraParam;
        if (history.pushState) {
            var state = { summaryResults: "" };
            if (originalUrl == null) originalUrl = document.location.toString();
            if (statesPushed == 0) {
                //history.replaceState(state, "", originalUrl);
                //history.pushState(state, "", remote + extraParam);
                if (typeof permaLink != 'undefined')
                    history.pushState(state, "", permaLink);
                else
                    history.pushState(state, "", remote + extraParam);
                statesPushed++;
                //console.log('pushstate called:' + state.summaryResults);
            }
            else {
                if (typeof permaLink !== 'undefined')
                    history.replaceState(state, "", permaLink);
                else
                    history.replaceState(state, "", remote + extraParam);
            }
        }

        if (typeof ga !== 'undefined') {
            //log event as page view too since ga won't count it as a page view, even though it really is
            ga('send', 'pageview', remote);
        }
    }
});

//when we close modal we want to go back one spot on history because we pushed state when opening
//url's get changed when opening and closing modal so user can share url and back button will work
//$($('body').on('hide.bs.modal', function (e) {
//    if (history.replaceState) history.replaceState(null, "", originalUrl);
//    modalShowing = false;
//    //if (!modalHiddenViaPop) history.back();
//    //else modalHiddenViaPop = false;  
//}));

//allows same modal to be opened with new data
//$($(document).on("hidden.bs.modal", function (e) {
//    $(e.target).removeData("bs.modal").find(".modal-content").empty();
//}));

$($(".editCriteria").click(function () {
    toggleEditCriteria();
}));

$($("#editCriteriaBottom").click(function () {
    if ($("#criteriaBlock").is(':visible')) toggleEditCriteria();
    window.scrollTo(0, 0);
}));

$($("#addCriteria").click(function () {
    $("#addCriteria").hide();
    
    $("#extraCriteria").removeClass("hidden");

    if (typeof ga !== 'undefined') {
        var label = getSearchTypeFromUrl(window.location.pathname);
        ga('send', 'event', 'search-add-criteria', 'click', label);
    }
}));

$($("#clearCriteria").click(function (event) {
    event.preventDefault();

    $("#First").val("");
    $("#Middle").val("");
    $("#Last").val("");
    $("#City").val("");
    $("#CityStateZip").val("");
    $("#County").val("");
    $("#Country").val("");
    $("#DobYYYY").val("");
    $("#Relative").val("");
    $("#DodYYYY").val("");
    $("#State").val("");
    $("#DodMM").val("");
    $("#DodDD").val("");
    $("#StreetAddress").val("");
    $("#PhoneNo").val("");

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'search-clear-criteria', 'click', '');
    }
}));

$($(".search-button").click(function (event) {
    $(this).html("<i class='fa fa-spinner fa-lg fa-spin'></i>");
    //$(this).val("Searching...");

    var thisForm = $(this).parents("form");

    var location = thisForm.attr("action");
    var index = 0;
    var gaLabel = "";

    //only append criteria that has been entered to keep url clean
    if (thisForm.find("#First") && thisForm.find("#First").val() && thisForm.find("#First").val() != '') {
        if (index == 0) location += "?"; else location += "&";
        if (index != 0) gaLabel += '-';
        gaLabel += 'first';
        location += "first=" + thisForm.find("#First").val();
        index++;
    }
    if (thisForm.find("#Middle") && thisForm.find("#Middle").val() && thisForm.find("#Middle").val() != '') {
        if (index == 0) location += "?"; else location += "&";
        if (index != 0) gaLabel += '-';
        gaLabel += 'middle';
        location += "middle=" + thisForm.find("#Middle").val();
        index++;
    }
    if (thisForm.find("#Last") && thisForm.find("#Last").val() && thisForm.find("#Last").val() != '') {
        if (index == 0) location += "?"; else location += "&";
        if (index != 0) gaLabel += '-';
        gaLabel += 'last';
        location += "last=" + thisForm.find("#Last").val();
        index++;
    }
    if (thisForm.find("#StreetAddress") && thisForm.find("#StreetAddress").val() && thisForm.find("#StreetAddress").val() != '') {
        if (index == 0) location += "?"; else location += "&";
        if (index != 0) gaLabel += '-';
        gaLabel += 'address';
        location += "streetaddress=" + encodeURIComponent(thisForm.find("#StreetAddress").val());
        index++;
    }
    if (thisForm.find("#City") && thisForm.find("#City").val() && thisForm.find("#City").val() != '') {
        if (index == 0) location += "?"; else location += "&";
        if (index != 0) gaLabel += '-';
        gaLabel += 'city';
        location += "city=" + thisForm.find("#City").val();
        index++;
    }
    if (thisForm.find("#CityStateZip") && thisForm.find("#CityStateZip").val() && thisForm.find("#CityStateZip").val() != '') {
        if (index == 0) location += "?"; else location += "&";
        if (index != 0) gaLabel += '-';
        gaLabel += 'citystatezip';
        location += "citystatezip=" + thisForm.find("#CityStateZip").val();
        index++;
    }
    if (thisForm.find("#County") && thisForm.find("#County").val() && thisForm.find("#County").val() != '') {
        if (index == 0) location += "?"; else location += "&";
        if (index != 0) gaLabel += '-';
        gaLabel += 'county';
        location += "county=" + thisForm.find("#County").val();
        index++;
    }
    if (thisForm.find("#Country") && thisForm.find("#Country").val() && thisForm.find("#Country").val() != '') {
        if (index == 0) location += "?"; else location += "&";
        if (index != 0) gaLabel += '-';
        gaLabel += 'country';
        location += "country=" + thisForm.find("#Country").val();
        index++;
    }
    if (thisForm.find("#State") && thisForm.find("#State").val() && thisForm.find("#State").val() != '') {
        if (index == 0) location += "?"; else location += "&";
        if (index != 0) gaLabel += '-';
        gaLabel += 'state';
        location += "state=" + thisForm.find("#State").val();
        index++;
    }
    if (thisForm.find("#DobYYYY") && thisForm.find("#DobYYYY").val() && thisForm.find("#DobYYYY").val() != '')
    {
        if (index == 0) location += "?"; else location += "&";
        if (index != 0) gaLabel += '-';
        gaLabel += 'dobyyyy';
        location += "dobyyyy=" + thisForm.find("#DobYYYY").val();
        index++;
    }
    if (thisForm.find("#DodYYYY") && thisForm.find("#DodYYYY").val() && thisForm.find("#DodYYYY").val() != '') {
        if (index == 0) location += "?"; else location += "&";
        if (index != 0) gaLabel += '-';
        gaLabel += 'dodyyyy';
        location += "dodyyyy=" + thisForm.find("#DodYYYY").val();
        index++;
    }
    if (thisForm.find("#DodMM") && thisForm.find("#DodMM").val() && thisForm.find("#DodMM").val() != '') {
        if (index == 0) location += "?"; else location += "&";
        if (index != 0) gaLabel += '-';
        gaLabel += 'dodmm';
        location += "dodmm=" + thisForm.find("#DodMM").val();
        index++;
    }
    if (thisForm.find("#DodDD") && thisForm.find("#DodDD").val() && thisForm.find("#DodDD").val() != '') {
        if (index == 0) location += "?"; else location += "&";
        if (index != 0) gaLabel += '-';
        gaLabel += 'doddd';
        location += "doddd=" + thisForm.find("#DodDD").val();
        index++;
    }
    
    if (thisForm.find("#Relative") && thisForm.find("#Relative").val() && thisForm.find("#Relative").val() != '') {
        if (index == 0) location += "?"; else location += "&";
        if (index != 0) gaLabel += '-';
        gaLabel += 'relative';
        location += "relative=" + thisForm.find("#Relative").val();
        index++;
    }
    if (thisForm.find("#PhoneNo") && thisForm.find("#PhoneNo").val() && thisForm.find("#PhoneNo").val() != '') {
        if (index == 0) location += "?"; else location += "&";
        if (index != 0) gaLabel += '-';
        gaLabel += 'phone';
        location += "phoneno=" + thisForm.find("#PhoneNo").val().replace(/ /g, "");
        index++;
    }

    //send event to ga
    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'search-summary', 'submit', gaLabel);
    }
    
    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Macintosh/i.test(navigator.userAgent))  //spinner won't show unless we have a small delay for safari and mobile
        setTimeout(function () { document.location = location; }, 50);
    else
        document.location = location;

    event.preventDefault();
}));

function getSearchTypeFromUrl(url)
{
    var searchType = 'all';
    if (url.indexOf("/census") > -1) searchType = "census";
    else if (url.indexOf("/birth") > -1) searchType = "birth";
    else if (url.indexOf("/death") > -1) searchType = "death";
    else if (url.indexOf("/obituaries") > -1) searchType = "obituaries";
    else if (url.indexOf("/marriage") > -1) searchType = "marriage";
    else if (url.indexOf("/divorce") > -1) searchType = "divorce";
    else if (url.indexOf("phoneno=") > -1) searchType = "people-phone";
    else if (url.indexOf("streetaddress=") > -1) searchType = "people-address";
    else if (url.indexOf("/people") > -1) searchType = "people";
    else if (url.indexOf("/world-war-2-personnel") > -1) searchType = "world-war-2-personnel";
    else if (url.indexOf("/japanese-internment") > -1) searchType = "japanese-internment";
    else if (url.indexOf("/property") > -1) searchType = "property";
    else if (url.indexOf("/trees") > -1) searchType = "trees";

    return searchType;
}

//log detail clicks to ga
//$($("[data-target='#detailModal']").click(function (event) {
//    if (typeof ga !== 'undefined') {
//        var label = getSearchTypeFromUrl($(this).attr("href").valueOf());
//        ga('send', 'event', 'search-detail', 'click', label);

//        //log event as page view too since ga won't count it as a page view, even though it really is
//        ga('send', 'pageview', $(this).attr("href").valueOf());
//    }
//}));

$($(".filter-link").click(function (event) {
    if (typeof ga !== 'undefined') {
        var label = getSearchTypeFromUrl($(this).attr("href").valueOf());
        ga('send', 'event', 'search-filter', 'click', label);
    }
}));

$($(".detail-link").click(function (event) {
    if($(this).hasClass("btn"))
        $(this).html("View Details &nbsp;<i class='fa fa-lg fa-spinner fa-spin'></i>");
    else
        $(this).html($(this).html() + " <i class='fa fa-lg fa-spinner fa-spin'></i>");
    if (typeof ga !== 'undefined') {
        var label = getSearchTypeFromUrl($(this).attr("href").valueOf());
        ga('send', 'event', 'search-detail', 'click', label);
    }
}));

$($("#btnNextPage").click(function (event) {
    if (navigator.userAgent.indexOf("MSIE ") == -1 && navigator.userAgent.toLowerCase().indexOf("trident") == -1) $(this).html("<i class='fa fa-lg fa-spinner fa-spin'></i>");
    if (typeof ga !== 'undefined') {
        var label = getSearchTypeFromUrl($(this).attr("href").valueOf());
        ga('send', 'event', 'search-paging-next', 'click', label);
    }
}));

$($("#btnFirstPage").click(function (event) {
    if (navigator.userAgent.indexOf("MSIE ") == -1 && navigator.userAgent.toLowerCase().indexOf("trident") == -1) $(this).html("<i class='fa fa-lg fa-spinner fa-spin'></i>");
    if (typeof ga !== 'undefined') {
        var label = getSearchTypeFromUrl($(this).attr("href").valueOf());
        ga('send', 'event', 'search-paging-first', 'click', label);
    }
}));

//for mobile navbar, we have modify and filter buttons that show/hide the boxes

var editShown = false;
$($("#mobileEditCriteria").click(function () {
    $('#sidebar').removeClass('hidden-xs');
    toggleEditCriteria();
    if (editShown) {
        $('#modifyCriteria').hide();
        $('#sidebar').hide();
        editShown = false;
    }
    else {
        $('#modifyCriteria').show();
        $('#sidebar').show();
        $('#filterResults').hide();
        filterShown = false;
        editShown = true;
    }
    window.scrollTo(0, 0);
}));

var filterShown = false;
$($("#mobileFilterResults").click(function () {
    $('#sidebar').removeClass('hidden-xs');
    if (filterShown) {
        $('#filterResults').hide();
        $('#sidebar').hide();
        filterShown = false;
    }
    else {
        $('#filterResults').show();
        $('#sidebar').show();
        $('#modifyCriteria').hide();
        if (editShown) {
            editShown = false;
            toggleEditCriteria();
        }
        filterShown = true;
    }
    window.scrollTo(0, 0);
}));

$($(".share-link").click(function (event) {
    if ($(this).attr("href").indexOf("mailto:") == -1) window.open($(this).attr("href"), "share", "width=500,height=375,scrollbars=no,status=no,menubar=no");
    if (typeof ga !== 'undefined') {
        var title = 'unknown';
        if ($(this).attr("title")) {
            title = $(this).attr("title").valueOf().toLowerCase().replace(" ", "-");            
        }
        ga('send', 'event', 'share-link', 'click', title);
    }
    if ($(this).attr("href").indexOf("mailto:") == -1) event.preventDefault();
}));

$($(".share-link-record").click(function (event) {

    //create permalink
    $.ajax({
        url: appendParameterToUrl(window.location, 'createpermalink', 'true')
    });

    if ($(this).attr("data-target").indexOf("mailto:") == -1) window.open($(this).attr("data-target"), "share", "width=500,height=375,scrollbars=no,status=no,menubar=no");
    if (typeof ga !== 'undefined') {
        var title = 'unknown';
        if ($(this).attr("title")) {
            title = $(this).attr("title").valueOf().toLowerCase().replace(" ", "-");
        }
        ga('send', 'event', 'share-link-record', 'click', title);
    }
    if ($(this).attr("href").indexOf("mailto:") == -1) event.preventDefault();
}));

//var calcHtml = "<span>Was about <input class='form-control' type='number' id='calculatorAge' width='10' size='4' placeholder='Age' /> years old in <input class='form-control' type='number' id='calculatorYear' width='10' size='4' placeholder='Year' /> <a href='#' class='btn btn-sm btn-success center-block' id='calculatorCalculate'>Calculate</a></span>";
//$($("#btnCalculator").popover({
//    animation: true, html: true, content: calcHtml
//}).parent().delegate('a#calculatorCalculate', 'click', function () {
//    if ($("#calculatorAge").val() != "" && $("#calculatorYear").val() != "") {
//        try {
//            var age = $("#calculatorAge").val();
//            var year = $("#calculatorYear").val();
//            var birthYear = year - age;
//            if(!isNaN(birthYear)) $("#DobYYYY").val(birthYear);
//        }
//        catch (e) { }
//    }
//    $("#btnCalculator").popover("hide");
//})
//);

//$($("#btnCalculator").click(function (event) {
//    if (typeof ga !== 'undefined') {
//        ga('send', 'event', 'calculator', 'click', 'buttons');
//    }
//    event.preventDefault();
//}));

$($("body").on("click", "#btnPrint", function (event) {
    $(this).html("<i class='fa fa-spinner fa-spin'></i>");
    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'printer-friendly', 'click', getSearchTypeFromUrl($(this).attr("href").valueOf()));
    }
}));

$($("body").on("click", "#btnRelated", function (event) {
    $(this).html("<i class='fa fa-spinner fa-spin'></i>");
    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'search-related', 'click', getSearchTypeFromUrl($(this).attr("href").valueOf()));
    }
}));

$($("body").on("click", ".search-hints", function (event) {
    $(this).html("<i class='fa fa-spinner fa-spin'></i>");
    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'search-hints', 'click', getSearchTypeFromUrl($(this).attr("href").valueOf()));
    }
}));
$($("body").on("click", ".search-hints-button", function (event) {
    $(this).html("<i class='fa fa-spinner fa-spin'></i>");
    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'search-hints-button', 'click', getSearchTypeFromUrl($(this).attr("href").valueOf()));
    }
}));

$($("body").on("click", ".linked-record", function (event) {
    $(this).html($(this).html() + " " + "<i class='fa fa-spinner fa-spin'></i>");
    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'search-linked', 'click', getSearchTypeFromUrl($(this).attr("href").valueOf()));
    }
}));

$($("body").on("click", ".maps-link", function (event) {
    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'maps-link', 'click', getSearchTypeFromUrl($(this).attr("href").valueOf()));
    }
}));

$($("[data-target='adredirect']").click(function (event) {
    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'ad-link', 'click', $(this).attr("data-ad-advertiser"));
    }
}));

$($("body").on("click", "#censusImageLink", function (event) {
    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'record-image', 'click', 'census');

        //log event as page view too since ga won't count it as a page view, even though it really is
        ga('send', 'pageview', $(this).attr("href").valueOf());
    }
}));

$($("body").on("click", "#btnSaveRecord", function (event) {
    var url = $(this).attr("href").valueOf();
    var button = $(this);
    button.html("<i class='fa fa-spinner fa-spin'></i>");
    $.ajax({
        url: url,
        success: function(text) {
            if (text == "401") window.location = "/myaccount/register?returnUrl=" + encodeURIComponent(appendParameterToUrl(window.location.pathname + window.location.search, "showsidecount", "true"))
            else {
                button.html("<i class='fa fa-check'></i>");
                button.addClass("disabled");
            }
        }
    });

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'save-record', 'click', getSearchTypeFromUrl($(this).attr("href").valueOf()));
    }

    event.preventDefault();
}));

$($(".delete-link").click(function (event) {
    var oldHtml = $(this).html();
    $(this).html("<i class='fa fa-spinner fa-spin'></i>");
    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'delete-link', 'click', 'buttons');
    }
    if (!confirm("Confirm delete?")) {
        event.preventDefault();
        $(this).html(oldHtml);
    }
}));

$($(".link-to-form").click(function (event) {
    $(this).html("click search button above <i class='fa fa-arrow-up'></i>");
    $(this).css("color", "black");
    $(this).css("text-decoration", "none");
    $(this).css("cursor", "default");

    $("#divCity").addClass("hidden");
    $("#City").val("");
    $("#First").val($(this).data("first"));
    $("#Middle").val($(this).data("middle"));
    if ($("#Middle").val() != "") $("#divMiddle").removeClass("hidden"); else $("#divMiddle").addClass("hidden");
    $("#Last").val($(this).data("last"));
    $("#State").val("");

    $("#divFormHeader").text($(this).data("first") + " " + $(this).data("last") + " - See All Records Free!");

    window.scrollTo(0, 0);

    $("#searchButton").removeClass("btn-warning");
    $("#searchButton").addClass("btn-success");
    $("#searchButton").html('Search Now &nbsp;<i class="fa fa-arrow-right"></i>');

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'simulated-link', 'click', 'buttons');
    }
}));

$($(".search-records-modal").click(function (event) {
    var modal = $("#searchRecordsModal");
  
    modal.find("#First").val($(this).data("first"));
    modal.find("#Middle").val($(this).data("middle"));
    modal.find("#Last").val($(this).data("last"));
    modal.find("#City").val($(this).data("city"));
    modal.find("#State").val($(this).data("state"));
    
    if (modal.find("#City").val() == '') modal.find("#divCity").css("display", "none");
    if (modal.find("#State").val() == '') modal.find("#divState").css("display", "none");
    //modal.find("#State").val($(this).data("state"));
    //modal.find("#DobYYYY").val($(this).data("dobyyyy"));
    //if (modal.find("#DobYYYY").val() == "") modal.find("#divDobYYYY").addClass("hidden");

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'search-records-modal', 'click', 'buttons');
    }
}));

$($(".perma-link-textbox").click(function (event) {
    $(this).select();

    //create permalink
    $.ajax({
        url: appendParameterToUrl(window.location.toString(), 'createpermalink', 'true')
    });

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'perma-link', 'click', 'textbox');
    }
}));

$($(".oo-link").click(function (event) {
    //create permalink
    $.ajax({
        url: appendParameterToUrl(window.location.toString(), 'createpermalink', 'true')
    });
}));


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Family Tree Methods
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//this is used for after user creates account that sends to tree creation; we will auto-show the add relative
//modal when they reach the tree page to encourage adding more people; if user cancels out and then tries to 
//add father/mother on a different person, when that succeeds we don't want to still auto-open add relative
//modal because they are really on a different person now, would be confusing
var fromRelativeModal = false;

$($("body").on("click", "#treeSettings", function (event) {
    var url = $(this).attr("href").valueOf();
    var button = $(this);
    var buttonHtml = button.html();
    button.html("<i class='fa fa-spinner fa-spin'></i>");
    $.ajax({
        cache: false,
        url: url,
        success: function (text) {
            if (text == "401") window.location = "/myaccount/login?returnUrl=" + encodeURIComponent(appendParameterToUrl(window.location.pathname + window.location.search, "showsidecount", "true"))
            else {
                button.html(buttonHtml);

                //open modal
                $("#treeSettingsModal").find(".modal-content").html(text);
                $("#treeSettingsModal").modal('show');
            }
        }
    });

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'tree-settings', 'click', '');
    }

    event.preventDefault();
}));

$($("body").on("click", ".person-source", function (event) {
    var url = $(this).attr("href").valueOf();
    var button = $(this);
    var buttonHtml = button.html();
    button.html("<i class='fa fa-spinner fa-spin'></i>");
    $.ajax({
        cache: false,
        url: url,
        success: function (text) {
            if (text == "401") window.location = "/myaccount/register?returnUrl=" + encodeURIComponent(appendParameterToUrl(window.location.pathname + window.location.search, "showsidecount", "true"))
            else {
                button.html(buttonHtml);

                //open modal
                $("#personSourceModal").find(".modal-content").html(text);
                $("#personSourceModal").modal('show');
            }
        }
    });

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'person-source', 'click', '');
    }

    event.preventDefault();
}));

$($("body").on("click", "#addRelative", function (event) {
    var url = $(this).attr("href").valueOf();
    var button = $(this);
    var buttonHtml = button.html();
    button.html("<i class='fa fa-spinner fa-spin'></i>");
    $.ajax({
        cache: false,
        url: url,
        success: function (text) {
            if (text == "401") window.location = "/myaccount/login?returnUrl=" + encodeURIComponent(appendParameterToUrl(window.location.pathname + window.location.search, "showsidecount", "true"))
            else {
                button.html(buttonHtml);

                //open modal
                $("#treeAddRelativeModal").find(".modal-content").html(text);
                $("#treeAddRelativeModal").modal('show');
            }
        }
    });

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'tree-add-relative', 'click', '');
    }

    event.preventDefault();
}));

$($("body").on("click", ".save-record-tree-input", function (event) {
    var url = $(this).attr("href").valueOf();
    var button = $(this);
    var buttonHtml = button.html();
    button.html("<i class='fa fa-spinner fa-spin'></i>");
    $.ajax({
        cache: false,
        url: url,
        success: function (text) {
            if (text == "401") window.location = "/myaccount/login?returnUrl=" + encodeURIComponent(appendParameterToUrl(window.location.pathname + window.location.search, "showsidecount", "true"))
            else if (text == "402") button.html("Error");
            else {
                button.html(buttonHtml);

                //open modal
                if ($("#treeAddRelativeModal") && $("#treeAddRelativeModal").length && $("#treeAddRelativeModal").data("bs.modal") && $("#treeAddRelativeModal").data("bs.modal").isShown) {
                    $("#treeAddRelativeModal").modal('hide');
                    fromRelativeModal = true;
                }
                $("#treeNewPersonModal").find(".modal-content").html(text);
                $("#treeNewPersonModal").modal('show');

                //if any extra info fields have values then show extra info section
                if (($("#treeNewPersonModal").find("#Prefix").length && $("#treeNewPersonModal").find("#Prefix").val() != "")
                    || ($("#treeNewPersonModal").find("#NickName").length && $("#treeNewPersonModal").find("#NickName").val() != "")
                    || ($("#treeNewPersonModal").find("#Title").length && $("#treeNewPersonModal").find("#Title").val() != "")
                    || ($("#treeNewPersonModal").find("#MarriedName").length && $("#treeNewPersonModal").find("#MarriedName").val() != "")
                    ) {
                    $("#addExtraInfo").hide();

                    $("#extraInfo").removeClass("hidden");
                }
                $("#treeNewPersonModal").find(".typeahead-lastname").autocomplete({
                    serviceUrl: '/results/autocompletelastname',
                    paramName: 'lastname',
                    minChars: 2,
                    autoSelectFirst: true,
                    showNoSuggestionNotice: false
                });

                $("#treeNewPersonModal").find(".typeahead-firstname").autocomplete({
                    serviceUrl: '/results/autocompletefirstname',
                    paramName: 'firstname',
                    minChars: 2,
                    autoSelectFirst: true,
                    showNoSuggestionNotice: false
                });
                //setAutoCompleteFields(text);
            }
        }
    });

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'save-record-tree-input', 'click', getSearchTypeFromUrl($(this).attr("href").valueOf()));
    }

    event.preventDefault();
}));

$($("body").on("click", "#btnDeleteTree", function (event) {
    var errorMessage = "", validationMessage = "";
    var url = "/trees/tree/delete?1=1";
    var button = $(this);
    var buttonHtml = button.html();
    button.html("<i class='fa fa-spinner fa-spin'></i>");

    var modal = $("#treeSettingsModal");

    if (!confirm("Confirm delete this tree and all people in it? This CANNOT be undone.")) {
        event.preventDefault();
        $(button).html(buttonHtml);
        return;
    }

    //set all input variables
    url += "&FamilyTreeId=" + modal.find("#FamilyTreeId").val();
    
    //alert(url);
    $.ajax({
        url: url,
        success: function (text) {
            if (text == "401") window.location = "/myaccount/register?returnUrl=" + encodeURIComponent(appendParameterToUrl(window.location.pathname + window.location.search, "showsidecount", "true"));    //ajax only, after login will have to go to search results/tree page
            else if (text == "402" || text == "426") errorMessage = "There has been an error, please try again.";
            else if (text == "420") errorMessage = "No User found.";
            else if (text == "432") errorMessage = "This tree is being shared. You must remove all shared people before you can delete this tree. All of their contributions will be deleted which might not be a very nice thing to do. Keep that in mind.";
            else {
                //go to tree page
                location = "/trees";
            }

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        },
        error: function (text) {
            errorMessage = "There has been an error, please try again.";

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        }
    });

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'delete-tree', 'click', getSearchTypeFromUrl($(this).attr("href").valueOf()));
    }

    event.preventDefault();
}));

$($("body").on("click", ".delete-person-source", function (event) {
    var errorMessage = "", validationMessage = "";
    var url = $(this).attr("href").valueOf();
    var button = $(this);
    var buttonHtml = button.html();
    button.html("<i class='fa fa-spinner fa-spin'></i>");

    var modal = $("#personSourceModal");

    if (!confirm("Confirm delete this source?")) {
        event.preventDefault();
        $(button).html(buttonHtml);
        return;
    }

    //alert(url);
    $.ajax({
        url: url,
        success: function (text) {
            if (text == "401") window.location = "/myaccount/register?returnUrl=" + encodeURIComponent(appendParameterToUrl(window.location.pathname + window.location.search, "showsidecount", "true"));    //ajax only, after login will have to go to search results/tree page
            else if (text == "402" || text == "426") errorMessage = "There has been an error, please try again.";
            else {
                reloadTree(window.location);
            }

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        },
        error: function (text) {
            errorMessage = "There has been an error, please try again.";

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        }
    });

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'person-source-delete', 'click', getSearchTypeFromUrl($(this).attr("href").valueOf()));
    }

    event.preventDefault();
}));

$($("body").on("click", "#btnDeletePerson", function (event) {
    var errorMessage = "", validationMessage = "";
    var url = "/trees/person/delete?1=1";
    var button = $(this);
    var buttonHtml = button.html();
    button.html("<i class='fa fa-spinner fa-spin'></i>");

    var modal = $("#treeNewPersonModal");

    if (!confirm("Confirm delete this person?")) {
        event.preventDefault();
        $(button).html(buttonHtml);
        return;
    }

    //set all input variables
    url += "&personId=" + modal.find("#PersonId").val();

    //alert(url);
    $.ajax({
        url: url,
        success: function (text) {
            if (text == "401") window.location = "/myaccount/register?returnUrl=" + encodeURIComponent(appendParameterToUrl(window.location.pathname + window.location.search, "showsidecount", "true"));    //ajax only, after login will have to go to search results/tree page
            else if (text == "402" || text == "426") errorMessage = "There has been an error, please try again.";
            else if (text == "420") errorMessage = "No User found.";
            else {
                //go to tree page
                location = "/trees/" + modal.find("#FamilyTreeId").val();
            }

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        },
        error: function (text) {
            errorMessage = "There has been an error, please try again.";

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        }
    });

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'delete-person', 'click', getSearchTypeFromUrl($(this).attr("href").valueOf()));
    }

    event.preventDefault();
}));

$($("body").on("click", "#btnSetFocusPersonId", function (event) {
    var errorMessage = "", validationMessage = "";
    var url = "/trees/tree/save?1=1";
    var button = $(this);
    var buttonHtml = button.html();
    button.html("<i class='fa fa-spinner fa-spin'></i>");

    var modal = $("#treeNewPersonModal");

    //set all input variables
    url += "&FamilyTreeId=" + modal.find("#FamilyTreeId").val();
    url += "&FocusPersonId=" + modal.find("#PersonId").val();

    //alert(url);
    $.ajax({
        type: "POST",
        url: url,
        success: function (text) {
            if (text == "401") window.location = "/myaccount/register?returnUrl=" + encodeURIComponent(appendParameterToUrl(window.location.pathname + window.location.search, "showsidecount", "true"));    //ajax only, after login will have to go to search results/tree page
            else if (text == "402" || text == "426") errorMessage = "There has been an error, please try again.";
            else if (text == "420") errorMessage = "No User found.";
            else {
                //close modal
                modal.modal('hide');
            }

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        },
        error: function (text) {
            errorMessage = "There has been an error, please try again.";

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        }
    });

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'tree-set-focus-personid', 'click', getSearchTypeFromUrl($(this).attr("href").valueOf()));
    }

    event.preventDefault();
}));

$($("body").on("click", "#btnSaveTreeSettings", function (event) {
    var errorMessage = "", validationMessage = "";
    var url = "/trees/tree/save?1=1";
    var button = $(this);
    var buttonHtml = button.html();
    button.html("<i class='fa fa-spinner fa-spin'></i>");

    var modal = $("#treeSettingsModal");

    //validate input
    if ($("#PrivacyTypeId").val() == "" || $("#PrivacyTypeId").val() == null) {
        validationMessage += "Please select privacy setting<br/>";
        $("#PrivacyTypeId").addClass("validation-error");
    }
    if ($("#Name").val() == "" || $("#Name").val() == null) {
        validationMessage += "Please enter a tree name<br/>";
        $("#Name").addClass("validation-error");
    }

    if (validationMessage != "") {
        button.html(buttonHtml);
        modal.find("#errorMessage").html(validationMessage);
        modal.find("#errorMessage").removeClass("hidden");
        event.preventDefault();
        return;
    }
    else {
        modal.find("#errorMessage").addClass("hidden");
        $("#Name").removeClass("validation-error");
        $("#PrivacyTypeId").removeClass("validation-error");
    }

    //set all input variables
    url += "&FamilyTreeId=" + modal.find("#FamilyTreeId").val();
    url += "&Name=" + encodeURIComponent(modal.find("#Name").val().replace(/</g, "[").replace(/>/g, "]"));
    url += "&PrivacyTypeId=" + modal.find("#PrivacyTypeId").val();
    url += "&Description=" + encodeURIComponent(modal.find("#Description").val());
    
    //alert(url);
    $.ajax({
        type: "POST",
        url: url,
        success: function (text) {
            if (text == "401") window.location = "/myaccount/register?returnUrl=" + encodeURIComponent(appendParameterToUrl(window.location.pathname + window.location.search, "showsidecount", "true"));    //ajax only, after login will have to go to search results/tree page
            else if (text == "402" || text == "426") errorMessage = "There has been an error, please try again.";
            else if (text == "404") errorMessage = "Some of your input is invalid.";
            else if (text == "420") errorMessage = "No User found.";
            else {
                //close modal
                modal.modal('hide');

                //if on tree page need to refresh tree
                reloadTree(window.location);//location = location;
            }

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        },
        error: function (text) {
            errorMessage = "There has been an error, please try again.";

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        }
    });

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'save-tree-settings', 'click', '');
    }

    event.preventDefault();
}));

$($("body").on("click", "#btnShareTree", function (event) {
    var errorMessage = "", validationMessage = "";
    var url = "/trees/tree/share?1=1";
    var button = $(this);
    var buttonHtml = button.html();
    button.html("<i class='fa fa-spinner fa-spin'></i>");

    var modal = $("#treeShareModal");

    //validate input
    if (modal.find("#RoleTypeId").val() == "" || modal.find("#RoleTypeId").val() == null) {
        validationMessage += "Please select role<br/>";
        modal.find("#RoleTypeId").addClass("validation-error");
    }
    if (modal.find("#Email").val() == "" || modal.find("#Email").val() == null) {
        validationMessage += "Please enter a valid email address<br/>";
        modal.find("#Email").addClass("validation-error");
    }

    if (validationMessage != "") {
        button.html(buttonHtml);
        modal.find("#errorMessage").html(validationMessage);
        modal.find("#errorMessage").removeClass("hidden");
        event.preventDefault();
        return;
    }
    else {
        modal.find("#errorMessage").addClass("hidden");
        modal.find("#Name").removeClass("validation-error");
        modal.find("#PrivacyTypeId").removeClass("validation-error");
    }

    //set all input variables
    url += "&FamilyTreeId=" + modal.find("#FamilyTreeId").val();
    url += "&FocusPersonId=" + modal.find("#FocusPersonId").val();
    url += "&Email=" + encodeURIComponent(modal.find("#Email").val());
    url += "&RoleTypeId=" + modal.find("#RoleTypeId").val();

    //alert(url);
    $.ajax({
        type: "POST",
        url: url,
        success: function (text) {
            if (text == "401") window.location = "/myaccount/register?returnUrl=" + encodeURIComponent(appendParameterToUrl(window.location.pathname + window.location.search, "showsidecount", "true"));    //ajax only, after login will have to go to search results/tree page
            else if (text == "402" || text == "426") errorMessage = "There has been an error, please try again.";
            else if (text == "404") errorMessage = "Some of your input is invalid.  Make sure email was entered correctly.";
            else if (text == "420") errorMessage = "No User found.";
            else {
                button.html(buttonHtml);

                //close modal
                modal.modal('hide');
            }

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        },
        error: function (text) {
            errorMessage = "There has been an error, please try again.";

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        }
    });

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'share-tree', 'click', '');
    }

    event.preventDefault();
}));

$($("body").on("click", "#btnUpdateSource", function (event) {
    var errorMessage = "", validationMessage = "";
    var url = "/trees/person/sources/save";
    var button = $(this);
    var buttonHtml = button.html();
    button.html("<i class='fa fa-spinner fa-spin'></i>");

    var modal = $("#personSourceModal");

    //validate input
    if (modal.find("#Name").val() == "" || modal.find("#Name").val() == null) {
        validationMessage += "Please enter a name for the source<br/>";
        modal.find("#Name").addClass("validation-error");
    }
    if ((modal.find("#Description").val() == "" || modal.find("#Description").val() == null)
        && (modal.find("#Url").val() == "" || modal.find("#Url").val() == null)) {
        validationMessage += "Please enter either a description or a web address linking to source<br/>";
        modal.find("#Description").addClass("validation-error");
        modal.find("#Url").addClass("validation-error");
    }

    if (validationMessage != "") {
        button.html(buttonHtml);
        modal.find("#errorMessage").html(validationMessage);
        modal.find("#errorMessage").removeClass("hidden");
        event.preventDefault();
        return;
    }
    else {
        modal.find("#errorMessage").addClass("hidden");
        modal.find("#Name").removeClass("validation-error");
        modal.find("#Description").removeClass("validation-error");
        modal.find("#Url").removeClass("validation-error");
    }

    //set all input variables
    var data = new FormData();
    var files = modal.find("#File").get(0).files;

    // Add the uploaded image content to the form data collection
    if (files.length > 0) {
        data.append("file", files[0]);
    }
    data.append("PersonId", modal.find("#PersonId").val());
    data.append("SourceId", modal.find("#SourceId").val());
    data.append("Name", modal.find("#Name").val());
    data.append("Description", modal.find("#Description").val());
    data.append("Url", modal.find("#Url").val());

    //url += "&PersonId=" + modal.find("#PersonId").val();
    //url += "&SourceId=" + modal.find("#SourceId").val();
    //url += "&Name=" + encodeURIComponent(modal.find("#Name").val());
    //url += "&Description=" + encodeURIComponent(modal.find("#Description").val());
    //url += "&Url=" + encodeURIComponent(modal.find("#Url").val());

    //alert(url);
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        processData: false,
        contentType: false,
        success: function (text) {
            if (text == "401") window.location = "/myaccount/register?returnUrl=" + encodeURIComponent(appendParameterToUrl(window.location.pathname + window.location.search, "showsidecount", "true"));    //ajax only, after login will have to go to search results/tree page
            else if (text == "402" || text == "426") errorMessage = "There has been an error, please try again.";
            else if (text == "404") errorMessage = "Some of your input is invalid.  Make sure email was entered correctly.";
            else if (text == "420") errorMessage = "No User found.";
            else if (text == "433") errorMessage = "Maximum number of sources for this person has been reached.";
            else if (text == "435") errorMessage = "That URL appears to be invalid. It should look something like 'http://www.something.com/content'.";
            else {
                button.html("<i class='fa fa-check'></i>");

                //close modal
                modal.modal('hide');

                reloadTree(window.location);
            }

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        },
        error: function (text) {
            errorMessage = "There has been an error, please try again.";

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        }
    });

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'person-source-save', 'click', '');
    }

    event.preventDefault();
}));

$($("body").on("click", "#btnAddNewPerson", function (event) {

    var modal = $("#treeNewPersonModal");

    modal.find("#divAddNewPerson").addClass("hidden");
    modal.find("#divPersonDetails").removeClass("hidden");
    
    event.preventDefault();
}));

$($("body").on("click", ".save-record-tree", function (event) {
    var errorMessage = "", validationMessage = "";
    var url = "/trees/person/save";
    var postData = "1=1";
    var button = $(this);
    var buttonHtml = button.html();
    var familyTreeName = "", myFirstName = "", myLastName = "";
    button.html("<i class='fa fa-spinner fa-spin'></i>");

    var modal = $(this).parents(".modal");

    //if attaching source record to existing person in tree send to different url
    if (modal.find("#SourceViewModel_Name") && modal.find("#SourceViewModel_Name").val() && modal.find("#SourceViewModel_Name").val() != ""
     && modal.find("#drpRecentPersonId") && modal.find("#drpRecentPersonId").val() && modal.find("#drpRecentPersonId").val() != "")
    {
        var url = "/trees/person/sources/save";
    }

    //validate input
    if ($(modal).attr("id").valueOf() != "bioModal") {
        if (!modal.find("#drpRecentPersonId").length || modal.find("#drpRecentPersonId").val() == "") {
            if (!modal.find("#MiddleName").length) { //if no middle name field then means we are showing tree create/account create form
                if (modal.find("#FirstName").val() == "" || modal.find("#LastName").val() == "") {
                    validationMessage += "Please enter your first and last name<br/>";
                    modal.find("#FirstName").addClass("validation-error");
                    modal.find("#LastName").addClass("validation-error");
                }
                else {
                    myFirstName = modal.find("#FirstName").val();
                    myLastName = modal.find("#LastName").val();
                }
            }
            else {
                if (modal.find("#FirstName").val() == "" && modal.find("#LastName").val() == "") {
                    validationMessage += "Must enter at least first or last name<br/>";
                    modal.find("#FirstName").addClass("validation-error");
                    modal.find("#LastName").addClass("validation-error");
                }
            }
            if ($("#GenderTypeId").val() == "" || $("#GenderTypeId").val() == null) {
                validationMessage += "Please select gender<br/>";
                $("#GenderTypeId").addClass("validation-error");
            }
            if ($("#Living").val() == "" || $("#Living").val() == null) {
                validationMessage += "Please select status (living/deceased)<br/>";
                $("#Living").addClass("validation-error");
            }
            if (!$("#FamilyTreeId").length && ($("#drpFamilyTreeId").val() == "" || $("#drpFamilyTreeId").val() == null || $("#drpFamilyTreeId").val() == "-1") && ($("#FamilyTreeName").val() == "" || $("#FamilyTreeName").val() == null)) {
                //create family tree name based on last or first name
                if ($("#LastName").val() != "") familyTreeName = $("#LastName").val() + " Family Tree";
                else if ($("#FirstName").val() != "") familyTreeName = $("#FirstName").val() + " Family Tree";

                //validationMessage += "Please enter a new family tree name<br/>";
                //$("#FamilyTreeName").addClass("validation-error");
            }
            else if ($("#FamilyTreeName").length) familyTreeName = $("#FamilyTreeName").val();
        }
        if ($("#PossibleParents1").length && !$("#divPossibleParents1").hasClass("hidden") && ($("#PossibleParents1").val() == "" || $("#PossibleParents1").val() == null)) {
            validationMessage += "Please select parent(s)<br/>";
            $("#PossibleParents1").addClass("validation-error");
        }
        if ($("#PossibleParents2").length && !$("#divPossibleParents2").hasClass("hidden") && ($("#PossibleParents2").val() == "" || $("#PossibleParents2").val() == null)) {
            validationMessage += "Please select parent(s)<br/>";
            $("#PossibleParents2").addClass("validation-error");
        }

        if (validationMessage != "") {
            button.html(buttonHtml);
            modal.find("#errorMessage").html(validationMessage);
            modal.find("#errorMessage").removeClass("hidden");
            modal.find("#divAddNewPerson").addClass("hidden");
            modal.find("#divPersonDetails").removeClass("hidden");
            event.preventDefault();
            return;
        }
        else {
            modal.find("#errorMessage").addClass("hidden");
            $("#FirstName").removeClass("validation-error");
            $("#LastName").removeClass("validation-error");
            $("#GenderTypeId").removeClass("validation-error");
            $("#Living").removeClass("validation-error");
            $("#FamilyTreeName").removeClass("validation-error");
        }
    }
    
    //set all input variables
    if (modal.find("#PersonId") && modal.find("#PersonId").val() && modal.find("#PersonId").val() != "") postData += "&PersonId=" + modal.find("#PersonId").val();
    if (modal.find("#FamilyTreePersons_0__PersonId") && modal.find("#FamilyTreePersons_0__PersonId").val() && modal.find("#FamilyTreePersons_0__PersonId").val() != "") postData += "&PersonId=" + modal.find("#FamilyTreePersons_0__PersonId").val();
    if (modal.find("#SourceViewModel_Url") && modal.find("#SourceViewModel_Url").val() && modal.find("#SourceViewModel_Url").val() != "") postData += "&SourceViewModel.Url=" + modal.find("#SourceViewModel_Url").val();
    if (modal.find("#SourceViewModel_Name") && modal.find("#SourceViewModel_Name").val() && modal.find("#SourceViewModel_Name").val() != "") postData += "&SourceViewModel.Name=" + modal.find("#SourceViewModel_Name").val();
    if (modal.find("#SourceViewModel_ArchiveHashKey") && modal.find("#SourceViewModel_ArchiveHashKey").val() && modal.find("#SourceViewModel_ArchiveHashKey").val() != "") postData += "&SourceViewModel.ArchiveHashKey=" + modal.find("#SourceViewModel_ArchiveHashKey").val();
    if (familyTreeName != "") postData += "&FamilyTreeName=" + encodeURIComponent(familyTreeName.replace(/</g, "[").replace(/>/g, "]"));
    if (modal.find("#drpFamilyTreeId") && modal.find("#drpFamilyTreeId").length && modal.find("#drpFamilyTreeId").val() != "" && modal.find("#drpFamilyTreeId").val() != "-1") postData += "&FamilyTreeId=" + modal.find("#drpFamilyTreeId").val();
    if (modal.find("#FamilyTreeId") && modal.find("#FamilyTreeId").length && modal.find("#FamilyTreeId").val() != "" && modal.find("#FamilyTreeId").val() != "-1") postData += "&FamilyTreeId=" + modal.find("#FamilyTreeId").val();
    if (modal.find("#FirstName") && modal.find("#FirstName").length) postData += "&FirstName=" + encodeURIComponent(modal.find("#FirstName").val());
    if (modal.find("#MiddleName") && modal.find("#MiddleName").length) postData += "&MiddleName=" + encodeURIComponent(modal.find("#MiddleName").val());
    if (modal.find("#LastName") && modal.find("#LastName").length) postData += "&LastName=" + encodeURIComponent(modal.find("#LastName").val());
    if (modal.find("#MarriedName") && modal.find("#MarriedName").length) postData += "&MarriedName=" + encodeURIComponent(modal.find("#MarriedName").val());
    if (modal.find("#Suffix") && modal.find("#Suffix").length) postData += "&Suffix=" + encodeURIComponent(modal.find("#Suffix").val());
    if (modal.find("#GenderTypeId") && modal.find("#GenderTypeId").length) postData += "&GenderTypeId=" + modal.find("#GenderTypeId").val();
    if (modal.find("#FamilyTreePersons_0__Living") && modal.find("#FamilyTreePersons_0__Living").length) postData += "&Living=" + modal.find("#FamilyTreePersons_0__Living").val();
    if (modal.find("#Living") && modal.find("#Living").length) postData += "&Living=" + modal.find("#Living").val();    
    if (modal.find("#BirthPlace") && modal.find("#BirthPlace").length) postData += "&BirthPlace=" + encodeURIComponent(modal.find("#BirthPlace").val());    
    if (modal.find("#DeathPlace") && modal.find("#DeathPlace").length) postData += "&DeathPlace=" + encodeURIComponent(modal.find("#DeathPlace").val());
    if (modal.find("#Email") && modal.find("#Email").length) postData += "&Email=" + encodeURIComponent(modal.find("#Email").val());
    if (modal.find("#InvitePerson") && modal.find("#InvitePerson").length) postData += "&InvitePerson=" + modal.find("#InvitePerson").is(':checked').toString();
    if (modal.find("#NickName") && modal.find("#NickName").length) postData += "&NickName=" + encodeURIComponent(modal.find("#NickName").val());
    if (modal.find("#Prefix") && modal.find("#Prefix").length) postData += "&Prefix=" + encodeURIComponent(modal.find("#Prefix").val());
    if (modal.find("#Title") && modal.find("#Title").length) postData += "&Title=" + encodeURIComponent(modal.find("#Title").val().replace(/</g, "[").replace(/>/g, "]"));
    if (modal.find("#FamilyTreePersons_0__Bio") && modal.find("#FamilyTreePersons_0__Bio").length) postData += "&Bio=" + encodeURIComponent(modal.find("#FamilyTreePersons_0__Bio").val().replace(/</g, "[").replace(/>/g, "]"));

    //for these if they are empty then set to 0, means we will set to null in db
    if (modal.find("#DobDay") && modal.find("#DobDay").length) postData += "&DobDay=0" + modal.find("#DobDay").val();
    if (modal.find("#DobMonth") && modal.find("#DobMonth").length) postData += "&DobMonth=0" + modal.find("#DobMonth").val();
    if (modal.find("#DobYear") && modal.find("#DobYear").length) postData += "&DobYear=0" + modal.find("#DobYear").val();
    if (modal.find("#DodDay") && modal.find("#DodDay").length) postData += "&DodDay=0" + modal.find("#DodDay").val();
    if (modal.find("#DodMonth") && modal.find("#DodMonth").length) postData += "&DodMonth=0" + modal.find("#DodMonth").val();
    if (modal.find("#DodYear") && modal.find("#DodYear").length) postData += "&DodYear=0" + modal.find("#DodYear").val();

    //if selected from existing list add
    if (modal.find("#drpRecentPersonId") && modal.find("#drpRecentPersonId").val() && modal.find("#drpRecentPersonId").val() != "" && modal.find("#drpRecentPersonId").val() != "-1") postData += "&recentPersonId=" + modal.find("#drpRecentPersonId").val();

    //relationships
    if (modal.find("#relationshipViewModel_PersonId") && modal.find("#relationshipViewModel_PersonId").val() && modal.find("#relationshipViewModel_PersonId").val() != "") postData += "&relationshipViewModel.PersonId=" + modal.find("#relationshipViewModel_PersonId").val();
    if (modal.find("#relationshipViewModel_RelationshipTypeId") && modal.find("#relationshipViewModel_RelationshipTypeId").val() && modal.find("#relationshipViewModel_RelationshipTypeId").val() != "") postData += "&relationshipViewModel.RelationshipTypeId=" + modal.find("#relationshipViewModel_RelationshipTypeId").val();

    if ($("#PossibleParents1").length && !$("#divPossibleParents1").hasClass("hidden"))
    {
        if (modal.find("#PossibleParents1") && modal.find("#PossibleParents1").val() && modal.find("#PossibleParents1").val() != "") postData += "&relationshipParentViewModel1.RelationshipPersonId=" + modal.find("#PossibleParents1").val();
        if (modal.find("#RelationshipTypeIdParent1") && modal.find("#RelationshipTypeIdParent1").val() && modal.find("#RelationshipTypeIdParent1").val() != "") postData += "&relationshipParentViewModel1.RelationshipTypeId=" + modal.find("#RelationshipTypeIdParent1").val();
    }

    if ($("#PossibleParents2").length && !$("#divPossibleParents2").hasClass("hidden"))
    {
        if (modal.find("#PossibleParents2") && modal.find("#PossibleParents2").val() && modal.find("#PossibleParents2").val() != "") postData += "&relationshipParentViewModel2.RelationshipPersonId=" + modal.find("#PossibleParents2").val();
        if (modal.find("#RelationshipTypeIdParent2") && modal.find("#RelationshipTypeIdParent2").val() && modal.find("#RelationshipTypeIdParent2").val() != "") postData += "&relationshipParentViewModel2.RelationshipTypeId=" + modal.find("#RelationshipTypeIdParent2").val(); if (modal.find("#relationshipViewModel_RelationshipTypeId") && modal.find("#relationshipViewModel_RelationshipTypeId").val() && modal.find("#relationshipViewModel_RelationshipTypeId").val() != "") postData += "&relationshipViewModel.RelationshipTypeId=" + modal.find("#relationshipViewModel_RelationshipTypeId").val();
    }

    //alert(url);
    $.ajax({
        type: "POST",
        url: url,
        data: postData,
        success: function (text) {
            if (text == "401") window.location = "/myaccount/register?FirstName=" + encodeURIComponent(myFirstName) + "&LastName=" + encodeURIComponent(myLastName) + "&returnUrl=" + encodeURIComponent(url + "?" + postData);    //after login will create tree/person and send to tree page
            else if (text == "402" || text == "426") errorMessage = "There has been an error, please try again.";
            else if (text == "404") errorMessage = "Some of your input is invalid.";
            else if (text == "420") errorMessage = "No User found.";
            else if (text == "428") errorMessage = "User already has a relationship with selected person.";
            else if (text == "423") {
                errorMessage = "You already have the maximum number of allowed trees. Please select an existing tree.";
                $("#divFamilyTreeDropDown").toggleClass("hidden");
                $("#divFamilyTreeName").toggleClass("hidden");
                $("#FamilyTreeName").val("");
            }
            else {
                //only log this event if adding a new person
                if (!modal.find("#PersonId") || !modal.find("#PersonId").val() || modal.find("#PersonId").val() == "") {
                    if (typeof ga !== 'undefined') {
                        var eventLabel = "";
                        if (document.URL.toLowerCase().indexOf("registersuccess=true") > -1) eventLabel = "from-account-creation";
                        ga('send', 'event', 'save-record-tree', 'click', eventLabel);
                    }
                }

                button.html("<i class='fa fa-check'></i>");
                if ($("#btnSaveRecordTreeInput")) $("#btnSaveRecordTreeInput").html("<i class='fa fa-check'></i>");
                if ($("#btnSaveRecordTreeInput")) $("#btnSaveRecordTreeInput").addClass("disabled");

                //close modal
                modal.modal('hide');

                //if on tree page need to refresh tree
                //!modal.find("#drpFamilyTreeId").val() || !$("#FamilyTreeId").length
                if (window.location.toString().toLowerCase().indexOf("/trees") != -1 && window.location.toString().toLowerCase().indexOf("search/trees") == -1) {
                    reloadTree(window.location); //location = location;

                    //if came from account creation page we want user to keep adding people, so just keep showing add relative modal
                    //until they click to another page
                    if (fromRelativeModal && document.URL.toLowerCase().indexOf("registersuccess=true") > -1
                        && (!modal.find("#PersonId") || !modal.find("#PersonId").val() || modal.find("#PersonId").val() == "")) {
                        $("#addRelative").trigger("click");
                    }
                    fromRelativeModal = false;  //reset, will only be set to true if user clicked new person from relative modal
                }
                else if (window.location.toString().toLowerCase().indexOf("/registersuccess") != -1) location = "/trees";
            }

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        },
        error: function (text) {
            errorMessage = "There has been an error, please try again.";

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        }
    });

    event.preventDefault();
}));

$($("body").on("click", ".create-account-and-tree", function (event) {
    var errorMessage = "", validationMessage = "";
    var url = "/trees/person/save";
    var postData = "1=1";
    var button = $(this);
    var buttonHtml = button.html();
    var familyTreeName = "", myFirstName = "", myLastName = "", myEmail = "", terms = false;
    button.html("<i class='fa fa-spinner fa-spin'></i>");

    var modal = button.parents("#divCreateAccountAndTree");

    if (modal.find("#Terms").is(':checked')) terms = true;
    
    //validate input
    if (modal.find("#FirstName").val() == "" || modal.find("#LastName").val() == "") {
        validationMessage += "Please enter your name<br/>";
        modal.find("#FirstName").addClass("validation-error");
        modal.find("#LastName").addClass("validation-error");
    }
    else {
        myFirstName = modal.find("#FirstName").val();
        myLastName = modal.find("#LastName").val();
        modal.find("#FirstName").removeClass("validation-error");
        modal.find("#LastName").removeClass("validation-error");
    }
    if (modal.find("#Email").val() == "") {
        validationMessage += "Please enter your email address<br/>";
        modal.find("#Email").addClass("validation-error");
    }
    else {
        myEmail = modal.find("#Email").val();
        modal.find("#Email").removeClass("validation-error");
    }
    if (modal.find("#GenderTypeId").val() == "" || modal.find("#GenderTypeId").val() == null) {
        validationMessage += "Please select gender<br/>";
        modal.find("#GenderTypeId").addClass("validation-error");
    }
    else modal.find("#GenderTypeId").removeClass("validation-error");

    if (validationMessage != "") {
        button.html(buttonHtml);
        modal.find("#errorMessage").html(validationMessage);
        modal.find("#errorMessage").removeClass("hidden");
        modal.find("#divAddNewPerson").addClass("hidden");
        modal.find("#divPersonDetails").removeClass("hidden");
        event.preventDefault();
        return;
    }
    else {
        modal.find("#errorMessage").addClass("hidden");
        modal.find("#Email").removeClass("validation-error");
        modal.find("#FirstName").removeClass("validation-error");
        modal.find("#LastName").removeClass("validation-error");
        modal.find("#GenderTypeId").removeClass("validation-error");
    }
    
    //set all input variables
    if (modal.find("#FirstName") && modal.find("#FirstName").length) postData += "&FirstName=" + encodeURIComponent(modal.find("#FirstName").val());
    if (modal.find("#LastName") && modal.find("#LastName").length) postData += "&LastName=" + encodeURIComponent(modal.find("#LastName").val());
    if (modal.find("#GenderTypeId") && modal.find("#GenderTypeId").length) postData += "&GenderTypeId=" + modal.find("#GenderTypeId").val();
    postData += "&registerSuccess=true";
    postData += "&Living=true"; //adding self so living
    postData += "&FamilyTreeName=" + myLastName + " Family Tree";
    
    //alert(url);
    $.ajax({
        type: "POST",
        url: "/myaccount/register",
        data: "FirstName=" + myFirstName + "&LastName=" + myLastName + "&Email=" + myEmail + "&AutoGenerateUserName=True&Terms=" + terms + "&returnUrl=" + encodeURIComponent(url + "?" + postData),
        success: function (text) {
            if (text == "402") errorMessage = "There has been an error, please try again.";
            else if (text == "427") errorMessage = "That email has already been used to create an account, please sign in.";
            else if (text == "404") errorMessage = "Some of your input is invalid. Make sure your email address is valid and your name doesn't have strange characters in it.";
            else {
                if (typeof ga !== 'undefined') {
                    var eventLabel = "";
                    ga('send', 'event', 'save-record-tree', 'click', eventLabel);
                }
                location = text;
            }

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        },
        error: function (text) {
            errorMessage = "There has been an error, please try again.";

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        }
    });

    event.preventDefault();
}));

$($("body").on("click", "#btnSavePhotoPerson", function (event) {
    var errorMessage = "", validationMessage = "";
    var url = "/media/save";
    var button = $(this);
    var buttonHtml = button.html();
    button.html("<i class='fa fa-spinner fa-spin'></i>");

    var modal = $(this).parents(".modal");

    //validate input
    //if ($("#File").val() == "" || $("#File").val() == null) {
    //    validationMessage += "Please select file<br/>";
    //    $("#File").addClass("validation-error");
    //}

    if (validationMessage != "") {
        button.html(buttonHtml);
        modal.find("#errorMessage").html(validationMessage);
        modal.find("#errorMessage").removeClass("hidden");
        event.preventDefault();
        return;
    }
    else {
        modal.find("#errorMessage").addClass("hidden");
        modal.find("#File").removeClass("validation-error");
    }

    //set all input variables
    //if (modal.find("#FamilyTreePersons_0__PersonId") && modal.find("#FamilyTreePersons_0__PersonId").val() && modal.find("#FamilyTreePersons_0__PersonId").val() != "") url += "&PersonId=" + modal.find("#FamilyTreePersons_0__PersonId").val();

    var data = new FormData();
    var files = modal.find("#File").get(0).files;

    // Add the uploaded image content to the form data collection
    if (files.length > 0) {
        data.append("file", files[0]);
    }
    data.append("referenceId", modal.find("#referenceId").val());
    data.append("referenceTypeId", modal.find("#referenceTypeId").val());

    //alert(url);
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        processData: false,
        contentType: false,
        success: function (text) {
            if (text == "401") window.location = "/myaccount/register?returnUrl=" + encodeURIComponent(appendParameterToUrl(window.location.pathname + window.location.search, "showsidecount", "true"));    //ajax only, after login will have to go to search results/tree page
            else if (text == "402" || text == "426") errorMessage = "There has been an error, please try again.";
            else if (text == "404") errorMessage = "Some of your input is invalid.";
            else if (text == "420") errorMessage = "No User found.";
            else if (text == "436") errorMessage = "That file type is not allowed, only .jpg, .gif, .png, .tiff and .bmp allowed.";
            else if (text == "437") errorMessage = "You already have the maximum number of media allowed for that object.";
            else if (text == "438") errorMessage = "You have already uploaded this exact piece of media.";
            else if (text == "439") errorMessage = "We are unable to use that photo, sorry.";
            else {
                if (typeof ga !== 'undefined') {
                    ga('send', 'event', 'photo-save-person-main', 'click', '');
                }

                button.html("<i class='fa fa-check'></i>");

                //close modal
                modal.modal('hide');

                //if on tree page need to refresh tree
                //!modal.find("#drpFamilyTreeId").val() || !$("#FamilyTreeId").length
                if (window.location.toString().toLowerCase().indexOf("/trees") != -1) {
                    reloadTree(window.location); //location = location;

                    //if came from account creation page we want user to keep adding people, so just keep showing add relative modal
                    //until they click to another page
                    if (fromRelativeModal && document.URL.toLowerCase().indexOf("registersuccess=true") > -1
                        && (!modal.find("#PersonId") || !modal.find("#PersonId").val() || modal.find("#PersonId").val() == "")) {
                        $("#addRelative").trigger("click");
                    }
                    fromRelativeModal = false;  //reset, will only be set to true if user clicked new person from relative modal
                }
                else if (window.location.toString().toLowerCase().indexOf("/registersuccess") != -1) location = "/trees";
            }

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        },
        error: function (text) {
            errorMessage = "There has been an error, please try again.";

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        }
    });

    event.preventDefault();
}));

$($("body").on("click", ".delete-photo", function (event) {
    var errorMessage = "", validationMessage = "";
    var url = $(this).attr("href").valueOf();
    var button = $(this);
    var buttonHtml = button.html();
    button.html("<i class='fa fa-spinner fa-spin'></i>");

    var modal = $("#treeSettingsModal");

    if (!confirm("Confirm delete this photo?")) {
        event.preventDefault();
        $(button).html(buttonHtml);
        return;
    }

    //alert(url);
    $.ajax({
        url: url,
        success: function (text) {
            if (text == "401") window.location = "/myaccount/register?returnUrl=" + encodeURIComponent(appendParameterToUrl(window.location.pathname + window.location.search, "showsidecount", "true"));    //ajax only, after login will have to go to search results/tree page
            else if (text == "402" || text == "426") errorMessage = "There has been an error, please try again.";
            else if (text == "420") errorMessage = "No User found.";
            else if (text == "432") errorMessage = "This tree is being shared. You must remove all shared people before you can delete this tree. All of their contributions will be deleted which might not be a very nice thing to do. Keep that in mind.";
            else {
                if (window.location.toString().toLowerCase().indexOf("/trees") != -1) reloadTree(window.location);
            }

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        },
        error: function (text) {
            errorMessage = "There has been an error, please try again.";

            if (errorMessage != "") {
                button.html(buttonHtml);
                modal.find("#errorMessage").html(errorMessage);
                modal.find("#errorMessage").removeClass("hidden");
                event.preventDefault();
                return;
            }
        }
    });

    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'delete-photo', 'click', '');
    }

    event.preventDefault();
}));

function reloadTree(url)
{
    $.ajax({
        cache: false,
        url: url,
        success: function (text) {
            $("#treeContent").html(text);
            //history.replaceState({ treeContent: text }, null, window.location);
            //console.log('replaceState called');

            if (window.location.toString().toLowerCase().indexOf("/profile") == -1) {
                (function () {
                    var $container = $('#treeContainer');
                    var $panzoom = $container.find('#panzoom').panzoom();
                    $panzoom.parent().on('mousewheel.focal', function (e) {
                        e.preventDefault();
                        var delta = e.delta || e.originalEvent.wheelDelta;
                        var zoomOut = delta ? delta < 0 : e.originalEvent.deltaY > 0;
                        $panzoom.panzoom('zoom', zoomOut, {
                            increment: 0.1,
                            focal: e
                        });
                    });
                })();

                //make links work inside pan object
                $('#panzoom a').on('mousedown touchstart', function (e) {
                    e.stopImmediatePropagation();
                });
                $("#treeContainer").css("height", $(window).height() * .85);
                $("#panzoom").css("height", $(window).height() * 1.5);
                $(".tree-node-container").css("top", ($("#treeContainer").height() / 3) + 300);
            }            

            if (text.indexOf("<!--TREE_CREATED-->") != -1) {
                if (typeof ga !== 'undefined') {
                    ga('send', 'event', 'tree-create', 'click', '');
                }
            }
        }
    });
}

//if user selects to create a new tree we need to show new tree text box
$($("#treeNewPersonModal").on("change", "#drpFamilyTreeId", function (event) {
    val = $(this).val();
    if (val == "-1") {
        $("#divFamilyTreeDropDown").addClass("hidden");
        $("#divFamilyTreeName").removeClass("hidden");
        $("#divPersonDetails").removeClass("hidden");
        $("#divAddNewPerson").addClass("hidden");

        if ($("#divRecent").length)
        {
            $("#drpRecentPersonId").val("");
            $("#divRecent").addClass("hidden");
        }
    } else {
        $("#divFamilyTreeDropDown").removeClass("hidden");
        $("#divFamilyTreeName").addClass("hidden");

        //need to load recent list for this tree
        if (val != "") {
            loadRecentPersonsDropDown(val);
        }
    }
}));

function loadRecentPersonsDropDown(familyTreeId) {
    var url = "/trees/" + familyTreeId + "/recentlist";
    var button = $("#divRecentDropDown");
    var buttonHtml = button.html();
    button.html("<i class='fa fa-spinner fa-spin'></i>");

    if ($("#DobYear") && $("#DobYear").length) url = appendParameterToUrl(url, "DobYear", $("#DobYear").val());
    if ($("#GenderTypeId") && $("#GenderTypeId").length) url = appendParameterToUrl(url, "GenderTypeId", $("#GenderTypeId").val());

    $.ajax({
        cache: false,
        url: url,
        success: function (text) {
            if (text == "401") window.location = "/myaccount/register?returnUrl=" + encodeURIComponent(appendParameterToUrl(window.location.pathname + window.location.search, "showsidecount", "true"))
            else if (text == "402") {
                console.log("error loading recent");
                button.html(buttonHtml);
            }
            else {
                button.html(buttonHtml);
                $("#drpRecentPersonId").html(text);
                $("#divRecent").removeClass("hidden");
                $("#divRecentDropDown").removeClass("hidden");
            }
        },
        error: function (text) {
            button.html(buttonHtml);
        }
    });
}

$($("#treeNewPersonModal").on("change", "#drpRecentPersonId", function (event) {
    if ($("#divPossibleParents1").length) $("#divPossibleParents1").removeClass("hidden");
    if ($("#divPossibleParents2").length) $("#divPossibleParents2").removeClass("hidden");

    val = $(this).val();
    if (val == "") {
        $("#divPersonDetails").removeClass("hidden");
    } else {
        $("#divPersonDetails").addClass("hidden");
    }
    
    //if exising person has father or mother already then we need to hide the option
    //to choose parents
    var fatherPersonId = $(this).find("option[value='" + val + "']").attr("data-father-person-id").valueOf();
    var motherPersonId = $(this).find("option[value='" + val + "']").attr("data-mother-person-id").valueOf();
    
    if (fatherPersonId != "" && $("#divPossibleParents1").length && $("#RelationshipTypeIdParent1").val() == "Father")
    {
        $("#divPossibleParents1").addClass("hidden");
    }
    else if (fatherPersonId != "" && $("#divPossibleParents2").length && $("#RelationshipTypeIdParent2").val() == "Father") {
        $("#divPossibleParents2").addClass("hidden");
    }
    if (motherPersonId != "" && $("#divPossibleParents1").length && $("#RelationshipTypeIdParent1").val() == "Mother") {
        $("#divPossibleParents1").addClass("hidden");
    }
    else if (motherPersonId != "" && $("#divPossibleParents2").length && $("#RelationshipTypeIdParent2").val() == "Mother") {
        $("#divPossibleParents2").addClass("hidden");
    }
}));

//show/hide death info depending on status
$($("#treeNewPersonModal").on("change", "#Living", function (event) {
    val = $(this).val();
    if (val == "True") {
        $("#divDeathPlace").addClass("hidden");
        $("#divEmail").removeClass("hidden");
    } else if (val == "False") {
        $("#divDeathPlace").removeClass("hidden");
        $("#divEmail").addClass("hidden");
    }
}));

$($("body").on("click", "#addExtraInfo", function (event) {
    $("#addExtraInfo").hide();

    $("#extraInfo").removeClass("hidden");
}));

function trackWidgetClick(link) {
    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'widget-link', 'click', link);
    }
}

$(document).ready(function () {
    if (document.URL.toLowerCase().indexOf("print=1") > -1) {
        window.print();
        return false;
    }
    else if (document.URL.toLowerCase().indexOf("registersuccess=true") > -1) {
        $("#addRelative").trigger("click");
    }
});

var countKeysTyped = 0; //going to use for autocomplete (names), if no keys entered then don't show autocomplete (shows when you just click the input if already filled in, kind of messes up mobile cause it blocks the city form)
document.onkeydown = function (evt) {
    countKeysTyped++;
}

$(document).ready(function () {
    var url = window.location.toString().toLowerCase();

    //summary name searches only
    if ((url.indexOf("genealogy/results?") > -1 || url.indexOf("people/results?") > -1) && url.indexOf("&rid") == -1) {
        var first = '', middle = '', last = '', location = '';

        if ($("#criteriaForm").find("#First").val() && $("#criteriaForm").find("#First").val() != '') first = $("#criteriaForm").find("#First").val();
        if ($("#criteriaForm").find("#Middle").val() && $("#criteriaForm").find("#Middle").val() != '') middle = $("#criteriaForm").find("#Middle").val();
        if ($("#criteriaForm").find("#Last").val() && $("#criteriaForm").find("#Last").val() != '') last = $("#criteriaForm").find("#Last").val();
        if ($("#criteriaForm").find("#CityStateZip").val() && $("#criteriaForm").find("#CityStateZip").val() != '') location = $("#criteriaForm").find("#CityStateZip").val();

        $.ajax({
            url: '/search/widgets?first=' + first + '&middle=' + middle + '&last=' + last + '&citystatezip=' + location,
            success: function (text) {
                if (text != 'NONE') {
                    $("#widgets").html(text);
                    $("#widgets").css("display", "");
                }
            },
            error: function (text) {

            }
        });
    }
});

//$(document).ready(function () {
//    var url = window.location.toString().toLowerCase();

//    //summary name searches only
//    if (url.indexOf("/results?name=") > -1 && url.indexOf("&rid") != -1) {
//        var fn, ln, city, state, age;

//        fn = $("#personDetails").data("fn");
//        ln = $("#personDetails").data("ln");
//        city = $("#personDetails").data("city");
//        state = $("#personDetails").data("state");
//        age = $("#personDetails").data("age");

//        if (fn != "" && ln != "" && city != "" && state != "" & age != "") {
//            $.ajax({
//                url: '/search/widgetsdetails?name=' + fn + ' ' + ln + '&citystatezip=' + city + ',' + state + "&agerange=" + age,
//                success: function (text) {
//                    if (text != 'NONE') {
//                        $("#widgets").html(text);
//                        $("#widgets").css("display", "");
//                    }
//                },
//                error: function (text) {

//                }
//            });
//        }
//    }
//});

//autocomplete
$('.typeahead-locations').autocomplete({
    serviceUrl: '/autocomplete/location',
    paramName: 'location',
    minChars: 2,
    autoSelectFirst: true
});

$('.typeahead-lastname').autocomplete({
    serviceUrl: '/autocomplete/lastname',
    paramName: 'lastname',
    minChars: 2,
    autoSelectFirst: true,
    showNoSuggestionNotice: false,
    onSearchStart: function (params) {
        if (countKeysTyped == 0) return false;
    }
});

$('.typeahead-firstname').autocomplete({
    serviceUrl: '/autocomplete/firstname',
    paramName: 'firstname',
    minChars: 2,
    autoSelectFirst: true,
    showNoSuggestionNotice: false,
    onSearchStart: function (params) {
        if (countKeysTyped == 0) return false;
    }
});

function backLinkClick() {
    if (typeof ga !== 'undefined') {
        ga('send', 'event', 'search-back', 'click', 'nav');
    }
}

function appendParameterToUrl(url, parameterName, parameterValue) {
    if (url.indexOf("?") != -1) url += "&";
    else url += "?";
    url += parameterName + "=" + parameterValue;

    return url;
}

//phone mask
$('.phone_us').bind("paste", function () {
    $('.phone_us').unmask();
});

$(document).ready(function () {
    $('.phone_us').mask('(000) 000-0000', { placeholder: '' });
});

//close icon on text boxes
//$($(".input-clear-icon").parent().find(":text").focus(function (event) {
//    if ($(event.target).val() != '') $(event.target).parent().find(".input-clear-icon").removeClass("hidden");
//}));

//$($(".input-clear-icon").parent().find(":text").focusout(function (event) {
//    console.log('out');
//    if($(this).val() == '') $(event.target).parent().find(".input-clear-icon").addClass("hidden");
//}));

//$($(".input-clear-icon").click(function () {
//    console.log('click');
//    $(this).parent().find(":text").val("");
//    $(this).addClass("hidden");
//    $(this).parent().find(":text").focus();
//}));

//$($(".input-clear-icon").hover(function () {
//    $(this).css("cursor", "pointer");
//}));;
