////2023-07-18 : if (user_ip == '108.180.234.14') console.log('1               --------------------------------------------');
var xxy12121 = true;

/*! (C) Andrea Giammarchi - Mit Style License */
var URLSearchParams = URLSearchParams || function () { "use strict"; function URLSearchParams(query) { var index, key, value, pairs, i, length, dict = Object.create(null); this[secret] = dict; if (!query) return; if (typeof query === "string") { if (query.charAt(0) === "?") { query = query.slice(1) } for (pairs = query.split("&"), i = 0, length = pairs.length; i < length; i++) { value = pairs[i]; index = value.indexOf("="); if (-1 < index) { appendTo(dict, decode(value.slice(0, index)), decode(value.slice(index + 1))) } else if (value.length) { appendTo(dict, decode(value), "") } } } else { if (isArray(query)) { for (i = 0, length = query.length; i < length; i++) { value = query[i]; appendTo(dict, value[0], value[1]) } } else if (query.forEach) { query.forEach(addEach, dict) } else { for (key in query) { appendTo(dict, key, query[key]) } } } } var isArray = Array.isArray, URLSearchParamsProto = URLSearchParams.prototype, find = /[!'\(\)~]|%20|%00/g, plus = /\+/g, replace = { "!": "%21", "'": "%27", "(": "%28", ")": "%29", "~": "%7E", "%20": "+", "%00": "\0" }, replacer = function (match) { return replace[match] }, secret = "__URLSearchParams__:" + Math.random(); function addEach(value, key) { appendTo(this, key, value) } function appendTo(dict, name, value) { var res = isArray(value) ? value.join(",") : value; if (name in dict) dict[name].push(res); else dict[name] = [res] } function decode(str) { return decodeURIComponent(str.replace(plus, " ")) } function encode(str) { return encodeURIComponent(str).replace(find, replacer) } URLSearchParamsProto.append = function append(name, value) { appendTo(this[secret], name, value) }; URLSearchParamsProto["delete"] = function del(name) { delete this[secret][name] }; URLSearchParamsProto.get = function get(name) { var dict = this[secret]; return name in dict ? dict[name][0] : null }; URLSearchParamsProto.getAll = function getAll(name) { var dict = this[secret]; return name in dict ? dict[name].slice(0) : [] }; URLSearchParamsProto.has = function has(name) { return name in this[secret] }; URLSearchParamsProto.set = function set(name, value) { this[secret][name] = ["" + value] }; URLSearchParamsProto.forEach = function forEach(callback, thisArg) { var dict = this[secret]; Object.getOwnPropertyNames(dict).forEach(function (name) { dict[name].forEach(function (value) { callback.call(thisArg, value, name, this) }, this) }, this) }; URLSearchParamsProto.toJSON = function toJSON() { return {} }; URLSearchParamsProto.toString = function toString() { var dict = this[secret], query = [], i, key, name, value; for (key in dict) { name = encode(key); for (i = 0, value = dict[key]; i < value.length; i++) { query.push(name + "=" + encode(value[i])) } } return query.join("&") }; var dP = Object.defineProperty, gOPD = Object.getOwnPropertyDescriptor, createSearchParamsPollute = function (search) { function append(name, value) { URLSearchParamsProto.append.call(this, name, value); name = this.toString(); search.set.call(this._usp, name ? "?" + name : "") } function del(name) { URLSearchParamsProto["delete"].call(this, name); name = this.toString(); search.set.call(this._usp, name ? "?" + name : "") } function set(name, value) { URLSearchParamsProto.set.call(this, name, value); name = this.toString(); search.set.call(this._usp, name ? "?" + name : "") } return function (sp, value) { sp.append = append; sp["delete"] = del; sp.set = set; return dP(sp, "_usp", { configurable: true, writable: true, value: value }) } }, createSearchParamsCreate = function (polluteSearchParams) { return function (obj, sp) { dP(obj, "_searchParams", { configurable: true, writable: true, value: polluteSearchParams(sp, obj) }); return sp } }, updateSearchParams = function (sp) { var append = sp.append; sp.append = URLSearchParamsProto.append; URLSearchParams.call(sp, sp._usp.search.slice(1)); sp.append = append }, verifySearchParams = function (obj, Class) { if (!(obj instanceof Class)) throw new TypeError("'searchParams' accessed on an object that " + "does not implement interface " + Class.name) }, upgradeClass = function (Class) { var ClassProto = Class.prototype, searchParams = gOPD(ClassProto, "searchParams"), href = gOPD(ClassProto, "href"), search = gOPD(ClassProto, "search"), createSearchParams; if (!searchParams && search && search.set) { createSearchParams = createSearchParamsCreate(createSearchParamsPollute(search)); Object.defineProperties(ClassProto, { href: { get: function () { return href.get.call(this) }, set: function (value) { var sp = this._searchParams; href.set.call(this, value); if (sp) updateSearchParams(sp) } }, search: { get: function () { return search.get.call(this) }, set: function (value) { var sp = this._searchParams; search.set.call(this, value); if (sp) updateSearchParams(sp) } }, searchParams: { get: function () { verifySearchParams(this, Class); return this._searchParams || createSearchParams(this, new URLSearchParams(this.search.slice(1))) }, set: function (sp) { verifySearchParams(this, Class); createSearchParams(this, sp) } } }) } }; upgradeClass(HTMLAnchorElement); if (/^function|object$/.test(typeof URL) && URL.prototype) upgradeClass(URL); return URLSearchParams }(); (function (URLSearchParamsProto) { var iterable = function () { try { return !!Symbol.iterator } catch (error) { return false } }(); if (!("forEach" in URLSearchParamsProto)) { URLSearchParamsProto.forEach = function forEach(callback, thisArg) { var names = Object.create(null); this.toString().replace(/=[\s\S]*?(?:&|$)/g, "=").split("=").forEach(function (name) { if (!name.length || name in names) return; (names[name] = this.getAll(name)).forEach(function (value) { callback.call(thisArg, value, name, this) }, this) }, this) } } if (!("keys" in URLSearchParamsProto)) { URLSearchParamsProto.keys = function keys() { var items = []; this.forEach(function (value, name) { items.push(name) }); var iterator = { next: function () { var value = items.shift(); return { done: value === undefined, value: value } } }; if (iterable) { iterator[Symbol.iterator] = function () { return iterator } } return iterator } } if (!("values" in URLSearchParamsProto)) { URLSearchParamsProto.values = function values() { var items = []; this.forEach(function (value) { items.push(value) }); var iterator = { next: function () { var value = items.shift(); return { done: value === undefined, value: value } } }; if (iterable) { iterator[Symbol.iterator] = function () { return iterator } } return iterator } } if (!("entries" in URLSearchParamsProto)) { URLSearchParamsProto.entries = function entries() { var items = []; this.forEach(function (value, name) { items.push([name, value]) }); var iterator = { next: function () { var value = items.shift(); return { done: value === undefined, value: value } } }; if (iterable) { iterator[Symbol.iterator] = function () { return iterator } } return iterator } } if (iterable && !(Symbol.iterator in URLSearchParamsProto)) { URLSearchParamsProto[Symbol.iterator] = URLSearchParamsProto.entries } if (!("sort" in URLSearchParamsProto)) { URLSearchParamsProto.sort = function sort() { var entries = this.entries(), entry = entries.next(), done = entry.done, keys = [], values = Object.create(null), i, key, value; while (!done) { value = entry.value; key = value[0]; keys.push(key); if (!(key in values)) { values[key] = [] } values[key].push(value[1]); entry = entries.next(); done = entry.done } keys.sort(); for (i = 0; i < keys.length; i++) { this["delete"](keys[i]) } for (i = 0; i < keys.length; i++) { key = keys[i]; this.append(key, values[key].shift()) } } } })(URLSearchParams.prototype);

(function (factory) {

  if (typeof define === 'function' && define.amd) {

    // AMD. Register as an anonymous module.
    define([], factory);

  } else if (typeof exports === 'object') {

    // Node/CommonJS
    module.exports = factory();

  } else {

    // Browser globals
    window.wNumb = factory();
  }

}(function () {

  'use strict';

  var FormatOptions = [
    'decimals',
    'thousand',
    'mark',
    'prefix',
    'suffix',
    'encoder',
    'decoder',
    'negativeBefore',
    'negative',
    'edit',
    'undo'
  ];

  // General

  // Reverse a string
  function strReverse(a) {
    return a.split('').reverse().join('');
  }

  // Check if a string starts with a specified prefix.
  function strStartsWith(input, match) {
    return input.substring(0, match.length) === match;
  }

  // Check is a string ends in a specified suffix.
  function strEndsWith(input, match) {
    return input.slice(-1 * match.length) === match;
  }

  // Throw an error if formatting options are incompatible.
  function throwEqualError(F, a, b) {
    if ((F[a] || F[b]) && (F[a] === F[b])) {
      throw new Error(a);
    }
  }

  // Check if a number is finite and not NaN
  function isValidNumber(input) {
    return typeof input === 'number' && isFinite(input);
  }

  // Provide rounding-accurate toFixed method.
  // Borrowed: http://stackoverflow.com/a/21323330/775265
  function toFixed(value, exp) {
    value = value.toString().split('e');
    value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)));
    value = value.toString().split('e');
    return (+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))).toFixed(exp);
  }


  // Formatting

  // Accept a number as input, output formatted string.
  function formatTo(decimals, thousand, mark, prefix, suffix, encoder, decoder, negativeBefore, negative, edit, undo, input) {

    var originalInput = input, inputIsNegative, inputPieces, inputBase, inputDecimals = '', output = '';

    // Apply user encoder to the input.
    // Expected outcome: number.
    if (encoder) {
      input = encoder(input);
    }

    // Stop if no valid number was provided, the number is infinite or NaN.
    if (!isValidNumber(input)) {
      return false;
    }

    // Rounding away decimals might cause a value of -0
    // when using very small ranges. Remove those cases.
    if (decimals !== false && parseFloat(input.toFixed(decimals)) === 0) {
      input = 0;
    }

    // Formatting is done on absolute numbers,
    // decorated by an optional negative symbol.
    if (input < 0) {
      inputIsNegative = true;
      input = Math.abs(input);
    }

    // Reduce the number of decimals to the specified option.
    if (decimals !== false) {
      input = toFixed(input, decimals);
    }

    // Transform the number into a string, so it can be split.
    input = input.toString();

    // Break the number on the decimal separator.
    if (input.indexOf('.') !== -1) {
      inputPieces = input.split('.');

      inputBase = inputPieces[0];

      if (mark) {
        inputDecimals = mark + inputPieces[1];
      }

    } else {

      // If it isn't split, the entire number will do.
      inputBase = input;
    }

    // Group numbers in sets of three.
    if (thousand) {
      inputBase = strReverse(inputBase).match(/.{1,3}/g);
      inputBase = strReverse(inputBase.join(strReverse(thousand)));
    }

    // If the number is negative, prefix with negation symbol.
    if (inputIsNegative && negativeBefore) {
      output += negativeBefore;
    }

    // Prefix the number
    if (prefix) {
      output += prefix;
    }

    // Normal negative option comes after the prefix. Defaults to '-'.
    if (inputIsNegative && negative) {
      output += negative;
    }

    // Append the actual number.
    output += inputBase;
    output += inputDecimals;

    // Apply the suffix.
    if (suffix) {
      output += suffix;
    }

    // Run the output through a user-specified post-formatter.
    if (edit) {
      output = edit(output, originalInput);
    }

    // All done.
    return output;
  }

  // Accept a sting as input, output decoded number.
  function formatFrom(decimals, thousand, mark, prefix, suffix, encoder, decoder, negativeBefore, negative, edit, undo, input) {

    var originalInput = input, inputIsNegative, output = '';

    // User defined pre-decoder. Result must be a non empty string.
    if (undo) {
      input = undo(input);
    }

    // Test the input. Can't be empty.
    if (!input || typeof input !== 'string') {
      return false;
    }

    // If the string starts with the negativeBefore value: remove it.
    // Remember is was there, the number is negative.
    if (negativeBefore && strStartsWith(input, negativeBefore)) {
      input = input.replace(negativeBefore, '');
      inputIsNegative = true;
    }

    // Repeat the same procedure for the prefix.
    if (prefix && strStartsWith(input, prefix)) {
      input = input.replace(prefix, '');
    }

    // And again for negative.
    if (negative && strStartsWith(input, negative)) {
      input = input.replace(negative, '');
      inputIsNegative = true;
    }

    // Remove the suffix.
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice
    if (suffix && strEndsWith(input, suffix)) {
      input = input.slice(0, -1 * suffix.length);
    }

    // Remove the thousand grouping.
    if (thousand) {
      input = input.split(thousand).join('');
    }

    // Set the decimal separator back to period.
    if (mark) {
      input = input.replace(mark, '.');
    }

    // Prepend the negative symbol.
    if (inputIsNegative) {
      output += '-';
    }

    // Add the number
    output += input;

    // Trim all non-numeric characters (allow '.' and '-');
    output = output.replace(/[^0-9\.\-.]/g, '');

    // The value contains no parse-able number.
    if (output === '') {
      return false;
    }

    // Covert to number.
    output = Number(output);

    // Run the user-specified post-decoder.
    if (decoder) {
      output = decoder(output);
    }

    // Check is the output is valid, otherwise: return false.
    if (!isValidNumber(output)) {
      return false;
    }

    return output;
  }


  // Framework

  // Validate formatting options
  function validate(inputOptions) {

    var i, optionName, optionValue,
      filteredOptions = {};

    if (inputOptions['suffix'] === undefined) {
      inputOptions['suffix'] = inputOptions['postfix'];
    }

    for (i = 0; i < FormatOptions.length; i += 1) {

      optionName = FormatOptions[i];
      optionValue = inputOptions[optionName];

      if (optionValue === undefined) {

        // Only default if negativeBefore isn't set.
        if (optionName === 'negative' && !filteredOptions.negativeBefore) {
          filteredOptions[optionName] = '-';
          // Don't set a default for mark when 'thousand' is set.
        } else if (optionName === 'mark' && filteredOptions.thousand !== '.') {
          filteredOptions[optionName] = '.';
        } else {
          filteredOptions[optionName] = false;
        }

        // Floating points in JS are stable up to 7 decimals.
      } else if (optionName === 'decimals') {
        if (optionValue >= 0 && optionValue < 8) {
          filteredOptions[optionName] = optionValue;
        } else {
          throw new Error(optionName);
        }

        // These options, when provided, must be functions.
      } else if (optionName === 'encoder' || optionName === 'decoder' || optionName === 'edit' || optionName === 'undo') {
        if (typeof optionValue === 'function') {
          filteredOptions[optionName] = optionValue;
        } else {
          throw new Error(optionName);
        }

        // Other options are strings.
      } else {

        if (typeof optionValue === 'string') {
          filteredOptions[optionName] = optionValue;
        } else {
          throw new Error(optionName);
        }
      }
    }

    // Some values can't be extracted from a
    // string if certain combinations are present.
    throwEqualError(filteredOptions, 'mark', 'thousand');
    throwEqualError(filteredOptions, 'prefix', 'negative');
    throwEqualError(filteredOptions, 'prefix', 'negativeBefore');

    return filteredOptions;
  }

  // Pass all options as function arguments
  function passAll(options, method, input) {
    var i, args = [];

    // Add all options in order of FormatOptions
    for (i = 0; i < FormatOptions.length; i += 1) {
      args.push(options[FormatOptions[i]]);
    }

    // Append the input, then call the method, presenting all
    // options as arguments.
    args.push(input);
    return method.apply('', args);
  }
  ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('336             --------------------------------------------');

  function wNumb(options) {

    if (!(this instanceof wNumb)) {
      return new wNumb(options);
    }

    if (typeof options !== "object") {
      return;
    }

    options = validate(options);

    // Call 'formatTo' with proper arguments.
    this.to = function (input) {
      return passAll(options, formatTo, input);
    };

    // Call 'formatFrom' with proper arguments.
    this.from = function (input) {
      return passAll(options, formatFrom, input);
    };
  }

  return wNumb;

}));

/*! nouislider - 14.0.2 - 6/28/2019 */
!function (t) { "function" == typeof define && define.amd ? define([], t) : "object" == typeof exports ? module.exports = t() : window.noUiSlider = t() }(function () { "use strict"; var lt = "14.0.2"; function ut(t) { t.parentElement.removeChild(t) } function s(t) { return null != t } function ct(t) { t.preventDefault() } function i(t) { return "number" == typeof t && !isNaN(t) && isFinite(t) } function pt(t, e, r) { 0 < r && (ht(t, e), setTimeout(function () { mt(t, e) }, r)) } function ft(t) { return Math.max(Math.min(t, 100), 0) } function dt(t) { return Array.isArray(t) ? t : [t] } function e(t) { var e = (t = String(t)).split("."); return 1 < e.length ? e[1].length : 0 } function ht(t, e) { t.classList ? t.classList.add(e) : t.className += " " + e } function mt(t, e) { t.classList ? t.classList.remove(e) : t.className = t.className.replace(new RegExp("(^|\\b)" + e.split(" ").join("|") + "(\\b|$)", "gi"), " ") } function gt(t) { var e = void 0 !== window.pageXOffset, r = "CSS1Compat" === (t.compatMode || ""); return { x: e ? window.pageXOffset : r ? t.documentElement.scrollLeft : t.body.scrollLeft, y: e ? window.pageYOffset : r ? t.documentElement.scrollTop : t.body.scrollTop } } function c(t, e) { return 100 / (e - t) } function p(t, e) { return 100 * e / (t[1] - t[0]) } function f(t, e) { for (var r = 1; t >= e[r];)r += 1; return r } function r(t, e, r) { if (r >= t.slice(-1)[0]) return 100; var n, i, o = f(r, t), a = t[o - 1], s = t[o], l = e[o - 1], u = e[o]; return l + (i = r, p(n = [a, s], n[0] < 0 ? i + Math.abs(n[0]) : i - n[0]) / c(l, u)) } function n(t, e, r, n) { if (100 === n) return n; var i, o, a = f(n, t), s = t[a - 1], l = t[a]; return r ? (l - s) / 2 < n - s ? l : s : e[a - 1] ? t[a - 1] + (i = n - t[a - 1], o = e[a - 1], Math.round(i / o) * o) : n } function o(t, e, r) { var n; if ("number" == typeof e && (e = [e]), !Array.isArray(e)) throw new Error("noUiSlider (" + lt + "): 'range' contains invalid value."); if (!i(n = "min" === t ? 0 : "max" === t ? 100 : parseFloat(t)) || !i(e[0])) throw new Error("noUiSlider (" + lt + "): 'range' value isn't numeric."); r.xPct.push(n), r.xVal.push(e[0]), n ? r.xSteps.push(!isNaN(e[1]) && e[1]) : isNaN(e[1]) || (r.xSteps[0] = e[1]), r.xHighestCompleteStep.push(0) } function a(t, e, r) { if (e) if (r.xVal[t] !== r.xVal[t + 1]) { r.xSteps[t] = p([r.xVal[t], r.xVal[t + 1]], e) / c(r.xPct[t], r.xPct[t + 1]); var n = (r.xVal[t + 1] - r.xVal[t]) / r.xNumSteps[t], i = Math.ceil(Number(n.toFixed(3)) - 1), o = r.xVal[t] + r.xNumSteps[t] * i; r.xHighestCompleteStep[t] = o } else r.xSteps[t] = r.xHighestCompleteStep[t] = r.xVal[t] } function l(t, e, r) { var n; this.xPct = [], this.xVal = [], this.xSteps = [r || !1], this.xNumSteps = [!1], this.xHighestCompleteStep = [], this.snap = e; var i = []; for (n in t) t.hasOwnProperty(n) && i.push([t[n], n]); for (i.length && "object" == typeof i[0][0] ? i.sort(function (t, e) { return t[0][0] - e[0][0] }) : i.sort(function (t, e) { return t[0] - e[0] }), n = 0; n < i.length; n++)o(i[n][1], i[n][0], this); for (this.xNumSteps = this.xSteps.slice(0), n = 0; n < this.xNumSteps.length; n++)a(n, this.xNumSteps[n], this) } l.prototype.getMargin = function (t) { var e = this.xNumSteps[0]; if (e && t / e % 1 != 0) throw new Error("noUiSlider (" + lt + "): 'limit', 'margin' and 'padding' must be divisible by step."); return 2 === this.xPct.length && p(this.xVal, t) }, l.prototype.toStepping = function (t) { return t = r(this.xVal, this.xPct, t) }, l.prototype.fromStepping = function (t) { return function (t, e, r) { if (100 <= r) return t.slice(-1)[0]; var n, i = f(r, e), o = t[i - 1], a = t[i], s = e[i - 1], l = e[i]; return n = [o, a], (r - s) * c(s, l) * (n[1] - n[0]) / 100 + n[0] }(this.xVal, this.xPct, t) }, l.prototype.getStep = function (t) { return t = n(this.xPct, this.xSteps, this.snap, t) }, l.prototype.getDefaultStep = function (t, e, r) { var n = f(t, this.xPct); return (100 === t || e && t === this.xPct[n - 1]) && (n = Math.max(n - 1, 1)), (this.xVal[n] - this.xVal[n - 1]) / r }, l.prototype.getNearbySteps = function (t) { var e = f(t, this.xPct); return { stepBefore: { startValue: this.xVal[e - 2], step: this.xNumSteps[e - 2], highestStep: this.xHighestCompleteStep[e - 2] }, thisStep: { startValue: this.xVal[e - 1], step: this.xNumSteps[e - 1], highestStep: this.xHighestCompleteStep[e - 1] }, stepAfter: { startValue: this.xVal[e], step: this.xNumSteps[e], highestStep: this.xHighestCompleteStep[e] } } }, l.prototype.countStepDecimals = function () { var t = this.xNumSteps.map(e); return Math.max.apply(null, t) }, l.prototype.convert = function (t) { return this.getStep(this.toStepping(t)) }; var u = { to: function (t) { return void 0 !== t && t.toFixed(2) }, from: Number }; function d(t) { if ("object" == typeof (e = t) && "function" == typeof e.to && "function" == typeof e.from) return !0; var e; throw new Error("noUiSlider (" + lt + "): 'format' requires 'to' and 'from' methods.") } function h(t, e) { if (!i(e)) throw new Error("noUiSlider (" + lt + "): 'step' is not numeric."); t.singleStep = e } function m(t, e) { if ("object" != typeof e || Array.isArray(e)) throw new Error("noUiSlider (" + lt + "): 'range' is not an object."); if (void 0 === e.min || void 0 === e.max) throw new Error("noUiSlider (" + lt + "): Missing 'min' or 'max' in 'range'."); if (e.min === e.max) throw new Error("noUiSlider (" + lt + "): 'range' 'min' and 'max' cannot be equal."); t.spectrum = new l(e, t.snap, t.singleStep) } function g(t, e) { if (e = dt(e), !Array.isArray(e) || !e.length) throw new Error("noUiSlider (" + lt + "): 'start' option is incorrect."); t.handles = e.length, t.start = e } function v(t, e) { if ("boolean" != typeof (t.snap = e)) throw new Error("noUiSlider (" + lt + "): 'snap' option must be a boolean.") } function b(t, e) { if ("boolean" != typeof (t.animate = e)) throw new Error("noUiSlider (" + lt + "): 'animate' option must be a boolean.") } function S(t, e) { if ("number" != typeof (t.animationDuration = e)) throw new Error("noUiSlider (" + lt + "): 'animationDuration' option must be a number.") } function x(t, e) { var r, n = [!1]; if ("lower" === e ? e = [!0, !1] : "upper" === e && (e = [!1, !0]), !0 === e || !1 === e) { for (r = 1; r < t.handles; r++)n.push(e); n.push(!1) } else { if (!Array.isArray(e) || !e.length || e.length !== t.handles + 1) throw new Error("noUiSlider (" + lt + "): 'connect' option doesn't match handle count."); n = e } t.connect = n } function w(t, e) { switch (e) { case "horizontal": t.ort = 0; break; case "vertical": t.ort = 1; break; default: throw new Error("noUiSlider (" + lt + "): 'orientation' option is invalid.") } } function y(t, e) { if (!i(e)) throw new Error("noUiSlider (" + lt + "): 'margin' option must be numeric."); if (0 !== e && (t.margin = t.spectrum.getMargin(e), !t.margin)) throw new Error("noUiSlider (" + lt + "): 'margin' option is only supported on linear sliders.") } function E(t, e) { if (!i(e)) throw new Error("noUiSlider (" + lt + "): 'limit' option must be numeric."); if (t.limit = t.spectrum.getMargin(e), !t.limit || t.handles < 2) throw new Error("noUiSlider (" + lt + "): 'limit' option is only supported on linear sliders with 2 or more handles.") } function C(t, e) { if (!i(e) && !Array.isArray(e)) throw new Error("noUiSlider (" + lt + "): 'padding' option must be numeric or array of exactly 2 numbers."); if (Array.isArray(e) && 2 !== e.length && !i(e[0]) && !i(e[1])) throw new Error("noUiSlider (" + lt + "): 'padding' option must be numeric or array of exactly 2 numbers."); if (0 !== e) { if (Array.isArray(e) || (e = [e, e]), !(t.padding = [t.spectrum.getMargin(e[0]), t.spectrum.getMargin(e[1])]) === t.padding[0] || !1 === t.padding[1]) throw new Error("noUiSlider (" + lt + "): 'padding' option is only supported on linear sliders."); if (t.padding[0] < 0 || t.padding[1] < 0) throw new Error("noUiSlider (" + lt + "): 'padding' option must be a positive number(s)."); if (100 < t.padding[0] + t.padding[1]) throw new Error("noUiSlider (" + lt + "): 'padding' option must not exceed 100% of the range.") } } function N(t, e) { switch (e) { case "ltr": t.dir = 0; break; case "rtl": t.dir = 1; break; default: throw new Error("noUiSlider (" + lt + "): 'direction' option was not recognized.") } } function U(t, e) { if ("string" != typeof e) throw new Error("noUiSlider (" + lt + "): 'behaviour' must be a string containing options."); var r = 0 <= e.indexOf("tap"), n = 0 <= e.indexOf("drag"), i = 0 <= e.indexOf("fixed"), o = 0 <= e.indexOf("snap"), a = 0 <= e.indexOf("hover"), s = 0 <= e.indexOf("unconstrained"); if (i) { if (2 !== t.handles) throw new Error("noUiSlider (" + lt + "): 'fixed' behaviour must be used with 2 handles"); y(t, t.start[1] - t.start[0]) } if (s && (t.margin || t.limit)) throw new Error("noUiSlider (" + lt + "): 'unconstrained' behaviour cannot be used with margin or limit"); t.events = { tap: r || o, drag: n, fixed: i, snap: o, hover: a, unconstrained: s } } function k(t, e) { if (!1 !== e) if (!0 === e) { t.tooltips = []; for (var r = 0; r < t.handles; r++)t.tooltips.push(!0) } else { if (t.tooltips = dt(e), t.tooltips.length !== t.handles) throw new Error("noUiSlider (" + lt + "): must pass a formatter for all handles."); t.tooltips.forEach(function (t) { if ("boolean" != typeof t && ("object" != typeof t || "function" != typeof t.to)) throw new Error("noUiSlider (" + lt + "): 'tooltips' must be passed a formatter or 'false'.") }) } } function P(t, e) { d(t.ariaFormat = e) } function A(t, e) { d(t.format = e) } function V(t, e) { if ("boolean" != typeof (t.keyboardSupport = e)) throw new Error("noUiSlider (" + lt + "): 'keyboardSupport' option must be a boolean.") } function M(t, e) { t.documentElement = e } function O(t, e) { if ("string" != typeof e && !1 !== e) throw new Error("noUiSlider (" + lt + "): 'cssPrefix' must be a string or `false`."); t.cssPrefix = e } function L(t, e) { if ("object" != typeof e) throw new Error("noUiSlider (" + lt + "): 'cssClasses' must be an object."); if ("string" == typeof t.cssPrefix) for (var r in t.cssClasses = {}, e) e.hasOwnProperty(r) && (t.cssClasses[r] = t.cssPrefix + e[r]); else t.cssClasses = e } function vt(e) { var r = { margin: 0, limit: 0, padding: 0, animate: !0, animationDuration: 300, ariaFormat: u, format: u }, n = { step: { r: !1, t: h }, start: { r: !0, t: g }, connect: { r: !0, t: x }, direction: { r: !0, t: N }, snap: { r: !1, t: v }, animate: { r: !1, t: b }, animationDuration: { r: !1, t: S }, range: { r: !0, t: m }, orientation: { r: !1, t: w }, margin: { r: !1, t: y }, limit: { r: !1, t: E }, padding: { r: !1, t: C }, behaviour: { r: !0, t: U }, ariaFormat: { r: !1, t: P }, format: { r: !1, t: A }, tooltips: { r: !1, t: k }, keyboardSupport: { r: !0, t: V }, documentElement: { r: !1, t: M }, cssPrefix: { r: !0, t: O }, cssClasses: { r: !0, t: L } }, i = { connect: !1, direction: "ltr", behaviour: "tap", orientation: "horizontal", keyboardSupport: !0, cssPrefix: "noUi-", cssClasses: { target: "target", base: "base", origin: "origin", handle: "handle", handleLower: "handle-lower", handleUpper: "handle-upper", touchArea: "touch-area", horizontal: "horizontal", vertical: "vertical", background: "background", connect: "connect", connects: "connects", ltr: "ltr", rtl: "rtl", draggable: "draggable", drag: "state-drag", tap: "state-tap", active: "active", tooltip: "tooltip", pips: "pips", pipsHorizontal: "pips-horizontal", pipsVertical: "pips-vertical", marker: "marker", markerHorizontal: "marker-horizontal", markerVertical: "marker-vertical", markerNormal: "marker-normal", markerLarge: "marker-large", markerSub: "marker-sub", value: "value", valueHorizontal: "value-horizontal", valueVertical: "value-vertical", valueNormal: "value-normal", valueLarge: "value-large", valueSub: "value-sub" } }; e.format && !e.ariaFormat && (e.ariaFormat = e.format), Object.keys(n).forEach(function (t) { if (!s(e[t]) && void 0 === i[t]) { if (n[t].r) throw new Error("noUiSlider (" + lt + "): '" + t + "' is required."); return !0 } n[t].t(r, s(e[t]) ? e[t] : i[t]) }), r.pips = e.pips; var t = document.createElement("div"), o = void 0 !== t.style.msTransform, a = void 0 !== t.style.transform; r.transformRule = a ? "transform" : o ? "msTransform" : "webkitTransform"; return r.style = [["left", "top"], ["right", "bottom"]][r.dir][r.ort], r } function z(t, f, o) { var l, u, a, c, i, s, e, p, d = window.navigator.pointerEnabled ? { start: "pointerdown", move: "pointermove", end: "pointerup" } : window.navigator.msPointerEnabled ? { start: "MSPointerDown", move: "MSPointerMove", end: "MSPointerUp" } : { start: "mousedown touchstart", move: "mousemove touchmove", end: "mouseup touchend" }, h = window.CSS && CSS.supports && CSS.supports("touch-action", "none") && function () { var t = !1; try { var e = Object.defineProperty({}, "passive", { get: function () { t = !0 } }); window.addEventListener("test", null, e) } catch (t) { } return t }(), y = t, E = f.spectrum, m = [], g = [], v = [], b = 0, S = {}, x = t.ownerDocument, w = f.documentElement || x.documentElement, C = x.body, N = -1, U = 0, k = 1, P = 2, A = "rtl" === x.dir || 1 === f.ort ? 0 : 100; function V(t, e) { var r = x.createElement("div"); return e && ht(r, e), t.appendChild(r), r } function M(t, e) { var r = V(t, f.cssClasses.origin), n = V(r, f.cssClasses.handle); return V(n, f.cssClasses.touchArea), n.setAttribute("data-handle", e), f.keyboardSupport && (n.setAttribute("tabindex", "0"), n.addEventListener("keydown", function (t) { return function (t, e) { if (L() || z(e)) return !1; var r = ["Left", "Right"], n = ["Down", "Up"]; f.dir && !f.ort ? r.reverse() : f.ort && !f.dir && n.reverse(); var i = t.key.replace("Arrow", ""), o = i === n[0] || i === r[0], a = i === n[1] || i === r[1]; if (!o && !a) return !0; t.preventDefault(); var s = o ? 0 : 1, l = st(e)[s]; if (null === l) return !1; !1 === l && (l = E.getDefaultStep(g[e], o, 10)); return l = Math.max(l, 1e-7), l *= o ? -1 : 1, rt(e, E.toStepping(m[e] + l), !0, !0), J("slide", e), J("update", e), J("change", e), J("set", e), !1 }(t, e) })), n.setAttribute("role", "slider"), n.setAttribute("aria-orientation", f.ort ? "vertical" : "horizontal"), 0 === e ? ht(n, f.cssClasses.handleLower) : e === f.handles - 1 && ht(n, f.cssClasses.handleUpper), r } function O(t, e) { return !!e && V(t, f.cssClasses.connect) } function r(t, e) { return !!f.tooltips[e] && V(t.firstChild, f.cssClasses.tooltip) } function L() { return y.hasAttribute("disabled") } function z(t) { return u[t].hasAttribute("disabled") } function j() { i && (G("update.tooltips"), i.forEach(function (t) { t && ut(t) }), i = null) } function H() { j(), i = u.map(r), $("update.tooltips", function (t, e, r) { if (i[e]) { var n = t[e]; !0 !== f.tooltips[e] && (n = f.tooltips[e].to(r[e])), i[e].innerHTML = n } }) } function F(e, i, o) { var a = x.createElement("div"), s = []; s[U] = f.cssClasses.valueNormal, s[k] = f.cssClasses.valueLarge, s[P] = f.cssClasses.valueSub; var l = []; l[U] = f.cssClasses.markerNormal, l[k] = f.cssClasses.markerLarge, l[P] = f.cssClasses.markerSub; var u = [f.cssClasses.valueHorizontal, f.cssClasses.valueVertical], c = [f.cssClasses.markerHorizontal, f.cssClasses.markerVertical]; function p(t, e) { var r = e === f.cssClasses.value, n = r ? s : l; return e + " " + (r ? u : c)[f.ort] + " " + n[t] } return ht(a, f.cssClasses.pips), ht(a, 0 === f.ort ? f.cssClasses.pipsHorizontal : f.cssClasses.pipsVertical), Object.keys(e).forEach(function (t) { !function (t, e, r) { if ((r = i ? i(e, r) : r) !== N) { var n = V(a, !1); n.className = p(r, f.cssClasses.marker), n.style[f.style] = t + "%", U < r && ((n = V(a, !1)).className = p(r, f.cssClasses.value), n.setAttribute("data-value", e), n.style[f.style] = t + "%", n.innerHTML = o.to(e)) } }(t, e[t][0], e[t][1]) }), a } function D() { c && (ut(c), c = null) } function T(t) { D(); var m, g, v, b, e, r, S, x, w, n = t.mode, i = t.density || 1, o = t.filter || !1, a = function (t, e, r) { if ("range" === t || "steps" === t) return E.xVal; if ("count" === t) { if (e < 2) throw new Error("noUiSlider (" + lt + "): 'values' (>= 2) required for mode 'count'."); var n = e - 1, i = 100 / n; for (e = []; n--;)e[n] = n * i; e.push(100), t = "positions" } return "positions" === t ? e.map(function (t) { return E.fromStepping(r ? E.getStep(t) : t) }) : "values" === t ? r ? e.map(function (t) { return E.fromStepping(E.getStep(E.toStepping(t))) }) : e : void 0 }(n, t.values || !1, t.stepped || !1), s = (m = i, g = n, v = a, b = {}, e = E.xVal[0], r = E.xVal[E.xVal.length - 1], x = S = !1, w = 0, (v = v.slice().sort(function (t, e) { return t - e }).filter(function (t) { return !this[t] && (this[t] = !0) }, {}))[0] !== e && (v.unshift(e), S = !0), v[v.length - 1] !== r && (v.push(r), x = !0), v.forEach(function (t, e) { var r, n, i, o, a, s, l, u, c, p, f = t, d = v[e + 1], h = "steps" === g; if (h && (r = E.xNumSteps[e]), r || (r = d - f), !1 !== f && void 0 !== d) for (r = Math.max(r, 1e-7), n = f; n <= d; n = (n + r).toFixed(7) / 1) { for (u = (a = (o = E.toStepping(n)) - w) / m, p = a / (c = Math.round(u)), i = 1; i <= c; i += 1)b[(s = w + i * p).toFixed(5)] = [E.fromStepping(s), 0]; l = -1 < v.indexOf(n) ? k : h ? P : U, !e && S && (l = 0), n === d && x || (b[o.toFixed(5)] = [n, l]), w = o } }), b), l = t.format || { to: Math.round }; return c = y.appendChild(F(s, o, l)) } function R() { var t = l.getBoundingClientRect(), e = "offset" + ["Width", "Height"][f.ort]; return 0 === f.ort ? t.width || l[e] : t.height || l[e] } function B(n, i, o, a) { var e = function (t) { return !!(t = function (t, e, r) { var n, i, o = 0 === t.type.indexOf("touch"), a = 0 === t.type.indexOf("mouse"), s = 0 === t.type.indexOf("pointer"); 0 === t.type.indexOf("MSPointer") && (s = !0); if (o) { var l = function (t) { return t.target === r || r.contains(t.target) }; if ("touchstart" === t.type) { var u = Array.prototype.filter.call(t.touches, l); if (1 < u.length) return !1; n = u[0].pageX, i = u[0].pageY } else { var c = Array.prototype.find.call(t.changedTouches, l); if (!c) return !1; n = c.pageX, i = c.pageY } } e = e || gt(x), (a || s) && (n = t.clientX + e.x, i = t.clientY + e.y); return t.pageOffset = e, t.points = [n, i], t.cursor = a || s, t }(t, a.pageOffset, a.target || i)) && (!(L() && !a.doNotReject) && (e = y, r = f.cssClasses.tap, !((e.classList ? e.classList.contains(r) : new RegExp("\\b" + r + "\\b").test(e.className)) && !a.doNotReject) && (!(n === d.start && void 0 !== t.buttons && 1 < t.buttons) && ((!a.hover || !t.buttons) && (h || t.preventDefault(), t.calcPoint = t.points[f.ort], void o(t, a)))))); var e, r }, r = []; return n.split(" ").forEach(function (t) { i.addEventListener(t, e, !!h && { passive: !0 }), r.push([t, e]) }), r } function q(t) { var e, r, n, i, o, a, s = 100 * (t - (e = l, r = f.ort, n = e.getBoundingClientRect(), i = e.ownerDocument, o = i.documentElement, a = gt(i), /webkit.*Chrome.*Mobile/i.test(navigator.userAgent) && (a.x = 0), r ? n.top + a.y - o.clientTop : n.left + a.x - o.clientLeft)) / R(); return s = ft(s), f.dir ? 100 - s : s } function X(t, e) { "mouseout" === t.type && "HTML" === t.target.nodeName && null === t.relatedTarget && _(t, e) } function Y(t, e) { if (-1 === navigator.appVersion.indexOf("MSIE 9") && 0 === t.buttons && 0 !== e.buttonsProperty) return _(t, e); var r = (f.dir ? -1 : 1) * (t.calcPoint - e.startCalcPoint); Z(0 < r, 100 * r / e.baseSize, e.locations, e.handleNumbers) } function _(t, e) { e.handle && (mt(e.handle, f.cssClasses.active), b -= 1), e.listeners.forEach(function (t) { w.removeEventListener(t[0], t[1]) }), 0 === b && (mt(y, f.cssClasses.drag), et(), t.cursor && (C.style.cursor = "", C.removeEventListener("selectstart", ct))), e.handleNumbers.forEach(function (t) { J("change", t), J("set", t), J("end", t) }) } function I(t, e) { if (e.handleNumbers.some(z)) return !1; var r; 1 === e.handleNumbers.length && (r = u[e.handleNumbers[0]].children[0], b += 1, ht(r, f.cssClasses.active)); t.stopPropagation(); var n = [], i = B(d.move, w, Y, { target: t.target, handle: r, listeners: n, startCalcPoint: t.calcPoint, baseSize: R(), pageOffset: t.pageOffset, handleNumbers: e.handleNumbers, buttonsProperty: t.buttons, locations: g.slice() }), o = B(d.end, w, _, { target: t.target, handle: r, listeners: n, doNotReject: !0, handleNumbers: e.handleNumbers }), a = B("mouseout", w, X, { target: t.target, handle: r, listeners: n, doNotReject: !0, handleNumbers: e.handleNumbers }); n.push.apply(n, i.concat(o, a)), t.cursor && (C.style.cursor = getComputedStyle(t.target).cursor, 1 < u.length && ht(y, f.cssClasses.drag), C.addEventListener("selectstart", ct, !1)), e.handleNumbers.forEach(function (t) { J("start", t) }) } function n(t) { t.stopPropagation(); var i, o, a, e = q(t.calcPoint), r = (i = e, a = !(o = 100), u.forEach(function (t, e) { if (!z(e)) { var r = g[e], n = Math.abs(r - i); (n < o || n <= o && r < i || 100 === n && 100 === o) && (a = e, o = n) } }), a); if (!1 === r) return !1; f.events.snap || pt(y, f.cssClasses.tap, f.animationDuration), rt(r, e, !0, !0), et(), J("slide", r, !0), J("update", r, !0), J("change", r, !0), J("set", r, !0), f.events.snap && I(t, { handleNumbers: [r] }) } function W(t) { var e = q(t.calcPoint), r = E.getStep(e), n = E.fromStepping(r); Object.keys(S).forEach(function (t) { "hover" === t.split(".")[0] && S[t].forEach(function (t) { t.call(s, n) }) }) } function $(t, e) { S[t] = S[t] || [], S[t].push(e), "update" === t.split(".")[0] && u.forEach(function (t, e) { J("update", e) }) } function G(t) { var n = t && t.split(".")[0], i = n && t.substring(n.length); Object.keys(S).forEach(function (t) { var e = t.split(".")[0], r = t.substring(e.length); n && n !== e || i && i !== r || delete S[t] }) } function J(r, n, i) { Object.keys(S).forEach(function (t) { var e = t.split(".")[0]; r === e && S[t].forEach(function (t) { t.call(s, m.map(f.format.to), n, m.slice(), i || !1, g.slice()) }) }) } function K(t, e, r, n, i, o) { return 1 < u.length && !f.events.unconstrained && (n && 0 < e && (r = Math.max(r, t[e - 1] + f.margin)), i && e < u.length - 1 && (r = Math.min(r, t[e + 1] - f.margin))), 1 < u.length && f.limit && (n && 0 < e && (r = Math.min(r, t[e - 1] + f.limit)), i && e < u.length - 1 && (r = Math.max(r, t[e + 1] - f.limit))), f.padding && (0 === e && (r = Math.max(r, f.padding[0])), e === u.length - 1 && (r = Math.min(r, 100 - f.padding[1]))), !((r = ft(r = E.getStep(r))) === t[e] && !o) && r } function Q(t, e) { var r = f.ort; return (r ? e : t) + ", " + (r ? t : e) } function Z(t, n, r, e) { var i = r.slice(), o = [!t, t], a = [t, !t]; e = e.slice(), t && e.reverse(), 1 < e.length ? e.forEach(function (t, e) { var r = K(i, t, i[t] + n, o[e], a[e], !1); !1 === r ? n = 0 : (n = r - i[t], i[t] = r) }) : o = a = [!0]; var s = !1; e.forEach(function (t, e) { s = rt(t, r[t] + n, o[e], a[e]) || s }), s && e.forEach(function (t) { J("update", t), J("slide", t) }) } function tt(t, e) { return f.dir ? 100 - t - e : t } function et() { v.forEach(function (t) { var e = 50 < g[t] ? -1 : 1, r = 3 + (u.length + e * t); u[t].style.zIndex = r }) } function rt(t, e, r, n) { return !1 !== (e = K(g, t, e, r, n, !1)) && (function (t, e) { g[t] = e, m[t] = E.fromStepping(e); var r = "translate(" + Q(10 * (tt(e, 0) - A) + "%", "0") + ")"; u[t].style[f.transformRule] = r, nt(t), nt(t + 1) }(t, e), !0) } function nt(t) { if (a[t]) { var e = 0, r = 100; 0 !== t && (e = g[t - 1]), t !== a.length - 1 && (r = g[t]); var n = r - e, i = "translate(" + Q(tt(e, n) + "%", "0") + ")", o = "scale(" + Q(n / 100, "1") + ")"; a[t].style[f.transformRule] = i + " " + o } } function it(t, e) { return null === t || !1 === t || void 0 === t ? g[e] : ("number" == typeof t && (t = String(t)), t = f.format.from(t), !1 === (t = E.toStepping(t)) || isNaN(t) ? g[e] : t) } function ot(t, e) { var r = dt(t), n = void 0 === g[0]; e = void 0 === e || !!e, f.animate && !n && pt(y, f.cssClasses.tap, f.animationDuration), v.forEach(function (t) { rt(t, it(r[t], t), !0, !1) }), v.forEach(function (t) { rt(t, g[t], !0, !0) }), et(), v.forEach(function (t) { J("update", t), null !== r[t] && e && J("set", t) }) } function at() { var t = m.map(f.format.to); return 1 === t.length ? t[0] : t } function st(t) { var e = g[t], r = E.getNearbySteps(e), n = m[t], i = r.thisStep.step, o = null; if (f.snap) return [n - r.stepBefore.startValue || null, r.stepAfter.startValue - n || null]; !1 !== i && n + i > r.stepAfter.startValue && (i = r.stepAfter.startValue - n), o = n > r.thisStep.startValue ? r.thisStep.step : !1 !== r.stepBefore.step && n - r.stepBefore.highestStep, 100 === e ? i = null : 0 === e && (o = null); var a = E.countStepDecimals(); return null !== i && !1 !== i && (i = Number(i.toFixed(a))), null !== o && !1 !== o && (o = Number(o.toFixed(a))), [o, i] } return ht(e = y, f.cssClasses.target), 0 === f.dir ? ht(e, f.cssClasses.ltr) : ht(e, f.cssClasses.rtl), 0 === f.ort ? ht(e, f.cssClasses.horizontal) : ht(e, f.cssClasses.vertical), l = V(e, f.cssClasses.base), function (t, e) { var r = V(e, f.cssClasses.connects); u = [], (a = []).push(O(r, t[0])); for (var n = 0; n < f.handles; n++)u.push(M(e, n)), v[n] = n, a.push(O(r, t[n + 1])) }(f.connect, l), (p = f.events).fixed || u.forEach(function (t, e) { B(d.start, t.children[0], I, { handleNumbers: [e] }) }), p.tap && B(d.start, l, n, {}), p.hover && B(d.move, l, W, { hover: !0 }), p.drag && a.forEach(function (t, e) { if (!1 !== t && 0 !== e && e !== a.length - 1) { var r = u[e - 1], n = u[e], i = [t]; ht(t, f.cssClasses.draggable), p.fixed && (i.push(r.children[0]), i.push(n.children[0])), i.forEach(function (t) { B(d.start, t, I, { handles: [r, n], handleNumbers: [e - 1, e] }) }) } }), ot(f.start), f.pips && T(f.pips), f.tooltips && H(), $("update", function (t, e, a, r, s) { v.forEach(function (t) { var e = u[t], r = K(g, t, 0, !0, !0, !0), n = K(g, t, 100, !0, !0, !0), i = s[t], o = f.ariaFormat.to(a[t]); r = E.fromStepping(r).toFixed(1), n = E.fromStepping(n).toFixed(1), i = E.fromStepping(i).toFixed(1), e.children[0].setAttribute("aria-valuemin", r), e.children[0].setAttribute("aria-valuemax", n), e.children[0].setAttribute("aria-valuenow", i), e.children[0].setAttribute("aria-valuetext", o) }) }), s = { destroy: function () { for (var t in f.cssClasses) f.cssClasses.hasOwnProperty(t) && mt(y, f.cssClasses[t]); for (; y.firstChild;)y.removeChild(y.firstChild); delete y.noUiSlider }, steps: function () { return v.map(st) }, on: $, off: G, get: at, set: ot, setHandle: function (t, e, r) { if (!(0 <= (t = Number(t)) && t < v.length)) throw new Error("noUiSlider (" + lt + "): invalid handle number, got: " + t); rt(t, it(e, t), !0, !0), J("update", t), r && J("set", t) }, reset: function (t) { ot(f.start, t) }, __moveHandles: function (t, e, r) { Z(t, e, g, r) }, options: o, updateOptions: function (e, t) { var r = at(), n = ["margin", "limit", "padding", "range", "animate", "snap", "step", "format", "pips", "tooltips"]; n.forEach(function (t) { void 0 !== e[t] && (o[t] = e[t]) }); var i = vt(o); n.forEach(function (t) { void 0 !== e[t] && (f[t] = i[t]) }), E = i.spectrum, f.margin = i.margin, f.limit = i.limit, f.padding = i.padding, f.pips ? T(f.pips) : D(), f.tooltips ? H() : j(), g = [], ot(e.start || r, t) }, target: y, removePips: D, removeTooltips: j, pips: T } } return { __spectrum: l, version: lt, create: function (t, e) { if (!t || !t.nodeName) throw new Error("noUiSlider (" + lt + "): create requires a single element, got: " + t); if (t.noUiSlider) throw new Error("noUiSlider (" + lt + "): Slider was already initialized."); var r = z(t, vt(e), e); return t.noUiSlider = r } } });
/*!
 * VERSION: 1.16.1
 * DATE: 2015-03-13
 * UPDATES AND DOCS AT: http://greensock.com
 *
 * @license Copyright (c) 2008-2015, GreenSock. All rights reserved.
 * This work is subject to the terms at http://greensock.com/standard-license or for
 * Club GreenSock members, the software agreement that was issued with your membership.
 * 
 * @author: Jack Doyle, jack@greensock.com
 */
(function (t, e) { "use strict"; var i = t.GreenSockGlobals = t.GreenSockGlobals || t; if (!i.TweenLite) { var s, r, n, a, o, l = function (t) { var e, s = t.split("."), r = i; for (e = 0; s.length > e; e++)r[s[e]] = r = r[s[e]] || {}; return r }, h = l("com.greensock"), _ = 1e-10, u = function (t) { var e, i = [], s = t.length; for (e = 0; e !== s; i.push(t[e++])); return i }, m = function () { }, f = function () { var t = Object.prototype.toString, e = t.call([]); return function (i) { return null != i && (i instanceof Array || "object" == typeof i && !!i.push && t.call(i) === e) } }(), c = {}, p = function (s, r, n, a) { this.sc = c[s] ? c[s].sc : [], c[s] = this, this.gsClass = null, this.func = n; var o = []; this.check = function (h) { for (var _, u, m, f, d = r.length, v = d; --d > -1;)(_ = c[r[d]] || new p(r[d], [])).gsClass ? (o[d] = _.gsClass, v--) : h && _.sc.push(this); if (0 === v && n) for (u = ("com.greensock." + s).split("."), m = u.pop(), f = l(u.join("."))[m] = this.gsClass = n.apply(n, o), a && (i[m] = f, "function" == typeof define && define.amd ? define((t.GreenSockAMDPath ? t.GreenSockAMDPath + "/" : "") + s.split(".").pop(), [], function () { return f }) : s === e && "undefined" != typeof module && module.exports && (module.exports = f)), d = 0; this.sc.length > d; d++)this.sc[d].check() }, this.check(!0) }, d = t._gsDefine = function (t, e, i, s) { return new p(t, e, i, s) }, v = h._class = function (t, e, i) { return e = e || function () { }, d(t, [], function () { return e }, i), e }; d.globals = i; var g = [0, 0, 1, 1], T = [], y = v("easing.Ease", function (t, e, i, s) { this._func = t, this._type = i || 0, this._power = s || 0, this._params = e ? g.concat(e) : g }, !0), w = y.map = {}, P = y.register = function (t, e, i, s) { for (var r, n, a, o, l = e.split(","), _ = l.length, u = (i || "easeIn,easeOut,easeInOut").split(","); --_ > -1;)for (n = l[_], r = s ? v("easing." + n, null, !0) : h.easing[n] || {}, a = u.length; --a > -1;)o = u[a], w[n + "." + o] = w[o + n] = r[o] = t.getRatio ? t : t[o] || new t }; for (n = y.prototype, n._calcEnd = !1, n.getRatio = function (t) { if (this._func) return this._params[0] = t, this._func.apply(null, this._params); var e = this._type, i = this._power, s = 1 === e ? 1 - t : 2 === e ? t : .5 > t ? 2 * t : 2 * (1 - t); return 1 === i ? s *= s : 2 === i ? s *= s * s : 3 === i ? s *= s * s * s : 4 === i && (s *= s * s * s * s), 1 === e ? 1 - s : 2 === e ? s : .5 > t ? s / 2 : 1 - s / 2 }, s = ["Linear", "Quad", "Cubic", "Quart", "Quint,Strong"], r = s.length; --r > -1;)n = s[r] + ",Power" + r, P(new y(null, null, 1, r), n, "easeOut", !0), P(new y(null, null, 2, r), n, "easeIn" + (0 === r ? ",easeNone" : "")), P(new y(null, null, 3, r), n, "easeInOut"); w.linear = h.easing.Linear.easeIn, w.swing = h.easing.Quad.easeInOut; var b = v("events.EventDispatcher", function (t) { this._listeners = {}, this._eventTarget = t || this }); n = b.prototype, n.addEventListener = function (t, e, i, s, r) { r = r || 0; var n, l, h = this._listeners[t], _ = 0; for (null == h && (this._listeners[t] = h = []), l = h.length; --l > -1;)n = h[l], n.c === e && n.s === i ? h.splice(l, 1) : 0 === _ && r > n.pr && (_ = l + 1); h.splice(_, 0, { c: e, s: i, up: s, pr: r }), this !== a || o || a.wake() }, n.removeEventListener = function (t, e) { var i, s = this._listeners[t]; if (s) for (i = s.length; --i > -1;)if (s[i].c === e) return s.splice(i, 1), void 0 }, n.dispatchEvent = function (t) { var e, i, s, r = this._listeners[t]; if (r) for (e = r.length, i = this._eventTarget; --e > -1;)s = r[e], s && (s.up ? s.c.call(s.s || i, { type: t, target: i }) : s.c.call(s.s || i)) }; var k = t.requestAnimationFrame, S = t.cancelAnimationFrame, A = Date.now || function () { return (new Date).getTime() }, x = A(); for (s = ["ms", "moz", "webkit", "o"], r = s.length; --r > -1 && !k;)k = t[s[r] + "RequestAnimationFrame"], S = t[s[r] + "CancelAnimationFrame"] || t[s[r] + "CancelRequestAnimationFrame"]; v("Ticker", function (t, e) { var i, s, r, n, l, h = this, u = A(), f = e !== !1 && k, c = 500, p = 33, d = "tick", v = function (t) { var e, a, o = A() - x; o > c && (u += o - p), x += o, h.time = (x - u) / 1e3, e = h.time - l, (!i || e > 0 || t === !0) && (h.frame++, l += e + (e >= n ? .004 : n - e), a = !0), t !== !0 && (r = s(v)), a && h.dispatchEvent(d) }; b.call(h), h.time = h.frame = 0, h.tick = function () { v(!0) }, h.lagSmoothing = function (t, e) { c = t || 1 / _, p = Math.min(e, c, 0) }, h.sleep = function () { null != r && (f && S ? S(r) : clearTimeout(r), s = m, r = null, h === a && (o = !1)) }, h.wake = function () { null !== r ? h.sleep() : h.frame > 10 && (x = A() - c + 5), s = 0 === i ? m : f && k ? k : function (t) { return setTimeout(t, 0 | 1e3 * (l - h.time) + 1) }, h === a && (o = !0), v(2) }, h.fps = function (t) { return arguments.length ? (i = t, n = 1 / (i || 60), l = this.time + n, h.wake(), void 0) : i }, h.useRAF = function (t) { return arguments.length ? (h.sleep(), f = t, h.fps(i), void 0) : f }, h.fps(t), setTimeout(function () { f && 5 > h.frame && h.useRAF(!1) }, 1500) }), n = h.Ticker.prototype = new h.events.EventDispatcher, n.constructor = h.Ticker; var R = v("core.Animation", function (t, e) { if (this.vars = e = e || {}, this._duration = this._totalDuration = t || 0, this._delay = Number(e.delay) || 0, this._timeScale = 1, this._active = e.immediateRender === !0, this.data = e.data, this._reversed = e.reversed === !0, B) { o || a.wake(); var i = this.vars.useFrames ? q : B; i.add(this, i._time), this.vars.paused && this.paused(!0) } }); a = R.ticker = new h.Ticker, n = R.prototype, n._dirty = n._gc = n._initted = n._paused = !1, n._totalTime = n._time = 0, n._rawPrevTime = -1, n._next = n._last = n._onUpdate = n._timeline = n.timeline = null, n._paused = !1; var C = function () { o && A() - x > 2e3 && a.wake(), setTimeout(C, 2e3) }; C(), n.play = function (t, e) { return null != t && this.seek(t, e), this.reversed(!1).paused(!1) }, n.pause = function (t, e) { return null != t && this.seek(t, e), this.paused(!0) }, n.resume = function (t, e) { return null != t && this.seek(t, e), this.paused(!1) }, n.seek = function (t, e) { return this.totalTime(Number(t), e !== !1) }, n.restart = function (t, e) { return this.reversed(!1).paused(!1).totalTime(t ? -this._delay : 0, e !== !1, !0) }, n.reverse = function (t, e) { return null != t && this.seek(t || this.totalDuration(), e), this.reversed(!0).paused(!1) }, n.render = function () { }, n.invalidate = function () { return this._time = this._totalTime = 0, this._initted = this._gc = !1, this._rawPrevTime = -1, (this._gc || !this.timeline) && this._enabled(!0), this }, n.isActive = function () { var t, e = this._timeline, i = this._startTime; return !e || !this._gc && !this._paused && e.isActive() && (t = e.rawTime()) >= i && i + this.totalDuration() / this._timeScale > t }, n._enabled = function (t, e) { return o || a.wake(), this._gc = !t, this._active = this.isActive(), e !== !0 && (t && !this.timeline ? this._timeline.add(this, this._startTime - this._delay) : !t && this.timeline && this._timeline._remove(this, !0)), !1 }, n._kill = function () { return this._enabled(!1, !1) }, n.kill = function (t, e) { return this._kill(t, e), this }, n._uncache = function (t) { for (var e = t ? this : this.timeline; e;)e._dirty = !0, e = e.timeline; return this }, n._swapSelfInParams = function (t) { for (var e = t.length, i = t.concat(); --e > -1;)"{self}" === t[e] && (i[e] = this); return i }, n.eventCallback = function (t, e, i, s) { if ("on" === (t || "").substr(0, 2)) { var r = this.vars; if (1 === arguments.length) return r[t]; null == e ? delete r[t] : (r[t] = e, r[t + "Params"] = f(i) && -1 !== i.join("").indexOf("{self}") ? this._swapSelfInParams(i) : i, r[t + "Scope"] = s), "onUpdate" === t && (this._onUpdate = e) } return this }, n.delay = function (t) { return arguments.length ? (this._timeline.smoothChildTiming && this.startTime(this._startTime + t - this._delay), this._delay = t, this) : this._delay }, n.duration = function (t) { return arguments.length ? (this._duration = this._totalDuration = t, this._uncache(!0), this._timeline.smoothChildTiming && this._time > 0 && this._time < this._duration && 0 !== t && this.totalTime(this._totalTime * (t / this._duration), !0), this) : (this._dirty = !1, this._duration) }, n.totalDuration = function (t) { return this._dirty = !1, arguments.length ? this.duration(t) : this._totalDuration }, n.time = function (t, e) { return arguments.length ? (this._dirty && this.totalDuration(), this.totalTime(t > this._duration ? this._duration : t, e)) : this._time }, n.totalTime = function (t, e, i) { if (o || a.wake(), !arguments.length) return this._totalTime; if (this._timeline) { if (0 > t && !i && (t += this.totalDuration()), this._timeline.smoothChildTiming) { this._dirty && this.totalDuration(); var s = this._totalDuration, r = this._timeline; if (t > s && !i && (t = s), this._startTime = (this._paused ? this._pauseTime : r._time) - (this._reversed ? s - t : t) / this._timeScale, r._dirty || this._uncache(!1), r._timeline) for (; r._timeline;)r._timeline._time !== (r._startTime + r._totalTime) / r._timeScale && r.totalTime(r._totalTime, !0), r = r._timeline } this._gc && this._enabled(!0, !1), (this._totalTime !== t || 0 === this._duration) && (this.render(t, e, !1), z.length && $()) } return this }, n.progress = n.totalProgress = function (t, e) { return arguments.length ? this.totalTime(this.duration() * t, e) : this._time / this.duration() }, n.startTime = function (t) { return arguments.length ? (t !== this._startTime && (this._startTime = t, this.timeline && this.timeline._sortChildren && this.timeline.add(this, t - this._delay)), this) : this._startTime }, n.endTime = function (t) { return this._startTime + (0 != t ? this.totalDuration() : this.duration()) / this._timeScale }, n.timeScale = function (t) { if (!arguments.length) return this._timeScale; if (t = t || _, this._timeline && this._timeline.smoothChildTiming) { var e = this._pauseTime, i = e || 0 === e ? e : this._timeline.totalTime(); this._startTime = i - (i - this._startTime) * this._timeScale / t } return this._timeScale = t, this._uncache(!1) }, n.reversed = function (t) { return arguments.length ? (t != this._reversed && (this._reversed = t, this.totalTime(this._timeline && !this._timeline.smoothChildTiming ? this.totalDuration() - this._totalTime : this._totalTime, !0)), this) : this._reversed }, n.paused = function (t) { if (!arguments.length) return this._paused; var e, i, s = this._timeline; return t != this._paused && s && (o || t || a.wake(), e = s.rawTime(), i = e - this._pauseTime, !t && s.smoothChildTiming && (this._startTime += i, this._uncache(!1)), this._pauseTime = t ? e : null, this._paused = t, this._active = this.isActive(), !t && 0 !== i && this._initted && this.duration() && this.render(s.smoothChildTiming ? this._totalTime : (e - this._startTime) / this._timeScale, !0, !0)), this._gc && !t && this._enabled(!0, !1), this }; var D = v("core.SimpleTimeline", function (t) { R.call(this, 0, t), this.autoRemoveChildren = this.smoothChildTiming = !0 }); n = D.prototype = new R, n.constructor = D, n.kill()._gc = !1, n._first = n._last = n._recent = null, n._sortChildren = !1, n.add = n.insert = function (t, e) { var i, s; if (t._startTime = Number(e || 0) + t._delay, t._paused && this !== t._timeline && (t._pauseTime = t._startTime + (this.rawTime() - t._startTime) / t._timeScale), t.timeline && t.timeline._remove(t, !0), t.timeline = t._timeline = this, t._gc && t._enabled(!0, !0), i = this._last, this._sortChildren) for (s = t._startTime; i && i._startTime > s;)i = i._prev; return i ? (t._next = i._next, i._next = t) : (t._next = this._first, this._first = t), t._next ? t._next._prev = t : this._last = t, t._prev = i, this._recent = t, this._timeline && this._uncache(!0), this }, n._remove = function (t, e) { return t.timeline === this && (e || t._enabled(!1, !0), t._prev ? t._prev._next = t._next : this._first === t && (this._first = t._next), t._next ? t._next._prev = t._prev : this._last === t && (this._last = t._prev), t._next = t._prev = t.timeline = null, t === this._recent && (this._recent = this._last), this._timeline && this._uncache(!0)), this }, n.render = function (t, e, i) { var s, r = this._first; for (this._totalTime = this._time = this._rawPrevTime = t; r;)s = r._next, (r._active || t >= r._startTime && !r._paused) && (r._reversed ? r.render((r._dirty ? r.totalDuration() : r._totalDuration) - (t - r._startTime) * r._timeScale, e, i) : r.render((t - r._startTime) * r._timeScale, e, i)), r = s }, n.rawTime = function () { return o || a.wake(), this._totalTime }; var I = v("TweenLite", function (e, i, s) { if (R.call(this, i, s), this.render = I.prototype.render, null == e) throw "Cannot tween a null target."; this.target = e = "string" != typeof e ? e : I.selector(e) || e; var r, n, a, o = e.jquery || e.length && e !== t && e[0] && (e[0] === t || e[0].nodeType && e[0].style && !e.nodeType), l = this.vars.overwrite; if (this._overwrite = l = null == l ? Q[I.defaultOverwrite] : "number" == typeof l ? l >> 0 : Q[l], (o || e instanceof Array || e.push && f(e)) && "number" != typeof e[0]) for (this._targets = a = u(e), this._propLookup = [], this._siblings = [], r = 0; a.length > r; r++)n = a[r], n ? "string" != typeof n ? n.length && n !== t && n[0] && (n[0] === t || n[0].nodeType && n[0].style && !n.nodeType) ? (a.splice(r--, 1), this._targets = a = a.concat(u(n))) : (this._siblings[r] = K(n, this, !1), 1 === l && this._siblings[r].length > 1 && J(n, this, null, 1, this._siblings[r])) : (n = a[r--] = I.selector(n), "string" == typeof n && a.splice(r + 1, 1)) : a.splice(r--, 1); else this._propLookup = {}, this._siblings = K(e, this, !1), 1 === l && this._siblings.length > 1 && J(e, this, null, 1, this._siblings); (this.vars.immediateRender || 0 === i && 0 === this._delay && this.vars.immediateRender !== !1) && (this._time = -_, this.render(-this._delay)) }, !0), E = function (e) { return e && e.length && e !== t && e[0] && (e[0] === t || e[0].nodeType && e[0].style && !e.nodeType) }, O = function (t, e) { var i, s = {}; for (i in t) G[i] || i in e && "transform" !== i && "x" !== i && "y" !== i && "width" !== i && "height" !== i && "className" !== i && "border" !== i || !(!U[i] || U[i] && U[i]._autoCSS) || (s[i] = t[i], delete t[i]); t.css = s }; n = I.prototype = new R, n.constructor = I, n.kill()._gc = !1, n.ratio = 0, n._firstPT = n._targets = n._overwrittenProps = n._startAt = null, n._notifyPluginsOfEnabled = n._lazy = !1, I.version = "1.16.1", I.defaultEase = n._ease = new y(null, null, 1, 1), I.defaultOverwrite = "auto", I.ticker = a, I.autoSleep = 120, I.lagSmoothing = function (t, e) { a.lagSmoothing(t, e) }, I.selector = t.$ || t.jQuery || function (e) { var i = t.$ || t.jQuery; return i ? (I.selector = i, i(e)) : "undefined" == typeof document ? e : document.querySelectorAll ? document.querySelectorAll(e) : document.getElementById("#" === e.charAt(0) ? e.substr(1) : e) }; var z = [], L = {}, N = I._internals = { isArray: f, isSelector: E, lazyTweens: z }, U = I._plugins = {}, F = N.tweenLookup = {}, j = 0, G = N.reservedProps = { ease: 1, delay: 1, overwrite: 1, onComplete: 1, onCompleteParams: 1, onCompleteScope: 1, useFrames: 1, runBackwards: 1, startAt: 1, onUpdate: 1, onUpdateParams: 1, onUpdateScope: 1, onStart: 1, onStartParams: 1, onStartScope: 1, onReverseComplete: 1, onReverseCompleteParams: 1, onReverseCompleteScope: 1, onRepeat: 1, onRepeatParams: 1, onRepeatScope: 1, easeParams: 1, yoyo: 1, immediateRender: 1, repeat: 1, repeatDelay: 1, data: 1, paused: 1, reversed: 1, autoCSS: 1, lazy: 1, onOverwrite: 1 }, Q = { none: 0, all: 1, auto: 2, concurrent: 3, allOnStart: 4, preexisting: 5, "true": 1, "false": 0 }, q = R._rootFramesTimeline = new D, B = R._rootTimeline = new D, M = 30, $ = N.lazyRender = function () { var t, e = z.length; for (L = {}; --e > -1;)t = z[e], t && t._lazy !== !1 && (t.render(t._lazy[0], t._lazy[1], !0), t._lazy = !1); z.length = 0 }; B._startTime = a.time, q._startTime = a.frame, B._active = q._active = !0, setTimeout($, 1), R._updateRoot = I.render = function () { var t, e, i; if (z.length && $(), B.render((a.time - B._startTime) * B._timeScale, !1, !1), q.render((a.frame - q._startTime) * q._timeScale, !1, !1), z.length && $(), a.frame >= M) { M = a.frame + (parseInt(I.autoSleep, 10) || 120); for (i in F) { for (e = F[i].tweens, t = e.length; --t > -1;)e[t]._gc && e.splice(t, 1); 0 === e.length && delete F[i] } if (i = B._first, (!i || i._paused) && I.autoSleep && !q._first && 1 === a._listeners.tick.length) { for (; i && i._paused;)i = i._next; i || a.sleep() } } }, a.addEventListener("tick", R._updateRoot); var K = function (t, e, i) { var s, r, n = t._gsTweenID; if (F[n || (t._gsTweenID = n = "t" + j++)] || (F[n] = { target: t, tweens: [] }), e && (s = F[n].tweens, s[r = s.length] = e, i)) for (; --r > -1;)s[r] === e && s.splice(r, 1); return F[n].tweens }, H = function (t, e, i, s) { var r, n, a = t.vars.onOverwrite; return a && (r = a(t, e, i, s)), a = I.onOverwrite, a && (n = a(t, e, i, s)), r !== !1 && n !== !1 }, J = function (t, e, i, s, r) { var n, a, o, l; if (1 === s || s >= 4) { for (l = r.length, n = 0; l > n; n++)if ((o = r[n]) !== e) o._gc || H(o, e) && o._enabled(!1, !1) && (a = !0); else if (5 === s) break; return a } var h, u = e._startTime + _, m = [], f = 0, c = 0 === e._duration; for (n = r.length; --n > -1;)(o = r[n]) === e || o._gc || o._paused || (o._timeline !== e._timeline ? (h = h || V(e, 0, c), 0 === V(o, h, c) && (m[f++] = o)) : u >= o._startTime && o._startTime + o.totalDuration() / o._timeScale > u && ((c || !o._initted) && 2e-10 >= u - o._startTime || (m[f++] = o))); for (n = f; --n > -1;)if (o = m[n], 2 === s && o._kill(i, t, e) && (a = !0), 2 !== s || !o._firstPT && o._initted) { if (2 !== s && !H(o, e)) continue; o._enabled(!1, !1) && (a = !0) } return a }, V = function (t, e, i) { for (var s = t._timeline, r = s._timeScale, n = t._startTime; s._timeline;) { if (n += s._startTime, r *= s._timeScale, s._paused) return -100; s = s._timeline } return n /= r, n > e ? n - e : i && n === e || !t._initted && 2 * _ > n - e ? _ : (n += t.totalDuration() / t._timeScale / r) > e + _ ? 0 : n - e - _ }; n._init = function () { var t, e, i, s, r, n = this.vars, a = this._overwrittenProps, o = this._duration, l = !!n.immediateRender, h = n.ease; if (n.startAt) { this._startAt && (this._startAt.render(-1, !0), this._startAt.kill()), r = {}; for (s in n.startAt) r[s] = n.startAt[s]; if (r.overwrite = !1, r.immediateRender = !0, r.lazy = l && n.lazy !== !1, r.startAt = r.delay = null, this._startAt = I.to(this.target, 0, r), l) if (this._time > 0) this._startAt = null; else if (0 !== o) return } else if (n.runBackwards && 0 !== o) if (this._startAt) this._startAt.render(-1, !0), this._startAt.kill(), this._startAt = null; else { 0 !== this._time && (l = !1), i = {}; for (s in n) G[s] && "autoCSS" !== s || (i[s] = n[s]); if (i.overwrite = 0, i.data = "isFromStart", i.lazy = l && n.lazy !== !1, i.immediateRender = l, this._startAt = I.to(this.target, 0, i), l) { if (0 === this._time) return } else this._startAt._init(), this._startAt._enabled(!1), this.vars.immediateRender && (this._startAt = null) } if (this._ease = h = h ? h instanceof y ? h : "function" == typeof h ? new y(h, n.easeParams) : w[h] || I.defaultEase : I.defaultEase, n.easeParams instanceof Array && h.config && (this._ease = h.config.apply(h, n.easeParams)), this._easeType = this._ease._type, this._easePower = this._ease._power, this._firstPT = null, this._targets) for (t = this._targets.length; --t > -1;)this._initProps(this._targets[t], this._propLookup[t] = {}, this._siblings[t], a ? a[t] : null) && (e = !0); else e = this._initProps(this.target, this._propLookup, this._siblings, a); if (e && I._onPluginEvent("_onInitAllProps", this), a && (this._firstPT || "function" != typeof this.target && this._enabled(!1, !1)), n.runBackwards) for (i = this._firstPT; i;)i.s += i.c, i.c = -i.c, i = i._next; this._onUpdate = n.onUpdate, this._initted = !0 }, n._initProps = function (e, i, s, r) { var n, a, o, l, h, _; if (null == e) return !1; L[e._gsTweenID] && $(), this.vars.css || e.style && e !== t && e.nodeType && U.css && this.vars.autoCSS !== !1 && O(this.vars, e); for (n in this.vars) { if (_ = this.vars[n], G[n]) _ && (_ instanceof Array || _.push && f(_)) && -1 !== _.join("").indexOf("{self}") && (this.vars[n] = _ = this._swapSelfInParams(_, this)); else if (U[n] && (l = new U[n])._onInitTween(e, this.vars[n], this)) { for (this._firstPT = h = { _next: this._firstPT, t: l, p: "setRatio", s: 0, c: 1, f: !0, n: n, pg: !0, pr: l._priority }, a = l._overwriteProps.length; --a > -1;)i[l._overwriteProps[a]] = this._firstPT; (l._priority || l._onInitAllProps) && (o = !0), (l._onDisable || l._onEnable) && (this._notifyPluginsOfEnabled = !0) } else this._firstPT = i[n] = h = { _next: this._firstPT, t: e, p: n, f: "function" == typeof e[n], n: n, pg: !1, pr: 0 }, h.s = h.f ? e[n.indexOf("set") || "function" != typeof e["get" + n.substr(3)] ? n : "get" + n.substr(3)]() : parseFloat(e[n]), h.c = "string" == typeof _ && "=" === _.charAt(1) ? parseInt(_.charAt(0) + "1", 10) * Number(_.substr(2)) : Number(_) - h.s || 0; h && h._next && (h._next._prev = h) } return r && this._kill(r, e) ? this._initProps(e, i, s, r) : this._overwrite > 1 && this._firstPT && s.length > 1 && J(e, this, i, this._overwrite, s) ? (this._kill(i, e), this._initProps(e, i, s, r)) : (this._firstPT && (this.vars.lazy !== !1 && this._duration || this.vars.lazy && !this._duration) && (L[e._gsTweenID] = !0), o) }, n.render = function (t, e, i) { var s, r, n, a, o = this._time, l = this._duration, h = this._rawPrevTime; if (t >= l) this._totalTime = this._time = l, this.ratio = this._ease._calcEnd ? this._ease.getRatio(1) : 1, this._reversed || (s = !0, r = "onComplete", i = i || this._timeline.autoRemoveChildren), 0 === l && (this._initted || !this.vars.lazy || i) && (this._startTime === this._timeline._duration && (t = 0), (0 === t || 0 > h || h === _ && "isPause" !== this.data) && h !== t && (i = !0, h > _ && (r = "onReverseComplete")), this._rawPrevTime = a = !e || t || h === t ? t : _); else if (1e-7 > t) this._totalTime = this._time = 0, this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0, (0 !== o || 0 === l && h > 0) && (r = "onReverseComplete", s = this._reversed), 0 > t && (this._active = !1, 0 === l && (this._initted || !this.vars.lazy || i) && (h >= 0 && (h !== _ || "isPause" !== this.data) && (i = !0), this._rawPrevTime = a = !e || t || h === t ? t : _)), this._initted || (i = !0); else if (this._totalTime = this._time = t, this._easeType) { var u = t / l, m = this._easeType, f = this._easePower; (1 === m || 3 === m && u >= .5) && (u = 1 - u), 3 === m && (u *= 2), 1 === f ? u *= u : 2 === f ? u *= u * u : 3 === f ? u *= u * u * u : 4 === f && (u *= u * u * u * u), this.ratio = 1 === m ? 1 - u : 2 === m ? u : .5 > t / l ? u / 2 : 1 - u / 2 } else this.ratio = this._ease.getRatio(t / l); if (this._time !== o || i) { if (!this._initted) { if (this._init(), !this._initted || this._gc) return; if (!i && this._firstPT && (this.vars.lazy !== !1 && this._duration || this.vars.lazy && !this._duration)) return this._time = this._totalTime = o, this._rawPrevTime = h, z.push(this), this._lazy = [t, e], void 0; this._time && !s ? this.ratio = this._ease.getRatio(this._time / l) : s && this._ease._calcEnd && (this.ratio = this._ease.getRatio(0 === this._time ? 0 : 1)) } for (this._lazy !== !1 && (this._lazy = !1), this._active || !this._paused && this._time !== o && t >= 0 && (this._active = !0), 0 === o && (this._startAt && (t >= 0 ? this._startAt.render(t, e, i) : r || (r = "_dummyGS")), this.vars.onStart && (0 !== this._time || 0 === l) && (e || this.vars.onStart.apply(this.vars.onStartScope || this, this.vars.onStartParams || T))), n = this._firstPT; n;)n.f ? n.t[n.p](n.c * this.ratio + n.s) : n.t[n.p] = n.c * this.ratio + n.s, n = n._next; this._onUpdate && (0 > t && this._startAt && t !== -1e-4 && this._startAt.render(t, e, i), e || (this._time !== o || s) && this._onUpdate.apply(this.vars.onUpdateScope || this, this.vars.onUpdateParams || T)), r && (!this._gc || i) && (0 > t && this._startAt && !this._onUpdate && t !== -1e-4 && this._startAt.render(t, e, i), s && (this._timeline.autoRemoveChildren && this._enabled(!1, !1), this._active = !1), !e && this.vars[r] && this.vars[r].apply(this.vars[r + "Scope"] || this, this.vars[r + "Params"] || T), 0 === l && this._rawPrevTime === _ && a !== _ && (this._rawPrevTime = 0)) } }, n._kill = function (t, e, i) { if ("all" === t && (t = null), null == t && (null == e || e === this.target)) return this._lazy = !1, this._enabled(!1, !1); e = "string" != typeof e ? e || this._targets || this.target : I.selector(e) || e; var s, r, n, a, o, l, h, _, u; if ((f(e) || E(e)) && "number" != typeof e[0]) for (s = e.length; --s > -1;)this._kill(t, e[s]) && (l = !0); else { if (this._targets) { for (s = this._targets.length; --s > -1;)if (e === this._targets[s]) { o = this._propLookup[s] || {}, this._overwrittenProps = this._overwrittenProps || [], r = this._overwrittenProps[s] = t ? this._overwrittenProps[s] || {} : "all"; break } } else { if (e !== this.target) return !1; o = this._propLookup, r = this._overwrittenProps = t ? this._overwrittenProps || {} : "all" } if (o) { if (h = t || o, _ = t !== r && "all" !== r && t !== o && ("object" != typeof t || !t._tempKill), i && (I.onOverwrite || this.vars.onOverwrite)) { for (n in h) o[n] && (u || (u = []), u.push(n)); if (!H(this, i, e, u)) return !1 } for (n in h) (a = o[n]) && (a.pg && a.t._kill(h) && (l = !0), a.pg && 0 !== a.t._overwriteProps.length || (a._prev ? a._prev._next = a._next : a === this._firstPT && (this._firstPT = a._next), a._next && (a._next._prev = a._prev), a._next = a._prev = null), delete o[n]), _ && (r[n] = 1); !this._firstPT && this._initted && this._enabled(!1, !1) } } return l }, n.invalidate = function () { return this._notifyPluginsOfEnabled && I._onPluginEvent("_onDisable", this), this._firstPT = this._overwrittenProps = this._startAt = this._onUpdate = null, this._notifyPluginsOfEnabled = this._active = this._lazy = !1, this._propLookup = this._targets ? {} : [], R.prototype.invalidate.call(this), this.vars.immediateRender && (this._time = -_, this.render(-this._delay)), this }, n._enabled = function (t, e) { if (o || a.wake(), t && this._gc) { var i, s = this._targets; if (s) for (i = s.length; --i > -1;)this._siblings[i] = K(s[i], this, !0); else this._siblings = K(this.target, this, !0) } return R.prototype._enabled.call(this, t, e), this._notifyPluginsOfEnabled && this._firstPT ? I._onPluginEvent(t ? "_onEnable" : "_onDisable", this) : !1 }, I.to = function (t, e, i) { return new I(t, e, i) }, I.from = function (t, e, i) { return i.runBackwards = !0, i.immediateRender = 0 != i.immediateRender, new I(t, e, i) }, I.fromTo = function (t, e, i, s) { return s.startAt = i, s.immediateRender = 0 != s.immediateRender && 0 != i.immediateRender, new I(t, e, s) }, I.delayedCall = function (t, e, i, s, r) { return new I(e, 0, { delay: t, onComplete: e, onCompleteParams: i, onCompleteScope: s, onReverseComplete: e, onReverseCompleteParams: i, onReverseCompleteScope: s, immediateRender: !1, lazy: !1, useFrames: r, overwrite: 0 }) }, I.set = function (t, e) { return new I(t, 0, e) }, I.getTweensOf = function (t, e) { if (null == t) return []; t = "string" != typeof t ? t : I.selector(t) || t; var i, s, r, n; if ((f(t) || E(t)) && "number" != typeof t[0]) { for (i = t.length, s = []; --i > -1;)s = s.concat(I.getTweensOf(t[i], e)); for (i = s.length; --i > -1;)for (n = s[i], r = i; --r > -1;)n === s[r] && s.splice(i, 1) } else for (s = K(t).concat(), i = s.length; --i > -1;)(s[i]._gc || e && !s[i].isActive()) && s.splice(i, 1); return s }, I.killTweensOf = I.killDelayedCallsTo = function (t, e, i) { "object" == typeof e && (i = e, e = !1); for (var s = I.getTweensOf(t, e), r = s.length; --r > -1;)s[r]._kill(i, t) }; var W = v("plugins.TweenPlugin", function (t, e) { this._overwriteProps = (t || "").split(","), this._propName = this._overwriteProps[0], this._priority = e || 0, this._super = W.prototype }, !0); if (n = W.prototype, W.version = "1.10.1", W.API = 2, n._firstPT = null, n._addTween = function (t, e, i, s, r, n) { var a, o; return null != s && (a = "number" == typeof s || "=" !== s.charAt(1) ? Number(s) - i : parseInt(s.charAt(0) + "1", 10) * Number(s.substr(2))) ? (this._firstPT = o = { _next: this._firstPT, t: t, p: e, s: i, c: a, f: "function" == typeof t[e], n: r || e, r: n }, o._next && (o._next._prev = o), o) : void 0 }, n.setRatio = function (t) { for (var e, i = this._firstPT, s = 1e-6; i;)e = i.c * t + i.s, i.r ? e = Math.round(e) : s > e && e > -s && (e = 0), i.f ? i.t[i.p](e) : i.t[i.p] = e, i = i._next }, n._kill = function (t) { var e, i = this._overwriteProps, s = this._firstPT; if (null != t[this._propName]) this._overwriteProps = []; else for (e = i.length; --e > -1;)null != t[i[e]] && i.splice(e, 1); for (; s;)null != t[s.n] && (s._next && (s._next._prev = s._prev), s._prev ? (s._prev._next = s._next, s._prev = null) : this._firstPT === s && (this._firstPT = s._next)), s = s._next; return !1 }, n._roundProps = function (t, e) { for (var i = this._firstPT; i;)(t[this._propName] || null != i.n && t[i.n.split(this._propName + "_").join("")]) && (i.r = e), i = i._next }, I._onPluginEvent = function (t, e) { var i, s, r, n, a, o = e._firstPT; if ("_onInitAllProps" === t) { for (; o;) { for (a = o._next, s = r; s && s.pr > o.pr;)s = s._next; (o._prev = s ? s._prev : n) ? o._prev._next = o : r = o, (o._next = s) ? s._prev = o : n = o, o = a } o = e._firstPT = r } for (; o;)o.pg && "function" == typeof o.t[t] && o.t[t]() && (i = !0), o = o._next; return i }, W.activate = function (t) { for (var e = t.length; --e > -1;)t[e].API === W.API && (U[(new t[e])._propName] = t[e]); return !0 }, d.plugin = function (t) { if (!(t && t.propName && t.init && t.API)) throw "illegal plugin definition."; var e, i = t.propName, s = t.priority || 0, r = t.overwriteProps, n = { init: "_onInitTween", set: "setRatio", kill: "_kill", round: "_roundProps", initAll: "_onInitAllProps" }, a = v("plugins." + i.charAt(0).toUpperCase() + i.substr(1) + "Plugin", function () { W.call(this, i, s), this._overwriteProps = r || [] }, t.global === !0), o = a.prototype = new W(i); o.constructor = a, a.API = t.API; for (e in n) "function" == typeof t[e] && (o[n[e]] = t[e]); return a.version = t.version, W.activate([a]), a }, s = t._gsQueue) { for (r = 0; s.length > r; r++)s[r](); for (n in c) c[n].func || t.console.log("GSAP encountered missing dependency: com.greensock." + n) } o = !1 } })("undefined" != typeof module && module.exports && "undefined" != typeof global ? global : this || window, "TweenLite");
/*!
 * VERSION: beta 1.9.4
 * DATE: 2014-07-17
 * UPDATES AND DOCS AT: http://greensock.com
 *
 * @license Copyright (c) 2008-2015, GreenSock. All rights reserved.
 * This work is subject to the terms at http://greensock.com/standard-license or for
 * Club GreenSock members, the software agreement that was issued with your membership.
 * 
 * @author: Jack Doyle, jack@greensock.com
 **/
var _gsScope = "undefined" != typeof module && module.exports && "undefined" != typeof global ? global : this || window; (_gsScope._gsQueue || (_gsScope._gsQueue = [])).push(function () { "use strict"; _gsScope._gsDefine("easing.Back", ["easing.Ease"], function (t) { var e, i, s, r = _gsScope.GreenSockGlobals || _gsScope, n = r.com.greensock, a = 2 * Math.PI, o = Math.PI / 2, h = n._class, l = function (e, i) { var s = h("easing." + e, function () { }, !0), r = s.prototype = new t; return r.constructor = s, r.getRatio = i, s }, _ = t.register || function () { }, u = function (t, e, i, s) { var r = h("easing." + t, { easeOut: new e, easeIn: new i, easeInOut: new s }, !0); return _(r, t), r }, c = function (t, e, i) { this.t = t, this.v = e, i && (this.next = i, i.prev = this, this.c = i.v - e, this.gap = i.t - t) }, p = function (e, i) { var s = h("easing." + e, function (t) { this._p1 = t || 0 === t ? t : 1.70158, this._p2 = 1.525 * this._p1 }, !0), r = s.prototype = new t; return r.constructor = s, r.getRatio = i, r.config = function (t) { return new s(t) }, s }, f = u("Back", p("BackOut", function (t) { return (t -= 1) * t * ((this._p1 + 1) * t + this._p1) + 1 }), p("BackIn", function (t) { return t * t * ((this._p1 + 1) * t - this._p1) }), p("BackInOut", function (t) { return 1 > (t *= 2) ? .5 * t * t * ((this._p2 + 1) * t - this._p2) : .5 * ((t -= 2) * t * ((this._p2 + 1) * t + this._p2) + 2) })), m = h("easing.SlowMo", function (t, e, i) { e = e || 0 === e ? e : .7, null == t ? t = .7 : t > 1 && (t = 1), this._p = 1 !== t ? e : 0, this._p1 = (1 - t) / 2, this._p2 = t, this._p3 = this._p1 + this._p2, this._calcEnd = i === !0 }, !0), d = m.prototype = new t; return d.constructor = m, d.getRatio = function (t) { var e = t + (.5 - t) * this._p; return this._p1 > t ? this._calcEnd ? 1 - (t = 1 - t / this._p1) * t : e - (t = 1 - t / this._p1) * t * t * t * e : t > this._p3 ? this._calcEnd ? 1 - (t = (t - this._p3) / this._p1) * t : e + (t - e) * (t = (t - this._p3) / this._p1) * t * t * t : this._calcEnd ? 1 : e }, m.ease = new m(.7, .7), d.config = m.config = function (t, e, i) { return new m(t, e, i) }, e = h("easing.SteppedEase", function (t) { t = t || 1, this._p1 = 1 / t, this._p2 = t + 1 }, !0), d = e.prototype = new t, d.constructor = e, d.getRatio = function (t) { return 0 > t ? t = 0 : t >= 1 && (t = .999999999), (this._p2 * t >> 0) * this._p1 }, d.config = e.config = function (t) { return new e(t) }, i = h("easing.RoughEase", function (e) { e = e || {}; for (var i, s, r, n, a, o, h = e.taper || "none", l = [], _ = 0, u = 0 | (e.points || 20), p = u, f = e.randomize !== !1, m = e.clamp === !0, d = e.template instanceof t ? e.template : null, g = "number" == typeof e.strength ? .4 * e.strength : .4; --p > -1;)i = f ? Math.random() : 1 / u * p, s = d ? d.getRatio(i) : i, "none" === h ? r = g : "out" === h ? (n = 1 - i, r = n * n * g) : "in" === h ? r = i * i * g : .5 > i ? (n = 2 * i, r = .5 * n * n * g) : (n = 2 * (1 - i), r = .5 * n * n * g), f ? s += Math.random() * r - .5 * r : p % 2 ? s += .5 * r : s -= .5 * r, m && (s > 1 ? s = 1 : 0 > s && (s = 0)), l[_++] = { x: i, y: s }; for (l.sort(function (t, e) { return t.x - e.x }), o = new c(1, 1, null), p = u; --p > -1;)a = l[p], o = new c(a.x, a.y, o); this._prev = new c(0, 0, 0 !== o.t ? o : o.next) }, !0), d = i.prototype = new t, d.constructor = i, d.getRatio = function (t) { var e = this._prev; if (t > e.t) { for (; e.next && t >= e.t;)e = e.next; e = e.prev } else for (; e.prev && e.t >= t;)e = e.prev; return this._prev = e, e.v + (t - e.t) / e.gap * e.c }, d.config = function (t) { return new i(t) }, i.ease = new i, u("Bounce", l("BounceOut", function (t) { return 1 / 2.75 > t ? 7.5625 * t * t : 2 / 2.75 > t ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : 2.5 / 2.75 > t ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375 }), l("BounceIn", function (t) { return 1 / 2.75 > (t = 1 - t) ? 1 - 7.5625 * t * t : 2 / 2.75 > t ? 1 - (7.5625 * (t -= 1.5 / 2.75) * t + .75) : 2.5 / 2.75 > t ? 1 - (7.5625 * (t -= 2.25 / 2.75) * t + .9375) : 1 - (7.5625 * (t -= 2.625 / 2.75) * t + .984375) }), l("BounceInOut", function (t) { var e = .5 > t; return t = e ? 1 - 2 * t : 2 * t - 1, t = 1 / 2.75 > t ? 7.5625 * t * t : 2 / 2.75 > t ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : 2.5 / 2.75 > t ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375, e ? .5 * (1 - t) : .5 * t + .5 })), u("Circ", l("CircOut", function (t) { return Math.sqrt(1 - (t -= 1) * t) }), l("CircIn", function (t) { return -(Math.sqrt(1 - t * t) - 1) }), l("CircInOut", function (t) { return 1 > (t *= 2) ? -.5 * (Math.sqrt(1 - t * t) - 1) : .5 * (Math.sqrt(1 - (t -= 2) * t) + 1) })), s = function (e, i, s) { var r = h("easing." + e, function (t, e) { this._p1 = t || 1, this._p2 = e || s, this._p3 = this._p2 / a * (Math.asin(1 / this._p1) || 0) }, !0), n = r.prototype = new t; return n.constructor = r, n.getRatio = i, n.config = function (t, e) { return new r(t, e) }, r }, u("Elastic", s("ElasticOut", function (t) { return this._p1 * Math.pow(2, -10 * t) * Math.sin((t - this._p3) * a / this._p2) + 1 }, .3), s("ElasticIn", function (t) { return -(this._p1 * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - this._p3) * a / this._p2)) }, .3), s("ElasticInOut", function (t) { return 1 > (t *= 2) ? -.5 * this._p1 * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - this._p3) * a / this._p2) : .5 * this._p1 * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - this._p3) * a / this._p2) + 1 }, .45)), u("Expo", l("ExpoOut", function (t) { return 1 - Math.pow(2, -10 * t) }), l("ExpoIn", function (t) { return Math.pow(2, 10 * (t - 1)) - .001 }), l("ExpoInOut", function (t) { return 1 > (t *= 2) ? .5 * Math.pow(2, 10 * (t - 1)) : .5 * (2 - Math.pow(2, -10 * (t - 1))) })), u("Sine", l("SineOut", function (t) { return Math.sin(t * o) }), l("SineIn", function (t) { return -Math.cos(t * o) + 1 }), l("SineInOut", function (t) { return -.5 * (Math.cos(Math.PI * t) - 1) })), h("easing.EaseLookup", { find: function (e) { return t.map[e] } }, !0), _(r.SlowMo, "SlowMo", "ease,"), _(i, "RoughEase", "ease,"), _(e, "SteppedEase", "ease,"), f }, !0) }), _gsScope._gsDefine && _gsScope._gsQueue.pop()();

/*!
 * VERSION: 0.1.11
 * DATE: 2015-03-13
 * UPDATES AND DOCS AT: http://greensock.com/jquery-gsap-plugin/
 *
 * Requires TweenLite version 1.8.0 or higher and CSSPlugin.
 *
 * @license Copyright (c) 2013-2015, GreenSock. All rights reserved.
 * This work is subject to the terms at http://greensock.com/standard-license or for
 * Club GreenSock members, the software agreement that was issued with your membership.
 *
 * @author: Jack Doyle, jack@greensock.com
 */
(function (t) { "use strict"; var e, i, s, r = t.fn.animate, n = t.fn.stop, a = !0, o = function (t) { var e, i = {}; for (e in t) i[e] = t[e]; return i }, h = { overwrite: 1, delay: 1, useFrames: 1, runBackwards: 1, easeParams: 1, yoyo: 1, immediateRender: 1, repeat: 1, repeatDelay: 1, autoCSS: 1 }, l = ",scrollTop,scrollLeft,show,hide,toggle,", _ = l, u = function (t, e) { for (var i in h) h[i] && void 0 !== t[i] && (e[i] = t[i]) }, f = function (t) { return function (e) { return t.getRatio(e) } }, c = {}, p = function () { var r, n, a, o = window.GreenSockGlobals || window; if (e = o.TweenMax || o.TweenLite, e && (r = (e.version + ".0.0").split("."), n = !(Number(r[0]) > 0 && Number(r[1]) > 7), o = o.com.greensock, i = o.plugins.CSSPlugin, c = o.easing.Ease.map || {}), !e || !i || n) return e = null, !s && window.console && (window.console.log("The jquery.gsap.js plugin requires the TweenMax (or at least TweenLite and CSSPlugin) JavaScript file(s)." + (n ? " Version " + r.join(".") + " is too old." : "")), s = !0), void 0; if (t.easing) { for (a in c) t.easing[a] = f(c[a]); p = !1 } }; t.fn.animate = function (s, n, h, l) { if (s = s || {}, p && (p(), !e || !i)) return r.call(this, s, n, h, l); if (!a || s.skipGSAP === !0 || "object" == typeof n && "function" == typeof n.step) return r.call(this, s, n, h, l); var f, m, d, g, v = t.speed(n, h, l), y = { ease: c[v.easing] || (v.easing === !1 ? c.linear : c.swing) }, T = this, w = "object" == typeof n ? n.specialEasing : null; for (m in s) { if (f = s[m], f instanceof Array && c[f[1]] && (w = w || {}, w[m] = f[1], f = f[0]), "show" === f || "hide" === f || "toggle" === f || -1 !== _.indexOf(m) && -1 !== _.indexOf("," + m + ",")) return r.call(this, s, n, h, l); y[-1 === m.indexOf("-") ? m : t.camelCase(m)] = f } if (w) { y = o(y), g = []; for (m in w) f = g[g.length] = {}, u(y, f), f.ease = c[w[m]] || y.ease, -1 !== m.indexOf("-") && (m = t.camelCase(m)), f[m] = y[m], delete y[m]; 0 === g.length && (g = null) } return d = function (i) { var s, r = o(y); if (g) for (s = g.length; --s > -1;)e.to(this, t.fx.off ? 0 : v.duration / 1e3, g[s]); r.onComplete = function () { i ? i() : v.old && t(this).each(v.old) }, e.to(this, t.fx.off ? 0 : v.duration / 1e3, r) }, v.queue !== !1 ? (T.queue(v.queue, d), "function" == typeof v.old && T.queue(v.queue, function (t) { v.old.call(this), t() })) : d.call(T), T }, t.fn.stop = function (t, i) { if (n.call(this, t, i), e) { if (i) for (var s, r = e.getTweensOf(this), a = r.length; --a > -1;)s = r[a].totalTime() / r[a].totalDuration(), s > 0 && 1 > s && r[a].seek(r[a].totalDuration()); e.killTweensOf(this) } return this }, t.gsap = { enabled: function (t) { a = t }, version: "0.1.11", legacyProps: function (t) { _ = l + t + "," } } })(jQuery);
////2023-07-18 : if (user_ip == '108.180.234.14') console.log('406             --------------------------------------------');

/*!
 * VERSION: 1.16.1
 * DATE: 2015-03-13
 * UPDATES AND DOCS AT: http://www.greensock.com
 *
 * @license Copyright (c) 2008-2015, GreenSock. All rights reserved.
 * This work is subject to the terms at http://greensock.com/standard-license or for
 * Club GreenSock members, the software agreement that was issued with your membership.
 * 
 * @author: Jack Doyle, jack@greensock.com
 */
var _gsScope = "undefined" != typeof module && module.exports && "undefined" != typeof global ? global : this || window; (_gsScope._gsQueue || (_gsScope._gsQueue = [])).push(function () {
  "use strict"; _gsScope._gsDefine("plugins.CSSPlugin", ["plugins.TweenPlugin", "TweenLite"], function (t, e) {
    var i, r, s, n, a = function () { t.call(this, "css"), this._overwriteProps.length = 0, this.setRatio = a.prototype.setRatio }, o = _gsScope._gsDefine.globals, l = {}, h = a.prototype = new t("css"); h.constructor = a, a.version = "1.16.1", a.API = 2, a.defaultTransformPerspective = 0, a.defaultSkewType = "compensated", h = "px", a.suffixMap = { top: h, right: h, bottom: h, left: h, width: h, height: h, fontSize: h, padding: h, margin: h, perspective: h, lineHeight: "" }; var u, f, p, c, _, d, m = /(?:\d|\-\d|\.\d|\-\.\d)+/g, g = /(?:\d|\-\d|\.\d|\-\.\d|\+=\d|\-=\d|\+=.\d|\-=\.\d)+/g, v = /(?:\+=|\-=|\-|\b)[\d\-\.]+[a-zA-Z0-9]*(?:%|\b)/gi, y = /(?![+-]?\d*\.?\d+|[+-]|e[+-]\d+)[^0-9]/g, x = /(?:\d|\-|\+|=|#|\.)*/g, T = /opacity *= *([^)]*)/i, w = /opacity:([^;]*)/i, b = /alpha\(opacity *=.+?\)/i, P = /^(rgb|hsl)/, S = /([A-Z])/g, C = /-([a-z])/gi, O = /(^(?:url\(\"|url\())|(?:(\"\))$|\)$)/gi, k = function (t, e) { return e.toUpperCase() }, R = /(?:Left|Right|Width)/i, A = /(M11|M12|M21|M22)=[\d\-\.e]+/gi, M = /progid\:DXImageTransform\.Microsoft\.Matrix\(.+?\)/i, D = /,(?=[^\)]*(?:\(|$))/gi, N = Math.PI / 180, L = 180 / Math.PI, X = {}, z = document, E = function (t) { return z.createElementNS ? z.createElementNS("http://www.w3.org/1999/xhtml", t) : z.createElement(t) }, F = E("div"), I = E("img"), Y = a._internals = { _specialProps: l }, B = navigator.userAgent, U = function () { var t = B.indexOf("Android"), e = E("a"); return p = -1 !== B.indexOf("Safari") && -1 === B.indexOf("Chrome") && (-1 === t || Number(B.substr(t + 8, 1)) > 3), _ = p && 6 > Number(B.substr(B.indexOf("Version/") + 8, 1)), c = -1 !== B.indexOf("Firefox"), (/MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(B) || /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(B)) && (d = parseFloat(RegExp.$1)), e ? (e.style.cssText = "top:1px;opacity:.55;", /^0.55/.test(e.style.opacity)) : !1 }(), j = function (t) { return T.test("string" == typeof t ? t : (t.currentStyle ? t.currentStyle.filter : t.style.filter) || "") ? parseFloat(RegExp.$1) / 100 : 1 }, V = function (t) { window.console && console.log(t) }, W = "", q = "", G = function (t, e) { e = e || F; var i, r, s = e.style; if (void 0 !== s[t]) return t; for (t = t.charAt(0).toUpperCase() + t.substr(1), i = ["O", "Moz", "ms", "Ms", "Webkit"], r = 5; --r > -1 && void 0 === s[i[r] + t];); return r >= 0 ? (q = 3 === r ? "ms" : i[r], W = "-" + q.toLowerCase() + "-", q + t) : null }, H = z.defaultView ? z.defaultView.getComputedStyle : function () { }, Q = a.getStyle = function (t, e, i, r, s) { var n; return U || "opacity" !== e ? (!r && t.style[e] ? n = t.style[e] : (i = i || H(t)) ? n = i[e] || i.getPropertyValue(e) || i.getPropertyValue(e.replace(S, "-$1").toLowerCase()) : t.currentStyle && (n = t.currentStyle[e]), null == s || n && "none" !== n && "auto" !== n && "auto auto" !== n ? n : s) : j(t) }, Z = Y.convertToPixels = function (t, i, r, s, n) { if ("px" === s || !s) return r; if ("auto" === s || !r) return 0; var o, l, h, u = R.test(i), f = t, p = F.style, c = 0 > r; if (c && (r = -r), "%" === s && -1 !== i.indexOf("border")) o = r / 100 * (u ? t.clientWidth : t.clientHeight); else { if (p.cssText = "border:0 solid red;position:" + Q(t, "position") + ";line-height:0;", "%" !== s && f.appendChild) p[u ? "borderLeftWidth" : "borderTopWidth"] = r + s; else { if (f = t.parentNode || z.body, l = f._gsCache, h = e.ticker.frame, l && u && l.time === h) return l.width * r / 100; p[u ? "width" : "height"] = r + s } f.appendChild(F), o = parseFloat(F[u ? "offsetWidth" : "offsetHeight"]), f.removeChild(F), u && "%" === s && a.cacheWidths !== !1 && (l = f._gsCache = f._gsCache || {}, l.time = h, l.width = 100 * (o / r)), 0 !== o || n || (o = Z(t, i, r, s, !0)) } return c ? -o : o }, $ = Y.calculateOffset = function (t, e, i) { if ("absolute" !== Q(t, "position", i)) return 0; var r = "left" === e ? "Left" : "Top", s = Q(t, "margin" + r, i); return t["offset" + r] - (Z(t, e, parseFloat(s), s.replace(x, "")) || 0) }, K = function (t, e) { var i, r, s, n = {}; if (e = e || H(t, null)) if (i = e.length) for (; --i > -1;)s = e[i], (-1 === s.indexOf("-transform") || be === s) && (n[s.replace(C, k)] = e.getPropertyValue(s)); else for (i in e) (-1 === i.indexOf("Transform") || we === i) && (n[i] = e[i]); else if (e = t.currentStyle || t.style) for (i in e) "string" == typeof i && void 0 === n[i] && (n[i.replace(C, k)] = e[i]); return U || (n.opacity = j(t)), r = De(t, e, !1), n.rotation = r.rotation, n.skewX = r.skewX, n.scaleX = r.scaleX, n.scaleY = r.scaleY, n.x = r.x, n.y = r.y, Se && (n.z = r.z, n.rotationX = r.rotationX, n.rotationY = r.rotationY, n.scaleZ = r.scaleZ), n.filters && delete n.filters, n }, J = function (t, e, i, r, s) { var n, a, o, l = {}, h = t.style; for (a in i) "cssText" !== a && "length" !== a && isNaN(a) && (e[a] !== (n = i[a]) || s && s[a]) && -1 === a.indexOf("Origin") && ("number" == typeof n || "string" == typeof n) && (l[a] = "auto" !== n || "left" !== a && "top" !== a ? "" !== n && "auto" !== n && "none" !== n || "string" != typeof e[a] || "" === e[a].replace(y, "") ? n : 0 : $(t, a), void 0 !== h[a] && (o = new ce(h, a, h[a], o))); if (r) for (a in r) "className" !== a && (l[a] = r[a]); return { difs: l, firstMPT: o } }, te = { width: ["Left", "Right"], height: ["Top", "Bottom"] }, ee = ["marginLeft", "marginRight", "marginTop", "marginBottom"], ie = function (t, e, i) { var r = parseFloat("width" === e ? t.offsetWidth : t.offsetHeight), s = te[e], n = s.length; for (i = i || H(t, null); --n > -1;)r -= parseFloat(Q(t, "padding" + s[n], i, !0)) || 0, r -= parseFloat(Q(t, "border" + s[n] + "Width", i, !0)) || 0; return r }, re = function (t, e) { (null == t || "" === t || "auto" === t || "auto auto" === t) && (t = "0 0"); var i = t.split(" "), r = -1 !== t.indexOf("left") ? "0%" : -1 !== t.indexOf("right") ? "100%" : i[0], s = -1 !== t.indexOf("top") ? "0%" : -1 !== t.indexOf("bottom") ? "100%" : i[1]; return null == s ? s = "center" === r ? "50%" : "0" : "center" === s && (s = "50%"), ("center" === r || isNaN(parseFloat(r)) && -1 === (r + "").indexOf("=")) && (r = "50%"), t = r + " " + s + (i.length > 2 ? " " + i[2] : ""), e && (e.oxp = -1 !== r.indexOf("%"), e.oyp = -1 !== s.indexOf("%"), e.oxr = "=" === r.charAt(1), e.oyr = "=" === s.charAt(1), e.ox = parseFloat(r.replace(y, "")), e.oy = parseFloat(s.replace(y, "")), e.v = t), e || t }, se = function (t, e) { return "string" == typeof t && "=" === t.charAt(1) ? parseInt(t.charAt(0) + "1", 10) * parseFloat(t.substr(2)) : parseFloat(t) - parseFloat(e) }, ne = function (t, e) { return null == t ? e : "string" == typeof t && "=" === t.charAt(1) ? parseInt(t.charAt(0) + "1", 10) * parseFloat(t.substr(2)) + e : parseFloat(t) }, ae = function (t, e, i, r) { var s, n, a, o, l, h = 1e-6; return null == t ? o = e : "number" == typeof t ? o = t : (s = 360, n = t.split("_"), l = "=" === t.charAt(1), a = (l ? parseInt(t.charAt(0) + "1", 10) * parseFloat(n[0].substr(2)) : parseFloat(n[0])) * (-1 === t.indexOf("rad") ? 1 : L) - (l ? 0 : e), n.length && (r && (r[i] = e + a), -1 !== t.indexOf("short") && (a %= s, a !== a % (s / 2) && (a = 0 > a ? a + s : a - s)), -1 !== t.indexOf("_cw") && 0 > a ? a = (a + 9999999999 * s) % s - (0 | a / s) * s : -1 !== t.indexOf("ccw") && a > 0 && (a = (a - 9999999999 * s) % s - (0 | a / s) * s)), o = e + a), h > o && o > -h && (o = 0), o }, oe = { aqua: [0, 255, 255], lime: [0, 255, 0], silver: [192, 192, 192], black: [0, 0, 0], maroon: [128, 0, 0], teal: [0, 128, 128], blue: [0, 0, 255], navy: [0, 0, 128], white: [255, 255, 255], fuchsia: [255, 0, 255], olive: [128, 128, 0], yellow: [255, 255, 0], orange: [255, 165, 0], gray: [128, 128, 128], purple: [128, 0, 128], green: [0, 128, 0], red: [255, 0, 0], pink: [255, 192, 203], cyan: [0, 255, 255], transparent: [255, 255, 255, 0] }, le = function (t, e, i) { return t = 0 > t ? t + 1 : t > 1 ? t - 1 : t, 0 | 255 * (1 > 6 * t ? e + 6 * (i - e) * t : .5 > t ? i : 2 > 3 * t ? e + 6 * (i - e) * (2 / 3 - t) : e) + .5 }, he = a.parseColor = function (t) { var e, i, r, s, n, a; return t && "" !== t ? "number" == typeof t ? [t >> 16, 255 & t >> 8, 255 & t] : ("," === t.charAt(t.length - 1) && (t = t.substr(0, t.length - 1)), oe[t] ? oe[t] : "#" === t.charAt(0) ? (4 === t.length && (e = t.charAt(1), i = t.charAt(2), r = t.charAt(3), t = "#" + e + e + i + i + r + r), t = parseInt(t.substr(1), 16), [t >> 16, 255 & t >> 8, 255 & t]) : "hsl" === t.substr(0, 3) ? (t = t.match(m), s = Number(t[0]) % 360 / 360, n = Number(t[1]) / 100, a = Number(t[2]) / 100, i = .5 >= a ? a * (n + 1) : a + n - a * n, e = 2 * a - i, t.length > 3 && (t[3] = Number(t[3])), t[0] = le(s + 1 / 3, e, i), t[1] = le(s, e, i), t[2] = le(s - 1 / 3, e, i), t) : (t = t.match(m) || oe.transparent, t[0] = Number(t[0]), t[1] = Number(t[1]), t[2] = Number(t[2]), t.length > 3 && (t[3] = Number(t[3])), t)) : oe.black }, ue = "(?:\\b(?:(?:rgb|rgba|hsl|hsla)\\(.+?\\))|\\B#.+?\\b"; for (h in oe) ue += "|" + h + "\\b"; ue = RegExp(ue + ")", "gi"); var fe = function (t, e, i, r) { if (null == t) return function (t) { return t }; var s, n = e ? (t.match(ue) || [""])[0] : "", a = t.split(n).join("").match(v) || [], o = t.substr(0, t.indexOf(a[0])), l = ")" === t.charAt(t.length - 1) ? ")" : "", h = -1 !== t.indexOf(" ") ? " " : ",", u = a.length, f = u > 0 ? a[0].replace(m, "") : ""; return u ? s = e ? function (t) { var e, p, c, _; if ("number" == typeof t) t += f; else if (r && D.test(t)) { for (_ = t.replace(D, "|").split("|"), c = 0; _.length > c; c++)_[c] = s(_[c]); return _.join(",") } if (e = (t.match(ue) || [n])[0], p = t.split(e).join("").match(v) || [], c = p.length, u > c--) for (; u > ++c;)p[c] = i ? p[0 | (c - 1) / 2] : a[c]; return o + p.join(h) + h + e + l + (-1 !== t.indexOf("inset") ? " inset" : "") } : function (t) { var e, n, p; if ("number" == typeof t) t += f; else if (r && D.test(t)) { for (n = t.replace(D, "|").split("|"), p = 0; n.length > p; p++)n[p] = s(n[p]); return n.join(",") } if (e = t.match(v) || [], p = e.length, u > p--) for (; u > ++p;)e[p] = i ? e[0 | (p - 1) / 2] : a[p]; return o + e.join(h) + l } : function (t) { return t } }, pe = function (t) { return t = t.split(","), function (e, i, r, s, n, a, o) { var l, h = (i + "").split(" "); for (o = {}, l = 0; 4 > l; l++)o[t[l]] = h[l] = h[l] || h[(l - 1) / 2 >> 0]; return s.parse(e, o, n, a) } }, ce = (Y._setPluginRatio = function (t) { this.plugin.setRatio(t); for (var e, i, r, s, n = this.data, a = n.proxy, o = n.firstMPT, l = 1e-6; o;)e = a[o.v], o.r ? e = Math.round(e) : l > e && e > -l && (e = 0), o.t[o.p] = e, o = o._next; if (n.autoRotate && (n.autoRotate.rotation = a.rotation), 1 === t) for (o = n.firstMPT; o;) { if (i = o.t, i.type) { if (1 === i.type) { for (s = i.xs0 + i.s + i.xs1, r = 1; i.l > r; r++)s += i["xn" + r] + i["xs" + (r + 1)]; i.e = s } } else i.e = i.s + i.xs0; o = o._next } }, function (t, e, i, r, s) { this.t = t, this.p = e, this.v = i, this.r = s, r && (r._prev = this, this._next = r) }), _e = (Y._parseToProxy = function (t, e, i, r, s, n) { var a, o, l, h, u, f = r, p = {}, c = {}, _ = i._transform, d = X; for (i._transform = null, X = e, r = u = i.parse(t, e, r, s), X = d, n && (i._transform = _, f && (f._prev = null, f._prev && (f._prev._next = null))); r && r !== f;) { if (1 >= r.type && (o = r.p, c[o] = r.s + r.c, p[o] = r.s, n || (h = new ce(r, "s", o, h, r.r), r.c = 0), 1 === r.type)) for (a = r.l; --a > 0;)l = "xn" + a, o = r.p + "_" + l, c[o] = r.data[l], p[o] = r[l], n || (h = new ce(r, l, o, h, r.rxp[l])); r = r._next } return { proxy: p, end: c, firstMPT: h, pt: u } }, Y.CSSPropTween = function (t, e, r, s, a, o, l, h, u, f, p) { this.t = t, this.p = e, this.s = r, this.c = s, this.n = l || e, t instanceof _e || n.push(this.n), this.r = h, this.type = o || 0, u && (this.pr = u, i = !0), this.b = void 0 === f ? r : f, this.e = void 0 === p ? r + s : p, a && (this._next = a, a._prev = this) }), de = a.parseComplex = function (t, e, i, r, s, n, a, o, l, h) { i = i || n || "", a = new _e(t, e, 0, 0, a, h ? 2 : 1, null, !1, o, i, r), r += ""; var f, p, c, _, d, v, y, x, T, w, b, S, C = i.split(", ").join(",").split(" "), O = r.split(", ").join(",").split(" "), k = C.length, R = u !== !1; for ((-1 !== r.indexOf(",") || -1 !== i.indexOf(",")) && (C = C.join(" ").replace(D, ", ").split(" "), O = O.join(" ").replace(D, ", ").split(" "), k = C.length), k !== O.length && (C = (n || "").split(" "), k = C.length), a.plugin = l, a.setRatio = h, f = 0; k > f; f++)if (_ = C[f], d = O[f], x = parseFloat(_), x || 0 === x) a.appendXtra("", x, se(d, x), d.replace(g, ""), R && -1 !== d.indexOf("px"), !0); else if (s && ("#" === _.charAt(0) || oe[_] || P.test(_))) S = "," === d.charAt(d.length - 1) ? ")," : ")", _ = he(_), d = he(d), T = _.length + d.length > 6, T && !U && 0 === d[3] ? (a["xs" + a.l] += a.l ? " transparent" : "transparent", a.e = a.e.split(O[f]).join("transparent")) : (U || (T = !1), a.appendXtra(T ? "rgba(" : "rgb(", _[0], d[0] - _[0], ",", !0, !0).appendXtra("", _[1], d[1] - _[1], ",", !0).appendXtra("", _[2], d[2] - _[2], T ? "," : S, !0), T && (_ = 4 > _.length ? 1 : _[3], a.appendXtra("", _, (4 > d.length ? 1 : d[3]) - _, S, !1))); else if (v = _.match(m)) { if (y = d.match(g), !y || y.length !== v.length) return a; for (c = 0, p = 0; v.length > p; p++)b = v[p], w = _.indexOf(b, c), a.appendXtra(_.substr(c, w - c), Number(b), se(y[p], b), "", R && "px" === _.substr(w + b.length, 2), 0 === p), c = w + b.length; a["xs" + a.l] += _.substr(c) } else a["xs" + a.l] += a.l ? " " + _ : _; if (-1 !== r.indexOf("=") && a.data) { for (S = a.xs0 + a.data.s, f = 1; a.l > f; f++)S += a["xs" + f] + a.data["xn" + f]; a.e = S + a["xs" + f] } return a.l || (a.type = -1, a.xs0 = a.e), a.xfirst || a }, me = 9; for (h = _e.prototype, h.l = h.pr = 0; --me > 0;)h["xn" + me] = 0, h["xs" + me] = ""; h.xs0 = "", h._next = h._prev = h.xfirst = h.data = h.plugin = h.setRatio = h.rxp = null, h.appendXtra = function (t, e, i, r, s, n) { var a = this, o = a.l; return a["xs" + o] += n && o ? " " + t : t || "", i || 0 === o || a.plugin ? (a.l++, a.type = a.setRatio ? 2 : 1, a["xs" + a.l] = r || "", o > 0 ? (a.data["xn" + o] = e + i, a.rxp["xn" + o] = s, a["xn" + o] = e, a.plugin || (a.xfirst = new _e(a, "xn" + o, e, i, a.xfirst || a, 0, a.n, s, a.pr), a.xfirst.xs0 = 0), a) : (a.data = { s: e + i }, a.rxp = {}, a.s = e, a.c = i, a.r = s, a)) : (a["xs" + o] += e + (r || ""), a) }; var ge = function (t, e) { e = e || {}, this.p = e.prefix ? G(t) || t : t, l[t] = l[this.p] = this, this.format = e.formatter || fe(e.defaultValue, e.color, e.collapsible, e.multi), e.parser && (this.parse = e.parser), this.clrs = e.color, this.multi = e.multi, this.keyword = e.keyword, this.dflt = e.defaultValue, this.pr = e.priority || 0 }, ve = Y._registerComplexSpecialProp = function (t, e, i) { "object" != typeof e && (e = { parser: i }); var r, s, n = t.split(","), a = e.defaultValue; for (i = i || [a], r = 0; n.length > r; r++)e.prefix = 0 === r && e.prefix, e.defaultValue = i[r] || a, s = new ge(n[r], e) }, ye = function (t) { if (!l[t]) { var e = t.charAt(0).toUpperCase() + t.substr(1) + "Plugin"; ve(t, { parser: function (t, i, r, s, n, a, h) { var u = o.com.greensock.plugins[e]; return u ? (u._cssRegister(), l[r].parse(t, i, r, s, n, a, h)) : (V("Error: " + e + " js file not loaded."), n) } }) } }; h = ge.prototype, h.parseComplex = function (t, e, i, r, s, n) { var a, o, l, h, u, f, p = this.keyword; if (this.multi && (D.test(i) || D.test(e) ? (o = e.replace(D, "|").split("|"), l = i.replace(D, "|").split("|")) : p && (o = [e], l = [i])), l) { for (h = l.length > o.length ? l.length : o.length, a = 0; h > a; a++)e = o[a] = o[a] || this.dflt, i = l[a] = l[a] || this.dflt, p && (u = e.indexOf(p), f = i.indexOf(p), u !== f && (-1 === f ? o[a] = o[a].split(p).join("") : -1 === u && (o[a] += " " + p))); e = o.join(", "), i = l.join(", ") } return de(t, this.p, e, i, this.clrs, this.dflt, r, this.pr, s, n) }, h.parse = function (t, e, i, r, n, a) { return this.parseComplex(t.style, this.format(Q(t, this.p, s, !1, this.dflt)), this.format(e), n, a) }, a.registerSpecialProp = function (t, e, i) { ve(t, { parser: function (t, r, s, n, a, o) { var l = new _e(t, s, 0, 0, a, 2, s, !1, i); return l.plugin = o, l.setRatio = e(t, r, n._tween, s), l }, priority: i }) }, a.useSVGTransformAttr = p; var xe, Te = "scaleX,scaleY,scaleZ,x,y,z,skewX,skewY,rotation,rotationX,rotationY,perspective,xPercent,yPercent".split(","), we = G("transform"), be = W + "transform", Pe = G("transformOrigin"), Se = null !== G("perspective"), Ce = Y.Transform = function () { this.perspective = parseFloat(a.defaultTransformPerspective) || 0, this.force3D = a.defaultForce3D !== !1 && Se ? a.defaultForce3D || "auto" : !1 }, Oe = window.SVGElement, ke = function (t, e, i) { var r, s = z.createElementNS("http://www.w3.org/2000/svg", t), n = /([a-z])([A-Z])/g; for (r in i) s.setAttributeNS(null, r.replace(n, "$1-$2").toLowerCase(), i[r]); return e.appendChild(s), s }, Re = z.documentElement, Ae = function () { var t, e, i, r = d || /Android/i.test(B) && !window.chrome; return z.createElementNS && !r && (t = ke("svg", Re), e = ke("rect", t, { width: 100, height: 50, x: 100 }), i = e.getBoundingClientRect().width, e.style[Pe] = "50% 50%", e.style[we] = "scaleX(0.5)", r = i === e.getBoundingClientRect().width && !(c && Se), Re.removeChild(t)), r }(), Me = function (t, e, i, r) { var s, n; r && (n = r.split(" ")).length || (s = t.getBBox(), e = re(e).split(" "), n = [(-1 !== e[0].indexOf("%") ? parseFloat(e[0]) / 100 * s.width : parseFloat(e[0])) + s.x, (-1 !== e[1].indexOf("%") ? parseFloat(e[1]) / 100 * s.height : parseFloat(e[1])) + s.y]), i.xOrigin = parseFloat(n[0]), i.yOrigin = parseFloat(n[1]), t.setAttribute("data-svg-origin", n.join(" ")) }, De = Y.getTransform = function (t, e, i, r) { if (t._gsTransform && i && !r) return t._gsTransform; var n, o, l, h, u, f, p, c, _, d, m = i ? t._gsTransform || new Ce : new Ce, g = 0 > m.scaleX, v = 2e-5, y = 1e5, x = Se ? parseFloat(Q(t, Pe, e, !1, "0 0 0").split(" ")[2]) || m.zOrigin || 0 : 0, T = parseFloat(a.defaultTransformPerspective) || 0; if (we ? o = Q(t, be, e, !0) : t.currentStyle && (o = t.currentStyle.filter.match(A), o = o && 4 === o.length ? [o[0].substr(4), Number(o[2].substr(4)), Number(o[1].substr(4)), o[3].substr(4), m.x || 0, m.y || 0].join(",") : ""), n = !o || "none" === o || "matrix(1, 0, 0, 1, 0, 0)" === o, m.svg = !!(Oe && "function" == typeof t.getBBox && t.getCTM && (!t.parentNode || t.parentNode.getBBox && t.parentNode.getCTM)), m.svg && (n && -1 !== (t.style[we] + "").indexOf("matrix") && (o = t.style[we], n = !1), Me(t, Q(t, Pe, s, !1, "50% 50%") + "", m, t.getAttribute("data-svg-origin")), xe = a.useSVGTransformAttr || Ae, l = t.getAttribute("transform"), n && l && -1 !== l.indexOf("matrix") && (o = l, n = 0)), !n) { for (l = (o || "").match(/(?:\-|\b)[\d\-\.e]+\b/gi) || [], h = l.length; --h > -1;)u = Number(l[h]), l[h] = (f = u - (u |= 0)) ? (0 | f * y + (0 > f ? -.5 : .5)) / y + u : u; if (16 === l.length) { var w, b, P, S, C, O = l[0], k = l[1], R = l[2], M = l[3], D = l[4], N = l[5], X = l[6], z = l[7], E = l[8], F = l[9], I = l[10], Y = l[12], B = l[13], U = l[14], j = l[11], V = Math.atan2(X, I); m.zOrigin && (U = -m.zOrigin, Y = E * U - l[12], B = F * U - l[13], U = I * U + m.zOrigin - l[14]), m.rotationX = V * L, V && (S = Math.cos(-V), C = Math.sin(-V), w = D * S + E * C, b = N * S + F * C, P = X * S + I * C, E = D * -C + E * S, F = N * -C + F * S, I = X * -C + I * S, j = z * -C + j * S, D = w, N = b, X = P), V = Math.atan2(E, I), m.rotationY = V * L, V && (S = Math.cos(-V), C = Math.sin(-V), w = O * S - E * C, b = k * S - F * C, P = R * S - I * C, F = k * C + F * S, I = R * C + I * S, j = M * C + j * S, O = w, k = b, R = P), V = Math.atan2(k, O), m.rotation = V * L, V && (S = Math.cos(-V), C = Math.sin(-V), O = O * S + D * C, b = k * S + N * C, N = k * -C + N * S, X = R * -C + X * S, k = b), m.rotationX && Math.abs(m.rotationX) + Math.abs(m.rotation) > 359.9 && (m.rotationX = m.rotation = 0, m.rotationY += 180), m.scaleX = (0 | Math.sqrt(O * O + k * k) * y + .5) / y, m.scaleY = (0 | Math.sqrt(N * N + F * F) * y + .5) / y, m.scaleZ = (0 | Math.sqrt(X * X + I * I) * y + .5) / y, m.skewX = 0, m.perspective = j ? 1 / (0 > j ? -j : j) : 0, m.x = Y, m.y = B, m.z = U, m.svg && (m.x -= m.xOrigin - (m.xOrigin * O - m.yOrigin * D), m.y -= m.yOrigin - (m.yOrigin * k - m.xOrigin * N)) } else if (!(Se && !r && l.length && m.x === l[4] && m.y === l[5] && (m.rotationX || m.rotationY) || void 0 !== m.x && "none" === Q(t, "display", e))) { var W = l.length >= 6, q = W ? l[0] : 1, G = l[1] || 0, H = l[2] || 0, Z = W ? l[3] : 1; m.x = l[4] || 0, m.y = l[5] || 0, p = Math.sqrt(q * q + G * G), c = Math.sqrt(Z * Z + H * H), _ = q || G ? Math.atan2(G, q) * L : m.rotation || 0, d = H || Z ? Math.atan2(H, Z) * L + _ : m.skewX || 0, Math.abs(d) > 90 && 270 > Math.abs(d) && (g ? (p *= -1, d += 0 >= _ ? 180 : -180, _ += 0 >= _ ? 180 : -180) : (c *= -1, d += 0 >= d ? 180 : -180)), m.scaleX = p, m.scaleY = c, m.rotation = _, m.skewX = d, Se && (m.rotationX = m.rotationY = m.z = 0, m.perspective = T, m.scaleZ = 1), m.svg && (m.x -= m.xOrigin - (m.xOrigin * q - m.yOrigin * G), m.y -= m.yOrigin - (m.yOrigin * Z - m.xOrigin * H)) } m.zOrigin = x; for (h in m) v > m[h] && m[h] > -v && (m[h] = 0) } return i && (t._gsTransform = m, m.svg && (xe && t.style[we] ? ze(t.style, we) : !xe && t.getAttribute("transform") && t.removeAttribute("transform"))), m }, Ne = function (t) { var e, i, r = this.data, s = -r.rotation * N, n = s + r.skewX * N, a = 1e5, o = (0 | Math.cos(s) * r.scaleX * a) / a, l = (0 | Math.sin(s) * r.scaleX * a) / a, h = (0 | Math.sin(n) * -r.scaleY * a) / a, u = (0 | Math.cos(n) * r.scaleY * a) / a, f = this.t.style, p = this.t.currentStyle; if (p) { i = l, l = -h, h = -i, e = p.filter, f.filter = ""; var c, _, m = this.t.offsetWidth, g = this.t.offsetHeight, v = "absolute" !== p.position, y = "progid:DXImageTransform.Microsoft.Matrix(M11=" + o + ", M12=" + l + ", M21=" + h + ", M22=" + u, w = r.x + m * r.xPercent / 100, b = r.y + g * r.yPercent / 100; if (null != r.ox && (c = (r.oxp ? .01 * m * r.ox : r.ox) - m / 2, _ = (r.oyp ? .01 * g * r.oy : r.oy) - g / 2, w += c - (c * o + _ * l), b += _ - (c * h + _ * u)), v ? (c = m / 2, _ = g / 2, y += ", Dx=" + (c - (c * o + _ * l) + w) + ", Dy=" + (_ - (c * h + _ * u) + b) + ")") : y += ", sizingMethod='auto expand')", f.filter = -1 !== e.indexOf("DXImageTransform.Microsoft.Matrix(") ? e.replace(M, y) : y + " " + e, (0 === t || 1 === t) && 1 === o && 0 === l && 0 === h && 1 === u && (v && -1 === y.indexOf("Dx=0, Dy=0") || T.test(e) && 100 !== parseFloat(RegExp.$1) || -1 === e.indexOf("gradient(" && e.indexOf("Alpha")) && f.removeAttribute("filter")), !v) { var P, S, C, O = 8 > d ? 1 : -1; for (c = r.ieOffsetX || 0, _ = r.ieOffsetY || 0, r.ieOffsetX = Math.round((m - ((0 > o ? -o : o) * m + (0 > l ? -l : l) * g)) / 2 + w), r.ieOffsetY = Math.round((g - ((0 > u ? -u : u) * g + (0 > h ? -h : h) * m)) / 2 + b), me = 0; 4 > me; me++)S = ee[me], P = p[S], i = -1 !== P.indexOf("px") ? parseFloat(P) : Z(this.t, S, parseFloat(P), P.replace(x, "")) || 0, C = i !== r[S] ? 2 > me ? -r.ieOffsetX : -r.ieOffsetY : 2 > me ? c - r.ieOffsetX : _ - r.ieOffsetY, f[S] = (r[S] = Math.round(i - C * (0 === me || 2 === me ? 1 : O))) + "px" } } }, Le = Y.set3DTransformRatio = Y.setTransformRatio = function (t) { var e, i, r, s, n, a, o, l, h, u, f, p, _, d, m, g, v, y, x, T, w, b, P, S = this.data, C = this.t.style, O = S.rotation, k = S.rotationX, R = S.rotationY, A = S.scaleX, M = S.scaleY, D = S.scaleZ, L = S.x, X = S.y, z = S.z, E = S.svg, F = S.perspective, I = S.force3D; if (!(((1 !== t && 0 !== t || "auto" !== I || this.tween._totalTime !== this.tween._totalDuration && this.tween._totalTime) && I || z || F || R || k) && (!xe || !E) && Se)) return O || S.skewX || E ? (O *= N, b = S.skewX * N, P = 1e5, e = Math.cos(O) * A, s = Math.sin(O) * A, i = Math.sin(O - b) * -M, n = Math.cos(O - b) * M, b && "simple" === S.skewType && (v = Math.tan(b), v = Math.sqrt(1 + v * v), i *= v, n *= v, S.skewY && (e *= v, s *= v)), E && (L += S.xOrigin - (S.xOrigin * e + S.yOrigin * i), X += S.yOrigin - (S.xOrigin * s + S.yOrigin * n), d = 1e-6, d > L && L > -d && (L = 0), d > X && X > -d && (X = 0)), x = (0 | e * P) / P + "," + (0 | s * P) / P + "," + (0 | i * P) / P + "," + (0 | n * P) / P + "," + L + "," + X + ")", E && xe ? this.t.setAttribute("transform", "matrix(" + x) : C[we] = (S.xPercent || S.yPercent ? "translate(" + S.xPercent + "%," + S.yPercent + "%) matrix(" : "matrix(") + x) : C[we] = (S.xPercent || S.yPercent ? "translate(" + S.xPercent + "%," + S.yPercent + "%) matrix(" : "matrix(") + A + ",0,0," + M + "," + L + "," + X + ")", void 0; if (c && (d = 1e-4, d > A && A > -d && (A = D = 2e-5), d > M && M > -d && (M = D = 2e-5), !F || S.z || S.rotationX || S.rotationY || (F = 0)), O || S.skewX) O *= N, m = e = Math.cos(O), g = s = Math.sin(O), S.skewX && (O -= S.skewX * N, m = Math.cos(O), g = Math.sin(O), "simple" === S.skewType && (v = Math.tan(S.skewX * N), v = Math.sqrt(1 + v * v), m *= v, g *= v, S.skewY && (e *= v, s *= v))), i = -g, n = m; else { if (!(R || k || 1 !== D || F || E)) return C[we] = (S.xPercent || S.yPercent ? "translate(" + S.xPercent + "%," + S.yPercent + "%) translate3d(" : "translate3d(") + L + "px," + X + "px," + z + "px)" + (1 !== A || 1 !== M ? " scale(" + A + "," + M + ")" : ""), void 0; e = n = 1, i = s = 0 } h = 1, r = a = o = l = u = f = 0, p = F ? -1 / F : 0, _ = S.zOrigin, d = 1e-6, T = ",", w = "0", O = R * N, O && (m = Math.cos(O), g = Math.sin(O), o = -g, u = p * -g, r = e * g, a = s * g, h = m, p *= m, e *= m, s *= m), O = k * N, O && (m = Math.cos(O), g = Math.sin(O), v = i * m + r * g, y = n * m + a * g, l = h * g, f = p * g, r = i * -g + r * m, a = n * -g + a * m, h *= m, p *= m, i = v, n = y), 1 !== D && (r *= D, a *= D, h *= D, p *= D), 1 !== M && (i *= M, n *= M, l *= M, f *= M), 1 !== A && (e *= A, s *= A, o *= A, u *= A), (_ || E) && (_ && (L += r * -_, X += a * -_, z += h * -_ + _), E && (L += S.xOrigin - (S.xOrigin * e + S.yOrigin * i), X += S.yOrigin - (S.xOrigin * s + S.yOrigin * n)), d > L && L > -d && (L = w), d > X && X > -d && (X = w), d > z && z > -d && (z = 0)), x = S.xPercent || S.yPercent ? "translate(" + S.xPercent + "%," + S.yPercent + "%) matrix3d(" : "matrix3d(", x += (d > e && e > -d ? w : e) + T + (d > s && s > -d ? w : s) + T + (d > o && o > -d ? w : o), x += T + (d > u && u > -d ? w : u) + T + (d > i && i > -d ? w : i) + T + (d > n && n > -d ? w : n), k || R ? (x += T + (d > l && l > -d ? w : l) + T + (d > f && f > -d ? w : f) + T + (d > r && r > -d ? w : r), x += T + (d > a && a > -d ? w : a) + T + (d > h && h > -d ? w : h) + T + (d > p && p > -d ? w : p) + T) : x += ",0,0,0,0,1,0,", x += L + T + X + T + z + T + (F ? 1 + -z / F : 1) + ")", C[we] = x }; h = Ce.prototype, h.x = h.y = h.z = h.skewX = h.skewY = h.rotation = h.rotationX = h.rotationY = h.zOrigin = h.xPercent = h.yPercent = 0, h.scaleX = h.scaleY = h.scaleZ = 1, ve("transform,scale,scaleX,scaleY,scaleZ,x,y,z,rotation,rotationX,rotationY,rotationZ,skewX,skewY,shortRotation,shortRotationX,shortRotationY,shortRotationZ,transformOrigin,svgOrigin,transformPerspective,directionalRotation,parseTransform,force3D,skewType,xPercent,yPercent", { parser: function (t, e, i, r, n, o, l) { if (r._lastParsedTransform === l) return n; r._lastParsedTransform = l; var h, u, f, p, c, _, d, m = r._transform = De(t, s, !0, l.parseTransform), g = t.style, v = 1e-6, y = Te.length, x = l, T = {}; if ("string" == typeof x.transform && we) f = F.style, f[we] = x.transform, f.display = "block", f.position = "absolute", z.body.appendChild(F), h = De(F, null, !1), z.body.removeChild(F); else if ("object" == typeof x) { if (h = { scaleX: ne(null != x.scaleX ? x.scaleX : x.scale, m.scaleX), scaleY: ne(null != x.scaleY ? x.scaleY : x.scale, m.scaleY), scaleZ: ne(x.scaleZ, m.scaleZ), x: ne(x.x, m.x), y: ne(x.y, m.y), z: ne(x.z, m.z), xPercent: ne(x.xPercent, m.xPercent), yPercent: ne(x.yPercent, m.yPercent), perspective: ne(x.transformPerspective, m.perspective) }, d = x.directionalRotation, null != d) if ("object" == typeof d) for (f in d) x[f] = d[f]; else x.rotation = d; "string" == typeof x.x && -1 !== x.x.indexOf("%") && (h.x = 0, h.xPercent = ne(x.x, m.xPercent)), "string" == typeof x.y && -1 !== x.y.indexOf("%") && (h.y = 0, h.yPercent = ne(x.y, m.yPercent)), h.rotation = ae("rotation" in x ? x.rotation : "shortRotation" in x ? x.shortRotation + "_short" : "rotationZ" in x ? x.rotationZ : m.rotation, m.rotation, "rotation", T), Se && (h.rotationX = ae("rotationX" in x ? x.rotationX : "shortRotationX" in x ? x.shortRotationX + "_short" : m.rotationX || 0, m.rotationX, "rotationX", T), h.rotationY = ae("rotationY" in x ? x.rotationY : "shortRotationY" in x ? x.shortRotationY + "_short" : m.rotationY || 0, m.rotationY, "rotationY", T)), h.skewX = null == x.skewX ? m.skewX : ae(x.skewX, m.skewX), h.skewY = null == x.skewY ? m.skewY : ae(x.skewY, m.skewY), (u = h.skewY - m.skewY) && (h.skewX += u, h.rotation += u) } for (Se && null != x.force3D && (m.force3D = x.force3D, _ = !0), m.skewType = x.skewType || m.skewType || a.defaultSkewType, c = m.force3D || m.z || m.rotationX || m.rotationY || h.z || h.rotationX || h.rotationY || h.perspective, c || null == x.scale || (h.scaleZ = 1); --y > -1;)i = Te[y], p = h[i] - m[i], (p > v || -v > p || null != x[i] || null != X[i]) && (_ = !0, n = new _e(m, i, m[i], p, n), i in T && (n.e = T[i]), n.xs0 = 0, n.plugin = o, r._overwriteProps.push(n.n)); return p = x.transformOrigin, m.svg && (p || x.svgOrigin) && (Me(t, re(p), h, x.svgOrigin), n = new _e(m, "xOrigin", m.xOrigin, h.xOrigin - m.xOrigin, n, -1, "transformOrigin"), n.b = m.xOrigin, n.e = n.xs0 = h.xOrigin, n = new _e(m, "yOrigin", m.yOrigin, h.yOrigin - m.yOrigin, n, -1, "transformOrigin"), n.b = m.yOrigin, n.e = n.xs0 = h.yOrigin, p = xe ? null : "0px 0px"), (p || Se && c && m.zOrigin) && (we ? (_ = !0, i = Pe, p = (p || Q(t, i, s, !1, "50% 50%")) + "", n = new _e(g, i, 0, 0, n, -1, "transformOrigin"), n.b = g[i], n.plugin = o, Se ? (f = m.zOrigin, p = p.split(" "), m.zOrigin = (p.length > 2 && (0 === f || "0px" !== p[2]) ? parseFloat(p[2]) : f) || 0, n.xs0 = n.e = p[0] + " " + (p[1] || "50%") + " 0px", n = new _e(m, "zOrigin", 0, 0, n, -1, n.n), n.b = f, n.xs0 = n.e = m.zOrigin) : n.xs0 = n.e = p) : re(p + "", m)), _ && (r._transformType = m.svg && xe || !c && 3 !== this._transformType ? 2 : 3), n }, prefix: !0 }), ve("boxShadow", { defaultValue: "0px 0px 0px 0px #999", prefix: !0, color: !0, multi: !0, keyword: "inset" }), ve("borderRadius", { defaultValue: "0px", parser: function (t, e, i, n, a) { e = this.format(e); var o, l, h, u, f, p, c, _, d, m, g, v, y, x, T, w, b = ["borderTopLeftRadius", "borderTopRightRadius", "borderBottomRightRadius", "borderBottomLeftRadius"], P = t.style; for (d = parseFloat(t.offsetWidth), m = parseFloat(t.offsetHeight), o = e.split(" "), l = 0; b.length > l; l++)this.p.indexOf("border") && (b[l] = G(b[l])), f = u = Q(t, b[l], s, !1, "0px"), -1 !== f.indexOf(" ") && (u = f.split(" "), f = u[0], u = u[1]), p = h = o[l], c = parseFloat(f), v = f.substr((c + "").length), y = "=" === p.charAt(1), y ? (_ = parseInt(p.charAt(0) + "1", 10), p = p.substr(2), _ *= parseFloat(p), g = p.substr((_ + "").length - (0 > _ ? 1 : 0)) || "") : (_ = parseFloat(p), g = p.substr((_ + "").length)), "" === g && (g = r[i] || v), g !== v && (x = Z(t, "borderLeft", c, v), T = Z(t, "borderTop", c, v), "%" === g ? (f = 100 * (x / d) + "%", u = 100 * (T / m) + "%") : "em" === g ? (w = Z(t, "borderLeft", 1, "em"), f = x / w + "em", u = T / w + "em") : (f = x + "px", u = T + "px"), y && (p = parseFloat(f) + _ + g, h = parseFloat(u) + _ + g)), a = de(P, b[l], f + " " + u, p + " " + h, !1, "0px", a); return a }, prefix: !0, formatter: fe("0px 0px 0px 0px", !1, !0) }), ve("backgroundPosition", { defaultValue: "0 0", parser: function (t, e, i, r, n, a) { var o, l, h, u, f, p, c = "background-position", _ = s || H(t, null), m = this.format((_ ? d ? _.getPropertyValue(c + "-x") + " " + _.getPropertyValue(c + "-y") : _.getPropertyValue(c) : t.currentStyle.backgroundPositionX + " " + t.currentStyle.backgroundPositionY) || "0 0"), g = this.format(e); if (-1 !== m.indexOf("%") != (-1 !== g.indexOf("%")) && (p = Q(t, "backgroundImage").replace(O, ""), p && "none" !== p)) { for (o = m.split(" "), l = g.split(" "), I.setAttribute("src", p), h = 2; --h > -1;)m = o[h], u = -1 !== m.indexOf("%"), u !== (-1 !== l[h].indexOf("%")) && (f = 0 === h ? t.offsetWidth - I.width : t.offsetHeight - I.height, o[h] = u ? parseFloat(m) / 100 * f + "px" : 100 * (parseFloat(m) / f) + "%"); m = o.join(" ") } return this.parseComplex(t.style, m, g, n, a) }, formatter: re }), ve("backgroundSize", { defaultValue: "0 0", formatter: re }), ve("perspective", { defaultValue: "0px", prefix: !0 }), ve("perspectiveOrigin", { defaultValue: "50% 50%", prefix: !0 }), ve("transformStyle", { prefix: !0 }), ve("backfaceVisibility", { prefix: !0 }), ve("userSelect", { prefix: !0 }), ve("margin", { parser: pe("marginTop,marginRight,marginBottom,marginLeft") }), ve("padding", { parser: pe("paddingTop,paddingRight,paddingBottom,paddingLeft") }), ve("clip", { defaultValue: "rect(0px,0px,0px,0px)", parser: function (t, e, i, r, n, a) { var o, l, h; return 9 > d ? (l = t.currentStyle, h = 8 > d ? " " : ",", o = "rect(" + l.clipTop + h + l.clipRight + h + l.clipBottom + h + l.clipLeft + ")", e = this.format(e).split(",").join(h)) : (o = this.format(Q(t, this.p, s, !1, this.dflt)), e = this.format(e)), this.parseComplex(t.style, o, e, n, a) } }), ve("textShadow", { defaultValue: "0px 0px 0px #999", color: !0, multi: !0 }), ve("autoRound,strictUnits", { parser: function (t, e, i, r, s) { return s } }), ve("border", { defaultValue: "0px solid #000", parser: function (t, e, i, r, n, a) { return this.parseComplex(t.style, this.format(Q(t, "borderTopWidth", s, !1, "0px") + " " + Q(t, "borderTopStyle", s, !1, "solid") + " " + Q(t, "borderTopColor", s, !1, "#000")), this.format(e), n, a) }, color: !0, formatter: function (t) { var e = t.split(" "); return e[0] + " " + (e[1] || "solid") + " " + (t.match(ue) || ["#000"])[0] } }), ve("borderWidth", { parser: pe("borderTopWidth,borderRightWidth,borderBottomWidth,borderLeftWidth") }), ve("float,cssFloat,styleFloat", { parser: function (t, e, i, r, s) { var n = t.style, a = "cssFloat" in n ? "cssFloat" : "styleFloat"; return new _e(n, a, 0, 0, s, -1, i, !1, 0, n[a], e) } }); var Xe = function (t) { var e, i = this.t, r = i.filter || Q(this.data, "filter") || "", s = 0 | this.s + this.c * t; 100 === s && (-1 === r.indexOf("atrix(") && -1 === r.indexOf("radient(") && -1 === r.indexOf("oader(") ? (i.removeAttribute("filter"), e = !Q(this.data, "filter")) : (i.filter = r.replace(b, ""), e = !0)), e || (this.xn1 && (i.filter = r = r || "alpha(opacity=" + s + ")"), -1 === r.indexOf("pacity") ? 0 === s && this.xn1 || (i.filter = r + " alpha(opacity=" + s + ")") : i.filter = r.replace(T, "opacity=" + s)) }; ve("opacity,alpha,autoAlpha", { defaultValue: "1", parser: function (t, e, i, r, n, a) { var o = parseFloat(Q(t, "opacity", s, !1, "1")), l = t.style, h = "autoAlpha" === i; return "string" == typeof e && "=" === e.charAt(1) && (e = ("-" === e.charAt(0) ? -1 : 1) * parseFloat(e.substr(2)) + o), h && 1 === o && "hidden" === Q(t, "visibility", s) && 0 !== e && (o = 0), U ? n = new _e(l, "opacity", o, e - o, n) : (n = new _e(l, "opacity", 100 * o, 100 * (e - o), n), n.xn1 = h ? 1 : 0, l.zoom = 1, n.type = 2, n.b = "alpha(opacity=" + n.s + ")", n.e = "alpha(opacity=" + (n.s + n.c) + ")", n.data = t, n.plugin = a, n.setRatio = Xe), h && (n = new _e(l, "visibility", 0, 0, n, -1, null, !1, 0, 0 !== o ? "inherit" : "hidden", 0 === e ? "hidden" : "inherit"), n.xs0 = "inherit", r._overwriteProps.push(n.n), r._overwriteProps.push(i)), n } }); var ze = function (t, e) { e && (t.removeProperty ? (("ms" === e.substr(0, 2) || "webkit" === e.substr(0, 6)) && (e = "-" + e), t.removeProperty(e.replace(S, "-$1").toLowerCase())) : t.removeAttribute(e)) }, Ee = function (t) { if (this.t._gsClassPT = this, 1 === t || 0 === t) { this.t.setAttribute("class", 0 === t ? this.b : this.e); for (var e = this.data, i = this.t.style; e;)e.v ? i[e.p] = e.v : ze(i, e.p), e = e._next; 1 === t && this.t._gsClassPT === this && (this.t._gsClassPT = null) } else this.t.getAttribute("class") !== this.e && this.t.setAttribute("class", this.e) }; ve("className", { parser: function (t, e, r, n, a, o, l) { var h, u, f, p, c, _ = t.getAttribute("class") || "", d = t.style.cssText; if (a = n._classNamePT = new _e(t, r, 0, 0, a, 2), a.setRatio = Ee, a.pr = -11, i = !0, a.b = _, u = K(t, s), f = t._gsClassPT) { for (p = {}, c = f.data; c;)p[c.p] = 1, c = c._next; f.setRatio(1) } return t._gsClassPT = a, a.e = "=" !== e.charAt(1) ? e : _.replace(RegExp("\\s*\\b" + e.substr(2) + "\\b"), "") + ("+" === e.charAt(0) ? " " + e.substr(2) : ""), t.setAttribute("class", a.e), h = J(t, u, K(t), l, p), t.setAttribute("class", _), a.data = h.firstMPT, t.style.cssText = d, a = a.xfirst = n.parse(t, h.difs, a, o) } }); var Fe = function (t) { if ((1 === t || 0 === t) && this.data._totalTime === this.data._totalDuration && "isFromStart" !== this.data.data) { var e, i, r, s, n, a = this.t.style, o = l.transform.parse; if ("all" === this.e) a.cssText = "", s = !0; else for (e = this.e.split(" ").join("").split(","), r = e.length; --r > -1;)i = e[r], l[i] && (l[i].parse === o ? s = !0 : i = "transformOrigin" === i ? Pe : l[i].p), ze(a, i); s && (ze(a, we), n = this.t._gsTransform, n && (n.svg && this.t.removeAttribute("data-svg-origin"), delete this.t._gsTransform)) } }; for (ve("clearProps", { parser: function (t, e, r, s, n) { return n = new _e(t, r, 0, 0, n, 2), n.setRatio = Fe, n.e = e, n.pr = -10, n.data = s._tween, i = !0, n } }), h = "bezier,throwProps,physicsProps,physics2D".split(","), me = h.length; me--;)ye(h[me]); h = a.prototype, h._firstPT = h._lastParsedTransform = h._transform = null, h._onInitTween = function (t, e, o) { if (!t.nodeType) return !1; this._target = t, this._tween = o, this._vars = e, u = e.autoRound, i = !1, r = e.suffixMap || a.suffixMap, s = H(t, ""), n = this._overwriteProps; var h, c, d, m, g, v, y, x, T, b = t.style; if (f && "" === b.zIndex && (h = Q(t, "zIndex", s), ("auto" === h || "" === h) && this._addLazySet(b, "zIndex", 0)), "string" == typeof e && (m = b.cssText, h = K(t, s), b.cssText = m + ";" + e, h = J(t, h, K(t)).difs, !U && w.test(e) && (h.opacity = parseFloat(RegExp.$1)), e = h, b.cssText = m), this._firstPT = c = e.className ? l.className.parse(t, e.className, "className", this, null, null, e) : this.parse(t, e, null), this._transformType) { for (T = 3 === this._transformType, we ? p && (f = !0, "" === b.zIndex && (y = Q(t, "zIndex", s), ("auto" === y || "" === y) && this._addLazySet(b, "zIndex", 0)), _ && this._addLazySet(b, "WebkitBackfaceVisibility", this._vars.WebkitBackfaceVisibility || (T ? "visible" : "hidden"))) : b.zoom = 1, d = c; d && d._next;)d = d._next; x = new _e(t, "transform", 0, 0, null, 2), this._linkCSSP(x, null, d), x.setRatio = we ? Le : Ne, x.data = this._transform || De(t, s, !0), x.tween = o, x.pr = -1, n.pop() } if (i) { for (; c;) { for (v = c._next, d = m; d && d.pr > c.pr;)d = d._next; (c._prev = d ? d._prev : g) ? c._prev._next = c : m = c, (c._next = d) ? d._prev = c : g = c, c = v } this._firstPT = m } return !0 }, h.parse = function (t, e, i, n) {
      var a, o, h, f, p, c, _, d, m, g, v = t.style; for (a in e) c = e[a], o = l[a], o ? i = o.parse(t, c, a, this, i, n, e) : (p = Q(t, a, s) + "", m = "string" == typeof c, "color" === a || "fill" === a || "stroke" === a || -1 !== a.indexOf("Color") || m && P.test(c) ? (m || (c = he(c), c = (c.length > 3 ? "rgba(" : "rgb(") + c.join(",") + ")"), i = de(v, a, p, c, !0, "transparent", i, 0, n)) : !m || -1 === c.indexOf(" ") && -1 === c.indexOf(",") ? (h = parseFloat(p), _ = h || 0 === h ? p.substr((h + "").length) : "", ("" === p || "auto" === p) && ("width" === a || "height" === a ? (h = ie(t, a, s), _ = "px") : "left" === a || "top" === a ? (h = $(t, a, s), _ = "px") : (h = "opacity" !== a ? 0 : 1, _ = "")), g = m && "=" === c.charAt(1), g ? (f = parseInt(c.charAt(0) + "1", 10), c = c.substr(2), f *= parseFloat(c), d = c.replace(x, "")) : (f = parseFloat(c), d = m ? c.replace(x, "") : ""), "" === d && (d = a in r ? r[a] : _), c = f || 0 === f ? (g ? f + h : f) + d : e[a], _ !== d && "" !== d && (f || 0 === f) && h && (h = Z(t, a, h, _), "%" === d ? (h /= Z(t, a, 100, "%") / 100, e.strictUnits !== !0 && (p = h + "%")) : "em" === d ? h /= Z(t, a, 1, "em") : "px" !== d && (f = Z(t, a, f, d), d = "px"), g && (f || 0 === f) && (c = f + h + d)), g && (f += h), !h && 0 !== h || !f && 0 !== f ? void 0 !== v[a] && (c || "NaN" != c + "" && null != c) ? (i = new _e(v, a, f || h || 0, 0, i, -1, a, !1, 0, p, c), i.xs0 = "none" !== c || "display" !== a && -1 === a.indexOf("Style") ? c : p) : V("invalid " + a + " tween value: " + e[a]) : (i = new _e(v, a, h, f - h, i, 0, a, u !== !1 && ("px" === d || "zIndex" === a), 0, p, c), i.xs0 = d)) : i = de(v, a, p, c, !0, null, i, 0, n)), n && i && !i.plugin && (i.plugin = n);
      return i
    }, h.setRatio = function (t) { var e, i, r, s = this._firstPT, n = 1e-6; if (1 !== t || this._tween._time !== this._tween._duration && 0 !== this._tween._time) if (t || this._tween._time !== this._tween._duration && 0 !== this._tween._time || this._tween._rawPrevTime === -1e-6) for (; s;) { if (e = s.c * t + s.s, s.r ? e = Math.round(e) : n > e && e > -n && (e = 0), s.type) if (1 === s.type) if (r = s.l, 2 === r) s.t[s.p] = s.xs0 + e + s.xs1 + s.xn1 + s.xs2; else if (3 === r) s.t[s.p] = s.xs0 + e + s.xs1 + s.xn1 + s.xs2 + s.xn2 + s.xs3; else if (4 === r) s.t[s.p] = s.xs0 + e + s.xs1 + s.xn1 + s.xs2 + s.xn2 + s.xs3 + s.xn3 + s.xs4; else if (5 === r) s.t[s.p] = s.xs0 + e + s.xs1 + s.xn1 + s.xs2 + s.xn2 + s.xs3 + s.xn3 + s.xs4 + s.xn4 + s.xs5; else { for (i = s.xs0 + e + s.xs1, r = 1; s.l > r; r++)i += s["xn" + r] + s["xs" + (r + 1)]; s.t[s.p] = i } else -1 === s.type ? s.t[s.p] = s.xs0 : s.setRatio && s.setRatio(t); else s.t[s.p] = e + s.xs0; s = s._next } else for (; s;)2 !== s.type ? s.t[s.p] = s.b : s.setRatio(t), s = s._next; else for (; s;)2 !== s.type ? s.t[s.p] = s.e : s.setRatio(t), s = s._next }, h._enableTransforms = function (t) { this._transform = this._transform || De(this._target, s, !0), this._transformType = this._transform.svg && xe || !t && 3 !== this._transformType ? 2 : 3 }; var Ie = function () { this.t[this.p] = this.e, this.data._linkCSSP(this, this._next, null, !0) }; h._addLazySet = function (t, e, i) { var r = this._firstPT = new _e(t, e, 0, 0, this._firstPT, 2); r.e = i, r.setRatio = Ie, r.data = this }, h._linkCSSP = function (t, e, i, r) { return t && (e && (e._prev = t), t._next && (t._next._prev = t._prev), t._prev ? t._prev._next = t._next : this._firstPT === t && (this._firstPT = t._next, r = !0), i ? i._next = t : r || null !== this._firstPT || (this._firstPT = t), t._next = e, t._prev = i), t }, h._kill = function (e) { var i, r, s, n = e; if (e.autoAlpha || e.alpha) { n = {}; for (r in e) n[r] = e[r]; n.opacity = 1, n.autoAlpha && (n.visibility = 1) } return e.className && (i = this._classNamePT) && (s = i.xfirst, s && s._prev ? this._linkCSSP(s._prev, i._next, s._prev._prev) : s === this._firstPT && (this._firstPT = i._next), i._next && this._linkCSSP(i._next, i._next._next, s._prev), this._classNamePT = null), t.prototype._kill.call(this, n) }; var Ye = function (t, e, i) { var r, s, n, a; if (t.slice) for (s = t.length; --s > -1;)Ye(t[s], e, i); else for (r = t.childNodes, s = r.length; --s > -1;)n = r[s], a = n.type, n.style && (e.push(K(n)), i && i.push(n)), 1 !== a && 9 !== a && 11 !== a || !n.childNodes.length || Ye(n, e, i) }; return a.cascadeTo = function (t, i, r) { var s, n, a, o, l = e.to(t, i, r), h = [l], u = [], f = [], p = [], c = e._internals.reservedProps; for (t = l._targets || l.target, Ye(t, u, p), l.render(i, !0, !0), Ye(t, f), l.render(0, !0, !0), l._enabled(!0), s = p.length; --s > -1;)if (n = J(p[s], u[s], f[s]), n.firstMPT) { n = n.difs; for (a in r) c[a] && (n[a] = r[a]); o = {}; for (a in n) o[a] = u[s][a]; h.push(e.fromTo(p[s], i, o, n)) } return h }, t.activate([a]), a
  }, !0)
}), _gsScope._gsDefine && _gsScope._gsQueue.pop()(), function (t) { "use strict"; var e = function () { return (_gsScope.GreenSockGlobals || _gsScope)[t] }; "function" == typeof define && define.amd ? define(["TweenLite"], e) : "undefined" != typeof module && module.exports && (require("../TweenLite.js"), module.exports = e()) }("CSSPlugin");
var zindex = 1030;
var debug = true;
////2023-07-18 : if (user_ip == '108.180.234.14') console.log('429             --------------------------------------------');

(function ($) {
  "use strict";
  $.fn.changeElementType = function (newType) {
    var attrs = {};

    $.each(this[0].attributes, function (idx, attr) {
      attrs[attr.nodeName] = attr.nodeValue;
    });

    this.replaceWith(function () {
      return $("<" + newType + "/>", attrs).append($(this).contents());
    });
  };
})(jQuery);

////2023-07-18 : if (user_ip == '108.180.234.14') console.log('444             --------------------------------------------');

function isNumeric(n) {
  'use strict';
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function isMobile() {
  'use strict';
  if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
    return true;
  } else {
    return false;
  }
}

function throttle(ms, callback) {
  'use strict';
  var timer, lastCall = 0;

  return function () {
    var now = new Date().getTime(),
      diff = now - lastCall;
    if (diff >= ms) {
      lastCall = now;
      callback.apply(this, arguments);
    }
  };
}

////2023-07-18 : if (user_ip == '108.180.234.14') console.log('502');

/**
 * shuffle function.
 *
 * @access public
 * @param mixed o
 * @return void
 */
function shuffle(o) {
  for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  return o;
}

////2023-07-18 : if (user_ip == '108.180.234.14') console.log('489             --------------------------------------------');

/**
 * show_listings function.
 *
 * @access public
 * @param mixed options
 * @return void
 */
function show_listings(options) {
  'use strict';
  ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('500 show_listings --------------------------------------------------------');
  // CONSOLE.LOG the options , the id's etc
  console.log(JSON.stringify(options));
  var orderby = options.orderby || 'featured',
    clear = options.clear || false,
    type = options.type || '',
    offset = options.offset || '',
    str = options.str || '',
    container = options.container || '#listing-load',
    table = options.table || 'data',
    $body = $('body'),
    dataX = null;

  if (Array.isArray(str)) str = str.toString();
  if (type === 'city') {
    dataX = {
      offset: offset,
      city: str,
      orderby: orderby,
      container: container
    };
  } else if (type === 'partner') {
    ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('523   partner=' + str + '   container: ' + container + ' --------------------------------------------');
    dataX = {
      offset: offset,
      partner: str,
      orderby: orderby,
      container: container,
    };
  } else {
    dataX = {
      ids: str,
      offset: offset,
      orderby: orderby,
      table: table,
      container: container
    };
  }
  ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('533             --------------------------------------------');

  $body.find(container).append('<div class="btn btn-primary loading"><i class="icon-spinner"></i> Loading More</div>');

  ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('before ajax get_listings (' + JSON.stringify(dataX) + ')--------------------------------------------------------');

  $.ajax({
    url: '/__inc/includes/get_listings.php',
    data: dataX,
    type: 'POST'
  }).done(function (data, string, xhr) {
    ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('get_listings ajax');
    $('.loading', container).remove();
    data = $.trim(data);
    var $container = $body.find(container);

    if (data) {
      if (clear) {
        $(dataX.container).html(data);
      } else {
        $container.append(data);
      }

      ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('ajax get_listings (' + data + ')--------------------------------------------------------');

      var $panel_container = $container.parent();
      $panel_container.on('scroll', function () {
        if (($panel_container.find('.loadmore').length > 0) &&
          ($panel_container.find('.loadmore').offset().top - $panel_container.height() < 400)) {
          $panel_container.find('.loadmore').trigger('click');
        }
      });

      $('section[role=PageView]').scroll(function () {
        if (($container.find('.loadmore').length > 0) &&
          ($container.find('.loadmore').offset().top - $container.height() < 100)) {

          $container.find('.loadmore').trigger('click');
        }
      });

      if (data.indexOf("id='no-listings'") >= 0) {
        if ($('#no-listings').prev().attr('class') == 'listing-page') {
          $('#no-listings').html('');
        }
      }

      listing_ids = str.split(',');
      for (var lid in listing_ids) {
        updateFavStars(listing_ids[lid]);
      }

      //Activate Tooltips
      $('[data-toggle="tooltip"]').tooltip();
    } else {
      // $container.html('');
      openNotification({ message: 'No Listings Found <button onclick="openSearch();" class="btn-btn-primary">Try searching again</button>' });
    }

  });













  if (type == 'partner') {
    ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('523   partner     --------------------------------------------');
    var alias = $('#partner_name').val();
    var address = window.location.href;
    var base = address.split('?')[0];

    // TODO: Get proper alias
    //history.pushState({},document.title,base+'?partner='+alias);
  }
}
////2023-07-18 : if (user_ip == '108.180.234.14') console.log('597             --------------------------------------------');

/**
 * show_roommates function.
 *
 * @access public
 * @param mixed options
 * @return void
 */
function show_roommates(options) {
  'use strict';

  var urlParams = new URLSearchParams(window.location.search);
  ////2023-07-18 : if (user_ip == '108.180.234.14') console.log(urlParams);
  if (typeof urlParams != 'undefined') {

  }
  var sex = parseInt(urlParams.get('sex')),
    program = parseInt(urlParams.get('program')),
    age = parseInt(urlParams.get('age')),
    occupation = parseInt(urlParams.get('occupation')),
    htype = parseInt(urlParams.get('htype')),
    smoking = parseInt(urlParams.get('smoking')),
    rent = parseInt(urlParams.get('rent')),
    distance = parseInt(urlParams.get('distance')),
    pets = parseInt(urlParams.get('pets')),
    sharing = parseInt(urlParams.get('sharing')),
    activity = parseInt(urlParams.get('activity')),
    hours = parseInt(urlParams.get('hours')),
    socially = parseInt(urlParams.get('socially')),
    diet = parseInt(urlParams.get('diet'));

  ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('show_roommates');
  var orderby = options.orderby || '',
    clear = options.clear || false,
    type = options.type || '',
    offset = options.offset || '',
    str = options.str || '',
    container = options.container || '#roommate-load',
    table = options.table || 'data',
    $body = $('body'),
    data = {
      ids: str,
      offset: offset,
      orderby: orderby,
      table: table,
      container: container,
      sex: sex,
      program: program,
      age: age,
      occupation: occupation,
      htype: htype,
      smoking: smoking,
      rent: rent,
      distance: distance,
      pets: pets,
      sharing: sharing,
      activity: activity,
      hours: hours,
      socially: socially,
      diet: diet
    };

  $body.find(container).append('<div class="loading btn btn-primary"><i class="icon-spinner"></i> Loading</div>');

  $.ajax({
    url: '/__inc/includes/get_roommates.php',
    data: data,
    type: 'POST'
  }).done(function (data, string, xhr) {
    if (debug) {
      //console.log('get_roommates ajax');
    }
    $('.loading', container).remove();
    data = $.trim(data);
    var $container = $body.find(container);
    if (data != '[]') {
      if (clear) {
        $container.html(data);
      } else {
        $container.append(data);
      }

      var $panel_container = $container.parent();
      $panel_container.on('scroll', function () {
        if (($panel_container.find('.loadmore').length > 0)
          && ($panel_container.find('.loadmore').offset().top - $panel_container.height() < 400)) {
          $panel_container.find('.loadmore').trigger('click');
        }
      });

      if (data.indexOf("id='no-roommates'") >= 0) {
        if ($('#no-roommates').prev().attr('class') == 'roommate-page') {
          $('#no-roommates').html('');
        }
      }

      roommate_ids = str.split(',');
      for (var rid in roommate_ids) {
        updateFavStars(roommate_ids[rid]);
      }
    } else {
      $container.html('<div id="notfound">' +
        '            <div class="notfound">' +
        '                <div class="notfound-404">' +
        '                    <h3>no roommates found</h3>\n' +
        '                    <a class="btn btn-primary w-100" href="/User/Add-User/new_user.php">Post Your roommate profile now</a>\n' +
        '                </div>' +
        '            </div>' +
        '        </div>');
      // openNotification({message:'No Roommates Found'});
    }
    openAlert({ remove: true });

  });
}
//2023-07-18 : if (user_ip == '108.180.234.14') console.log('712             --------------------------------------------');

//////////////////////////////////////////////////////////////
//
//	Show Users
//
//////////////////////////////////////////////////////////////
function show_users(options) {

  var orderby = options.orderby || '',
    clear = options.clear || false,
    type = options.type || '',
    offset = options.offset || '',
    str = options.str || '',
    container = options.container || '#user-load',
    $body = $('body');

  newdata = {
    ids: str,
    offset: offset,
    orderby: orderby,
    container: container
  };

  $body.find(container).prepend('<div class="loading btn btn-primary"><i class="icon-spinner"></i> Loading</div>');

  $.ajax({
    url: '/__inc/php/get_users.php',
    data: newdata,
    type: 'POST'
  }).done(function (data, str, xhr) {
    $('.loading', container).remove();
    //data = $.trim(data);
    $container = $body.find(container);

    if (data) {

      if (clear) $container.html(data);
      else $container.append(data);

      //if (clear) {
      $container.on('scroll', function () {

        if (($container.find('.loadmore').length > 0) &&
          ($container.find('.loadmore').offset().top - $container.height() < 100)) {

          $container.find('.loadmore').trigger('click');
        }
      });
      //}
    } else {
      openNotification({ message: 'No Users Found' })
    }

  });
  //return false;
}


/////////////////////////////////////////////////////////
//
//  Pane Sliders
//
/////////////////////////////////////////////////////////
//	Partial slide only 80% on screen
function slidePanel(args) {
  var $pane = args.pane || false,
    open = args.open || false,
    dur = args.duration || 250,
    property = args.property || 'marginLeft';

  if (open) {
    if (property == 'marginLeft')
      TweenLite.to($pane, 0.25, { css: { marginLeft: 0, paddingRight: 0 } });
    else
      TweenLite.to($pane, 0.25, { css: { marginRight: 0, paddingRight: 0 } });
    $pane.removeClass('closed').addClass('opened');
  } else if (!open) {
    var newleft = -($pane.width()) + 49,
      newright = -($pane.width()) + 49;
    if (property == 'marginLeft')
      TweenLite.to($pane, 0.25, { css: { marginLeft: newleft, paddingRight: 49 } });
    else
      TweenLite.to($pane, 0.25, { css: { marginRight: newright, paddingRight: 49 } });
    $pane.removeClass('opened').addClass('closed');
  }
  return true;
}


/////////////////////////////////////////////////////////
//
//  OPEN PANE (PANEL)
//
/////////////////////////////////////////////////////////
// Full slide on or offscreen
function openPanel($id) {
  zindex++;

  var $panel = $('#' + $id),
    panel = '#' + $id;
  var aniRightOut = { css: { right: '-100%', display: 'none' }, ease: Expo.easeIn },
    aniRightIn = { css: { right: '0', display: 'block', zIndex: (zindex) }, ease: Expo.easeOut },
    aniLeftOut = { css: { marginLeft: '-100%', display: 'none' }, ease: Expo.easeIn },
    aniLeftIn = { css: { marginLeft: '0', display: 'block', zIndex: (zindex) }, ease: Expo.easeOut };

  if ($panel.data('position') == 'right') {
    if ($panel.is(':visible')) {
      TweenLite.to(panel, 0.25, aniRightOut);
      $panel.removeClass('opened').addClass('closed');
      lastpath = window.location.pathname;
      if ($.isNumeric($id)) {
        lastpath = lastpath.substr(0, lastpath.lastIndexOf('/'));
        history.pushState('', document.title, lastpath);
      }
    } else {
      TweenLite.to('[role=PaneView][data-type=overlay][data-position=right]:not(' + panel + ')', 0.25, aniRightOut);

      TweenLite.to(panel, 0.25, aniRightIn);
      $panel.removeClass('closed').addClass('opened');
    }
  } else if ($panel.data('position') == 'left') {
    if ($panel.is(':visible')) {
      TweenLite.to(panel, 0.5, aniLeftOut);
      $panel.removeClass('opened').addClass('closed');

    } else {
      TweenLite.to('[role=PaneView][data-type=overlay][data-position=left]:not(' + panel + ')', 1, aniLeftOut);
      TweenLite.to(panel, 0.5, aniLeftIn);
      $panel.removeClass('closed').addClass('opened');

    }

  }
  if ($('.opened[role=PaneView]').length === 0
    && $('#search_bar:visible').length === 0 && $('[role=PageView] #Home').length > 0) {
    openSearch(true);
  }
  return true;
}

/////////////////////////////////////////////////////////
//
//  CLOSE PANE (PANEL)
//
/////////////////////////////////////////////////////////
// Full slide on or offscreen
function closePane($id) {

  var $panel = $('#' + $id),
    panel = '#' + $id;

  if ($panel.data('position') == 'right') {

    TweenLite.to(panel, 0.25, {
      css: { right: '-100%', display: 'none' }, ease: Expo.easeIn, onComplete: function () {
        $panel.remove();
      }
    });
    $panel.removeClass('opened').addClass('closed');
    lastpath = window.location.pathname;
    if ($.isNumeric($id)) {
      lastpath = lastpath.substr(0, lastpath.lastIndexOf('/'));
      history.pushState('', document.title, lastpath);
    }

  } else if ($panel.data('position') == 'left') {

    TweenLite.to(panel, 0.5, {
      css: { marginLeft: '-100%', display: 'none' }, ease: Expo.easeIn, onComplete: function () {
        $panel.remove();
      }
    });
    $panel.removeClass('opened').addClass('closed');

  }
  return true;
}


/////////////////////////////////////////////////////////
//
//  OPEN POPUPS
//
/////////////////////////////////////////////////////////
function openPopup(args) {
  var passdata = args.data || null,
    url = args.url || null,
    id = args.id || null,
    content = args.content || null,
    classes = args.classes || null,
    title = args.title || null,
    $PageView = $('[role=PageView], body');

  if (url === null) {
    args.url = id;
    url = args.url
  }

  if (id === null && url !== null) {
    args.id = url.replace(/\W/g, '');
    id = args.id
  }

  $popup = $PageView.find('#' + id);
  ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('#' + id, $popup);

  if ($popup.length > 0) {
    for (opt in passdata) {
      if (opt == 'links') {
        for (link in passdata[opt]) {
          $popup.find('.modal-data-link-' + link).attr('href', passdata[opt][link]);
        }
      } else $popup.find('.modal-data-' + opt).html(passdata[opt]);
    }
    $popup.modal('toggle');
    return;
  } else if (content !== null) {
    $.post('/__inc/includes/ajax.php', {
      'get_popup': { id: args.id, content: args.content, title: args.title }
    },
      function (data) {
        $PageView.append(data);

        openPopup({ id: args.id, content: args.content, title: args.title, passdata: args.passdata });

        openAlert({ remove: true });
      });
    return;
  }
  else if ($popup.length == 0 && content === null) {
    openAlert({});
    $.post('/__inc/includes/ajax.php', {
      'get_popup': args
    },
      function (data) {
        $PageView.append(data);
        // if(debug)console.log(data);
        openPopup({ id: id, data: passdata });

        openAlert({ remove: true });
      });
    return;
  }
  openAlert({ remove: true });
}


/////////////////////////////////////////////////////////
//
// 	OPEN SEARCH
//	ToDo: Integrate with openPopup()
//
/////////////////////////////////////////////////////////

function openSearch(open) {
  zindex++;

  var $PageView = $('[role=ViewController]'),
    $searchbar = $PageView.find('#search_bar'),
    forceOpen = open || false,
    openTime = false;

  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('partner_listings --------------------------------------------------------');

  /* if parner_listings panel is open - close it - otherwise panel won't close properly on new search*/
  if ($('#partner_listings').hasClass('opened') && $('[role=PaneView]#listings').length > 0) {
    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('523   partner     --------------------------------------------');
    openPanel('partner_listings');
  }
  if ($('#refinements').hasClass('opened')) {
    openPanel('refinements');
  }

  selectText = function ($popup) {
    $searchbar.find('input[type=search]').focus().select();
  },
    aniOpen = function () {
      openTime = true;
      $searchbar.css({ display: 'block', transform: 'scale(0.8, 0.8)', visibility: 'visible', margin: '0 auto', 'max-width': '100vw' });
      TweenLite.to($searchbar, 0.25, {
        css: { top: 0, autoAlpha: 1, zIndex: zindex, scale: 1 },
        ease: Expo.easeOut, onComplete: function () {
          setTimeout(function () {
            openTime = false;
          }, 500);
          $PageView.on('click', function (e) {
            closeWhenClickedOff(e);
          });
        }
      });
    },
    aniClose = function () {
      TweenLite.to($searchbar, 0.25, {
        css: { top: 1000, autoAlpha: 0, scale: 0.8 },
        ease: Expo.easeIn,
        onComplete: function () {
          $searchbar.removeClass('open').css('display', 'none');
          openTime = true;
        }
      });
    },
    closeWhenClickedOff = function (e) {
      var visiSearchBar = $('#search_bar:visible');
      if (visiSearchBar.length > 0) {
        if (!$searchbar.is(e.target)
          && visiSearchBar.has(e.target).length === 0
          /*&& ($('.opened[role=PaneView]').length > 0 || ($('#Home[role=PageView]').length === 0))*/
          && !openTime) {
          aniClose();
        }
      }
    }
  ////////////////////////////
  if ($searchbar.length > 0) {
    if ($searchbar.is(':visible')) {
      if (($('.opened[role=PaneView]').length > 0 && !forceOpen) || ($('[role=PageView]').not('#Home').length > 0)) {
        aniClose();
      } else {
        aniClose();
      }
    }
    // If popup exists but is hidden
    else if ($searchbar.is(':hidden') || forceOpen) {
      if ($('[role=PageView]').not('#Home').length > 0 && !forceOpen) {
        aniClose();
      } else {
        aniOpen();
        selectText($searchbar);
      }
    }
  }
  /////////////////////////////
}

/////////////////////////////////////////////////////////
//
// 	GET PANEL
//	ToDo: Integrate with openPanel()
//
/////////////////////////////////////////////////////////
function get_panel(args) {
  zindex++;

  if (url == 'full_listing' && isMobile()) {
    zindex = zindex + 2;
  }

  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('523   partner     --------------------------------------------');

  var position = args.position || 'right',
    type = args.type || 'static',
    id = args.id || null,
    url = args.url || null,
    partner = args.partner || null,
    state = args.state || null,
    passdata = args.data || null,
    style = args.style || null,

    $PageView = $('[role=PageView]'),
    $ViewController = $('[role=ViewController]'),
    $panel = $('#' + id + ',#account_' + id),
    panel = '#' + id,
    aniRightOut = { css: { right: '-100%', display: 'none' }, ease: Expo.easeIn },
    aniRightIn = { css: { right: '0', display: 'block' }, ease: Expo.easeOut },
    aniLeftIn = { css: { marginLeft: '0', display: 'block' }, ease: Expo.easeOut };


  ///////////////////////////////////
  //	Update URL path
  ///////////////////////////////////
  if (url && position === 'right') {
    history.pushState('', document.title, url);
  }

  // This Panel Exists
  if ($panel.length > 0) {

    // This Panel is on the right
    if ($panel.data('position') == 'right') {
      // Other Panel is Visible
      if ($('[role=PaneView][data-type=overlay][data-position=right]:not(' + panel + ')').is(':visible')
        && ($panel.attr('id') !== 'gmap')) {
        // Remove Other Panel
        TweenLite.to('[role=PaneView][data-type=overlay][data-position=right]:not(' + panel + ')', 0.25, aniRightOut);
      }
      TweenLite.to($panel, 0.25, aniRightIn);
    }
    // This Panel is on the left
    else if ($panel.data('position') == 'left') {
      $panel.css({
        'margin-left': -$panel.width()
        , opacity: 1
      })

      TweenLite.to($panel, 0.25, aniLeftIn);
    }
    $panel.addClass('opened').removeClass('closed');
    $panel.css('z-index', (zindex));

    if (url == 'full_listing') {
      if ($('.history').length > 0) {
        var directory = $('#listing-' + $panel.attr('id') + ' input[name=directory]').val();
        history.pushState({}, directory, directory);
      }
    }
    if (url == 'partner') {
      //2023-07-18 : if (user_ip == '108.180.234.14') console.log('523   partner     --------------------------------------------');
      var alias = $('#partner_name').val();
      var address = window.location.href;
      var base = address.split('?')[0];
      history.pushState({}, document.title, base + '?partner=' + alias);
    }

  } else {

    openAlert({ message: 'loading', icon: 'spinner' });
    $.ajax({
      url: '/__inc/includes/ajax.php',
      method: 'POST',
      data: {
        get_panel: args
      }
    }).done(
      function (data) {
        $ViewController.append(data);

        $panel = $ViewController.find('[role=PaneView][data-position=' + args.position + ']:first');
        panel = '#' + $panel.attr('id');
        $panel.css('z-index', (zindex));
        //////////////////////////////
        if (args.position == 'right') {
          // Other Panel is Visible
          if ($('[role=PaneView][data-type=overlay][data-position=right]:not(' + panel + ')').is(':visible')
            && ($panel.attr('id') !== 'gmap')) {
            // Remove Other Panel
            TweenLite.to('[role=PaneView][data-type=overlay][data-position=right]:not(' + panel + ')', 0.25, aniRightOut);
          }
          TweenLite.to($panel, 0.25, aniRightIn);

          if ($('#listings').length == 0 && $('[name=listing_lat]').length > 0) {
            var position = {
              coords: {
                latitude: $('[name=listing_lat]').val(),
                longitude: $('[name=listing_long]').val()
              }
            },
              listing_id = $('[name=listing_id]').val();
            zindex -= 3;
            geocoder = new google.maps.Geocoder();
            handle_geolocation_query(position);

          }
          if (url == 'full_listing') {
            updateFavStars(id);

            if ($('.history').length > 0) {
              var directory = $('#listing-' + $panel.attr('id') + ' input[name=directory]').val();
              history.pushState({}, directory, directory);
            }
          }
          if (url == 'partner') {
            //2023-07-18 : if (user_ip == '108.180.234.14') console.log('523   partner     --------------------------------------------');
            var alias = $('#partner_name').val();
            var address = window.location.href;
            var base = address.split('?')[0];
            history.pushState({}, document.title, base + '?partner=' + alias);
          }
        }

        // This Panel is on the left
        else if (args.position == 'left') {
          $panel.css({
            'margin-left': -$panel.width(),
            opacity: 1,
            'z-index': zindex
          })

          TweenLite.to($panel, 0.25, aniLeftIn);
        }
        $panel.addClass('opened').removeClass('closed');

        if (url == 'rmresults') {
          $panel.css('overflow', 'scroll');
        }

        openAlert({ remove: true });

      });
  }
  if ($('.opened[role=PaneView]').length === 0
    && $('#search_bar:visible').length === 0) {
    openSearch(true);
  } else if ($('#search_bar:visible').length > 0) {
    openSearch(false);
  }
}


/**
 * toggleLayout function.
 *
 * @access public
 * @param mixed container
 * @return void
 */
function toggleLayout(container) {
  $('#' + container).toggleClass('view-listing-grid');
  $('#navbarChangeLayout i').toggleClass('icon-map-view')
  return true;
}


function toggleLayoutMap(container) {
  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('toggleLayoutMap ------------------------------------------------');

  $('#' + container).toggleClass('listings-map-hide');
  $('#navbarChangeLayoutMap i').toggleClass('icon-map1')
  return true;
}

function toggleLayoutLeftRight(container) {
  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('toggleLayoutLeftRight --------------------------------------------');
  $('#' + container).toggleClass('listings-map-grid');
  $('#' + container).toggleClass('view-listing-grid');
  $('.container-map-listing').toggleClass('flex-nowrap').toggleClass('d-flex').css("flex-direction", "row-reverse");
  $('#navbarChangeLayout i').toggleClass('icon-map-view')

  if ($('.container-map-listing #gmap').attr('data-type') == 'push') {
    $('.container-map-listing #gmap').attr('data-position', 'right').attr('data-type', 'push')
  } else {
    $('.container-map-listing #gmap').attr('data-position', 'left').attr('data-type', 'static')
  }

  if ($('.container-map-listing #listings').attr('data-type') == 'push') {
    $('.container-map-listing #listings').attr('data-position', 'left').attr('data-type', 'static')
  } else {
    $('.container-map-listing #listings').attr('data-position', 'right').attr('data-type', 'push')
  }

  return true;
}

/////////////////////////////////////////////////////////
//
//  Alert Message
//
/////////////////////////////////////////////////////////
function openAlert(args) {

  var message = args.message || 'loading',
    icon = args.icon || 'spinner',
    dur = args.duration || false,
    remove = args.remove || false;
  $body = $('body');

  if (((message === 'loading') && ($body.find('#alert').length > 0)) || remove) {
    $body.find('#alert').remove();
  } else {
    $body.find('#alert').remove();
    $body.append('<div id="alert"><i class="icon-' + icon + '"></i> ' + message + '</div>');

    if (dur || (message !== 'loading' && dur)) {
      dur = dur || 4000;
      setTimeout(function () {
        $body.find('#alert').remove();
      }, dur);
    }
  }

  return true;
}

/////////////////////////////////////////////////////////
//
//  Notification Message
//
/////////////////////////////////////////////////////////
function openNotification(args) {
  var message = args.message || 'loading',
    dur = args.duration || 4000,
    dismiss = args.dismissable || false,
    remove = args.remove || false,
    $body = $('body'),
    aniOut = function () {
      $body.find('#notification').animate({ color: "rgba(255,255,255,0)", bottom: "-48px" }, 1000, function () {
        $body.find('#notification').remove();
      });
    },
    $dismissableNotification = $('<div id="notification"><i class="icon-times" onclick="openNotification({remove:true})"></i>' + message + '</div>'),
    addNotification = function () {
      if (dismiss) {
        $body.append($dismissableNotification);
      } else if (dur) {
        $body.append($dismissableNotification);
        setTimeout(function () {
          aniOut();
        }, dur);
      }
    };

  if (remove) {
    aniOut();
  } else {
    if (($body.find('#notification').length > 0)) {
      $body.find('#notification').animate({ color: "rgba(255,255,255,0)", bottom: -48 }, 400, function () {
        $body.find('#notification').remove();
        addNotification();
      });
    } else {
      addNotification();
    }
  }


  return true;
}

function executeFunctionByName(functionName, context, args) {
  var args = [].slice.call(arguments).splice(2);
  var namespaces = functionName.split(".");
  var func = namespaces.pop();
  for (var i = 0; i < namespaces.length; i++) {
    context = context[namespaces[i]];
  }
  return context[func].apply(this, args);
}

/////////////////////////////////////////////////////////
//
//  User Functions
//
/////////////////////////////////////////////////////////
var User = {
  login: function (data) {
    $('.login_button')
      .addClass('account_button')
      .attr({ href: 'account_menu' })
      .attr('data-rel', 'panel')
      .html('<i class="icon-user"></i> ' + data.firstname)
      .removeClass('login_button');
    $('aside#login').remove();
  },
  logout: function () {
    $('.account_button')
      .addClass('login_button')
      .attr({ href: 'login' })
      .attr('data-rel', 'popup')
      .html('<i class="icon-sign-in"></i> Login')
      .removeClass('account_button');
    $('aside[id*=account_]').remove();
  },
  loginas: function (data) {
    $('aside[id*=account_]').remove();
    $('.account_button').text(data.firstname);
    openNotification({ message: "You are currently logged in as " + data.firstname + " " + data.lastname, dismissable: true });
  },
  search: function (data) {
    show_users({ str: data.str, container: data.container, clear: true, orderby: 'status' });
    // $(data.container).parent('.content').animate({
    //   scrollTop: $(data.container).offset().top
    // }, 1000);
  },
  update: function (id) {
    $('#user_' + id).after('<div id="tempuser_' + id + '" style="min-height:10em"></div>');
    show_users({ container: '#tempuser_' + id, str: id });
    $('#user_' + id).fadeOut(1000, function () {
      $(this).remove();
    });
  }
}

var Listing = {
  update: function (id) {
    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('1397 show_listings --------------------------------------------------------');
    $('#listing_' + id).after('<div id="templisting_' + id + '" style="min-height:10em"></div>');
    show_listings({ container: '#templisting_' + id, str: id });
    $('#listing_' + id).fadeOut(1000, function () {
      $(this).remove();
    });
  },
  search: function (data) {
    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('1404 show_listings --------------------------------------------------------');
    show_listings({ str: data.str, container: data.container, table: data.table, clear: true });
    // $(data.container).parent('.content').animate({
    //   scrollTop: $(data.container).offset().top
    // }, 1000);
  },
  show: function (id) {
    get_panel({ id: id, url: 'full_listing', type: 'overlay', position: 'right' });
  }
}


/***************************************************************/
/**************** Functions for templated sites ****************/
/***************************************************************/

/* Use search button to fill and submit search_bar */
function search_start(lat_lng) {
  /* autofill search with lat/long from site variables */
  $('#search_bar input[type=search]').val(lat_lng);
  $('#search_bar').submit();
  $('#search_bar input[type=search]').val('');

  /* get filepath and update url using location info from db based on city id */
  $.get("/__inc/php/get_path.php", { city: city_id }, function (data) {
    var path = '/' + data.cont + '/' + data.country + '/' + data.state + '/' + data.city + '/';
    history.pushState('', document.title, path);
  }, "json");

}


function get_user_loc(callback) {

  $.ajax({
    method: "POST",
    url: "/__inc/includes/get_user_loc.php",
    data: { ip: user_ip }
  }).done(function (data) {
    var obj = jQuery.parseJSON(data);
    //console.log(obj.units);
    callback(obj.units);
  });

}

$('.rmsearch label').click(function () {
  var partner = $(this).attr("for");
  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('523   partner     --------------------------------------------');

  if ($('.rmsearch #' + partner).is(":checked")) {
    $('.rmsearch #' + partner).attr('name', '');
  } else {
    var rf = false;
    if ($('.rmsearch #' + partner).attr('name') == 'not_listed') {
      rf = true;
    }

    $('.rmsearch #' + partner).attr('name', 'list_partner[]');
    $('.rmsearch #' + partner).attr('checked', true);

    if (rf == true) {
      return false;
    }
  }
});


/**
 * addToFavorites function.
 *
 * @access public
 * @param mixed listing
 * @return void
 */
function addToFavorites(listing, type) {
  ////2023-07-18 : if (user_ip == '108.180.234.14') console.log(listing, type);
  if (listing == '' || listing == null) return false;
  if (type == '' || type == null) type = 'listing';

  if (type == 'listing') {
    str = localStorage.getItem('favorites');
    if ((str != '' && str != null) && str.indexOf(',') > 1) {
      str = str.split(',');
      var filtered = str.filter(function (el) {
        return el != null;
      });
      filtered.push(listing);
      str = filtered.toString();
    } else if ((str != '' && str != null) && str.length > 2) {
      str = str + ',' + listing;
    } else {
      str = listing;
    }

    favoriteList = str;


    localStorage.setItem('favorites', favoriteList);
    updateFavorites(favoriteList, 'listing');

  } else if (type == 'roommate') {
    str = localStorage.getItem('roommate-favorites');

    if ((str != '' && str != null) && str.indexOf(',') > 1) {
      str = str.split(',');
      var filtered = str.filter(function (el) {
        return el != null;
      });
      filtered.push(listing);
      str = filtered.toString();
    } else if ((str != '' && str != null) && str.length > 2) {
      str = str + ',' + listing;
    } else {
      str = listing;
    }

    roommateFavoriteList = str;

    localStorage.setItem('roommate-favorites', roommateFavoriteList);
    updateFavorites(roommateFavoriteList, 'roommate');
  }

  updateFavStars(listing);

  openPanel('favorites');

  return true;
}


/**
 * updateFavorites function.
 *
 * @access public
 * @param mixed str
 * @return void
 */
function updateFavorites(str, type) {
  ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('updateFavorites', str, type);
  if (type == '' || type == null) type = 'listing';
  str = str.toString();
  if (type == 'listing') {
    if (str != '' && str != null) {
      if (str.indexOf(',') > 1) {
        str = str.split(',');
        var filtered = str.filter(function (el) {
          return el != null;
        });
        str = filtered.toString();
      }
      //localStorage.setItem('favorites', str);

      data = { ids: str };
      if (str != '') {
        $.ajax({
          url: '/__inc/includes/get_listings.php',
          data: data,
          type: 'POST'
        }).done(function (data, stri, xhr) {

          $('body').find('#favorites-load').html(data);
          $listitems = $('body').find('#favorites-load [data-role=listing-brief]');

          var l = $listitems.length;

          for (var i = 0; i < l; i++) {
            $this = $listitems.eq(i);
            id = $this.attr('id');
            id = id.replace('listing_', '');
            $this.append('<button data-listing="' + id + '" data-toggle="tooltip" title="Remove From Favorites" class="btn btn-danger remove-from-favorites"><i class="icon-minus removeFav"></i></button>');
            updateFavStars(id)
            $this.css('padding-right', '2.7em');
          }

        });
      }
    }
  } else if (type == 'roommate') {
    if (str != '' && str != null) {
      if (str.indexOf(',') > 1) {
        str = str.split(',');
        var filtered = str.filter(function (el) {
          return el != null;
        });
        str = filtered.toString();
      }

      //localStorage.getItem('roommate-favorites', str);

      data = { ids: str };
      if (str != '') {
        $.ajax({
          url: '/__inc/includes/get_roommates.php',
          data: data,
          type: 'POST'
        }).done(function (data, stri, xhr) {

          $('body').find('#roommate-favorites-load').html(data);
          $listitems = $('body').find('#roommate-favorites-load [data-role=roommate-brief]');

          var l = $listitems.length;

          for (var i = 0; i < l; i++) {
            $this = $listitems.eq(i);
            id = $this.attr('id');
            id = id.replace('roommate_', '');
            $this.append('<button data-roommate="' + id + '" data-toggle="tooltip" title="Remove From Favorites" class="btn btn-danger remove-from-favorites"><i class="icon-minus removeFav"></i></button>');
            updateFavStars(id)
            $this.css('padding-right', '2.7em');
          }

        });
      }
    }
  }

  /*if(str == '' && rm_str == '') {
    $('#favorites-load').html('<div class="align-center p-4"><h4>You don\'t have any favorites yet.</h4><p>Click the heart icon on a listing to add it to your favorites.</p></div>');
  }*/

}


/**
 * updateFavStars function.
 *
 * @access public
 * @param mixed id
 * @return void
 */
function updateFavStars(id) {
  // If in array, change star

  if (roommateFavoriteList != '' && roommateFavoriteList != null) {
    roommateFavoriteList = roommateFavoriteList.toString();

    if (roommateFavoriteList.indexOf(id) !== -1) {

      // START HERE - it gets to here but these aren't updating (id is passed)

      $('#roommate_' + id + ' .add-to-favorites')
        .attr('onclick', '')
        .attr('title', 'Remove From Favorites')
        .attr('data-original-title', 'Remove From Favorites')
        .addClass('remove-from-favorites')
        .removeClass('add-to-favorites');

      $('#roommate_' + id + ' i.icon-heart-o')
        .addClass('icon-heart')
        .removeClass('icon-heart-o');
    } else {
      $('#roommate_' + id + ' .remove-from-favorites')
        .attr('title', 'Add to Favorites')
        .attr('data-original-title', 'Add to Favorites')
        .addClass('add-to-favorites')
        .removeClass('remove-from-favorites');

      $('#roommate_' + id + ' i.icon-heart')
        .addClass('icon-heart-o')
        .removeClass('icon-heart');
    }
  } else {
    $('#roommate_' + id + ' .remove-from-favorites')
      .attr('title', 'Add to Favorites')
      .attr('data-original-title', 'Add to Favorites')
      .addClass('add-to-favorites')
      .removeClass('remove-from-favorites');

    $('#roommate_' + id + ' i.icon-heart')
      .addClass('icon-heart-o')
      .removeClass('icon-heart');
  }

  if (favoriteList != '' && favoriteList != null) {
    favoriteList = favoriteList.toString();
    if (favoriteList.indexOf(id) !== -1) {

      // START HERE - it gets to here but these aren't updating (id is passed)

      $('#listing_' + id + ' .add-to-favorites')
        .attr('onclick', '')
        .attr('title', 'Remove From Favorites')
        .attr('data-original-title', 'Remove From Favorites')
        .addClass('remove-from-favorites')
        .removeClass('add-to-favorites');

      $('#listing_' + id + ' i.icon-heart-o')
        .addClass('icon-heart')
        .removeClass('icon-heart-o');
    } else {
      $('#listing_' + id + ' .remove-from-favorites')
        .attr('title', 'Add to Favorites')
        .attr('data-original-title', 'Add to Favorites')
        .addClass('add-to-favorites')
        .removeClass('remove-from-favorites');

      $('#listing_' + id + ' i.icon-heart')
        .addClass('icon-heart-o')
        .removeClass('icon-heart');
    }
  } else {
    $('#listing_' + id + ' .remove-from-favorites')
      .attr('title', 'Add to Favorites')
      .attr('data-original-title', 'Add to Favorites')
      .addClass('add-to-favorites')
      .removeClass('remove-from-favorites');

    $('#listing_' + id + ' i.icon-heart')
      .addClass('icon-heart-o')
      .removeClass('icon-heart');
  }
}

/////////////////////////////
//
//	Remove from Favorites
//
/////////////////////////////
function removeFromFavorites(listing, type) {
  ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('removeFromFavorites', listing, type);
  listing = listing.toString();
  var newlist = null;
  if (type == 'listing') {
    str = localStorage.getItem('favorites');

    if (str != '' && str.indexOf(',') > 1) {
      str = str.split(',');
      str = str.filter(function (el) {
        return el != null;
      });

      var index = str.indexOf(listing);
      if (index > -1) {
        str.splice(index, 1);
      }
      str = str.toString();
    } else if (str.length > 2) {
      var index = str.indexOf(listing);
      if (index > -1) {
        str = '';
      }
    }

    favoriteList = str;

    localStorage.setItem('favorites', favoriteList);

    $('#favorites-load #listing_' + listing).slideUp(250, function () {
      updateFavorites(favoriteList, 'listing');
      updateFavStars(listing);
    })
  } else if (type == 'roommate') {
    str = localStorage.getItem('roommate-favorites');
    //console.log('get', str);
    if (str != '' && str.indexOf(',') > 1) {
      str = str.split(',');
      str = str.filter(function (el) {
        return el != null;
      });

      var index = str.indexOf(listing);
      if (index > -1) {
        str.splice(index, 1);
      }
      str = str.toString();
      //console.log('set', str);
    } else if (str.length > 2) {
      var index = str.indexOf(listing);
      if (index > -1) {
        str = '';
      }
      //console.log('set', str);
    }

    roommateFavoriteList = str;

    localStorage.setItem('roommate-favorites', roommateFavoriteList);
    //console.log(roommateFavoriteList, localStorage.getItem('roommate-favorites'));

    $('#roommate-favorites-load #roommate_' + listing).slideUp(250, function () {
      updateFavorites(roommateFavoriteList, 'roommate');
      updateFavStars(listing);
    })
  }
}

///////////////////////////////////////////
//
//	Make record of click on phone btn
//
////////////////////////////////////////////
function phone_click(id, site, ip, phone) {
  $.ajax({
    method: "POST",
    url: "/shared/php/phone_clicks.php",
    data: { lid: id, domain: site, ip_address: ip }
  });
}


$(document).ready(function (e) {

  // // // // // // // // // // // // // // // // // // // // // // // // // // // //
  //
  //		Watch Alt Contact Buttons
  //
  // // // // // // // // // // // // // // // // // // // // // // // // // // // //

  $('#CreateNewContact').on("change", '#alt_contact', function () {
    cont = $(this).prop("selectedIndex");
    changeAltContact(cont);
  });

});//End Document Ready

function onKeyDown() {
  if ($("#Save").is(":hidden")) {
    $("#Update").show();
    $('#CreateNewContact #contaction').val('Update');
  } else {
    $('#CreateNewContact #contaction').val('Save');
  }
}

// // // // // // // // // // // // // // // // // // // // // // // // // // // //
//          :
// Function : newContact()
// Purpose  : Start a new contact in the Alt contact window
// Input    :
// Output   :
// Assuming :
//          :
// Created  : Oct 1, 2012
// Author   : Peter Vigilante
//          :
// // // // // // // // // // // // // // // // // // // // // // // // // // // //
function newContact() {
  $('#contact_info input').val("");
  $('#cont_firstname').val("");
  $('#cont_lastname').val("");
  $('#cont_phone').val("");
  $('#cont_fax').val("");
  $('#cont_email').val("");
  $('#alt_contact option:selected').attr('selected', '');
  $('#Save').show();
  $('#CreateNewContact #contaction').val('Save');
  $('#New_Contact').hide();
  $('#Update').hide();
  $('#Delete').hide();
  enable_inputs(true);

}

// // // // // // // // // // // // // // // // // // // // // // // // // // // //
//          :
// Function : deleteContact()
// Purpose  : Delete an alt contact
// Input    :
// Output   :
// Assuming :
//          :
// Created  : Oct 1, 2012
// Author   : Peter Vigilante
//          :
// // // // // // // // // // // // // // // // // // // // // // // // // // // //
function deleteContact() {
  $('#CreateNewContact #contaction').val('Delete');
  enable_inputs(true);
}

// // // // // // // // // // // // // // // // // // // // // // // // // // // //
//          :
// Function : startAltContactForm()
// Purpose  : Begin the process of preparing a new contact
// Input    :
// Output   :
// Assuming :
//          :
// Created  : Oct 1, 2012
// Author   : Peter Vigilante
//          :
// // // // // // // // // // // // // // // // // // // // // // // // // // // //
function startAltContactForm(cont) {
  if (cont == null) {
    cont = -1;
  }
  $('#Save').hide();
  $('#Update').hide();
  $('#Delete').hide();
  changeAltContact(cont);
  var checkselection = $('#alt_contact').val().split('|WEM3|');

  if (checkselection[0] == -1) {
    // disable inputs when on default contact
    enable_inputs(false);
  } else {
    enable_inputs(true);
  }
}

// // // // // // // // // // // // // // // // // // // // // // // // // // // //
//          :
// Function : changeAltContact()
// Purpose  :
// Input    :
// Output   :
// Assuming :
//          :
// Created  : Oct 1, 2012
// Author   : Peter Vigilante
//          :
// // // // // // // // // // // // // // // // // // // // // // // // // // // //
function changeAltContact(cont) {
  $('#New_Contact').show();
  //alert("lol");
  if (cont == null) {
    cont = -1;
  }

  $("#alt_contact option").each(function () {
    var checkselection = $(this).val().split('|WEM3|');
    if (checkselection[0] == cont) {
      $(this).attr('selected', 'selected');
    }
  });

  var alt_con = $("#alt_contact option:selected").val();
  if (alt_con != undefined) {
    $('#Delete').show();
    if (alt_con == -1) {
      $('#Update').hide();
    } else {
      $('#Update').show();
    }
    $('#Save').hide();
    var alt_con_arr = alt_con.split('|WEM3|');

    $("#alt_cont_id").val(alt_con_arr[0]);
    $("#cont_id").val(alt_con_arr[0]);
    $("#cont_firstname").val(alt_con_arr[1]);
    $("#cont_lastname").val(alt_con_arr[2]);
    $("#cont_phone").val(alt_con_arr[3]);
    $("#cont_fax").val(alt_con_arr[4]);
    $("#cont_email").val(alt_con_arr[5]);


    var checkselection = $('#alt_contact').val().split('|WEM3|');

    if (checkselection[0] == -1) {
      // disable inputs when on default contact
      enable_inputs(false);
    } else {
      enable_inputs(true);
    }
  }
  //console.log('changeAltContact');
}


// // // // // // // // // // // // // // // // // // // // // // // // // // // //
//          :
// Function : enable_inputs(enable)
// Purpose  : disable or enable input fields on the alt_contact form
// Input    : true or false
// Output   :
// Assuming :
//          :
// Created  : Mar 28, 2013
// Author   : Ernie Moreau
//          :
// // // // // // // // // // // // // // // // // // // // // // // // // // // //
function enable_inputs(enable) {
  if (enable == true) {
    $("#cont_firstname").removeAttr('disabled');
    $("#cont_lastname").removeAttr('disabled');
    $("#cont_phone").removeAttr('disabled');
    $("#cont_fax").removeAttr('disabled');
    $("#cont_email").removeAttr('disabled');
  } else {
    $("#cont_firstname").attr('disabled', 'disabled');
    $("#cont_lastname").attr('disabled', 'disabled');
    $("#cont_phone").attr('disabled', 'disabled');
    $("#cont_fax").attr('disabled', 'disabled');
    $("#cont_email").attr('disabled', 'disabled');
    $('#Delete').hide();
    $('#Update').hide();
  }
  //console.log('enable_inputs');
}


// // // // // // // // // // // // // // // // // // // // // // // // // // // //
//          :
// Function : sendForm()
// Purpose  : Send a form live using ajax
// Input    :
// Output   :
// Assuming :
//          :
// Created  : Oct 1, 2012
// Author   : Peter Vigilante
//          :
// // // // // // // // // // // // // // // // // // // // // // // // // // // //
function sendForm(action) {
  $("#CreateNewContact").on('submit', function () {
    //check the form is not currently submitting
    if ($(this).data('formstatus') !== 'submitting') {
      //setup variables
      var form = $(this),
        formData = form.serialize(),
        formUrl = form.attr('action'),
        formMethod = form.attr('method'),
        responseMsg = $('#message'),
        userBar = $('#CreateNewContact');

      //add status data to form
      form.data('formstatus', 'submitting');

      //show response message - waiting
      responseMsg.hide().addClass('alert alert-info').text('Please Wait...').fadeIn(100);

      $.ajax(
        {
          type: formMethod,
          url: formUrl,
          data: formData,
          success: function (data) {
            //alert(data);
            //setup variables
            var responseData = jQuery.parseJSON(data), klass = '';
            //response conditional
            switch (responseData.status) {
              case 'error':
                klass = 'alert alert-danger';
                break;
              case 'success':
                klass = 'alert alert-success';
                setTimeout(function () {
                  responseMsg.fadeOut(200, function () {
                    $(this).removeClass(klass);
                    form.data('formstatus', 'idle');
                    $('#tab_contact').load("/__admin/User/Alt-Contact/alt_contact6.inc.php", function () {
                      changeAltContact(responseData.cont);
                    }).hide().fadeIn(1000);
                  });
                }, 2000);
                break;
            }

            //show reponse message
            responseMsg.fadeOut(200, function () {
              $(this).removeClass()
                .addClass(klass)
                .text(responseData.message)
                .fadeIn(200, function () {
                  //set timeout to hide response message
                  setTimeout(function () {
                    responseMsg.fadeOut(200, function () {
                      $(this).removeClass(klass);
                      form.data('formstatus', 'idle');
                    });
                  }, 3000)
                });
            });
          }
        });
    }
    return false;
  });
}

/*!
 * Bootstrap-select v1.13.14 (https://developer.snapappointments.com/bootstrap-select)
 *
 * Copyright 2012-2020 SnapAppointments, LLC
 * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
 */

!function (e, t) { void 0 === e && void 0 !== window && (e = window), "function" == typeof define && define.amd ? define(["jquery"], function (e) { return t(e) }) : "object" == typeof module && module.exports ? module.exports = t(require("jquery")) : t(e.jQuery) }(this, function (e) { !function (z) { "use strict"; var d = ["sanitize", "whiteList", "sanitizeFn"], r = ["background", "cite", "href", "itemtype", "longdesc", "poster", "src", "xlink:href"], e = { "*": ["class", "dir", "id", "lang", "role", "tabindex", "style", /^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: [] }, l = /^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi, a = /^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 v(e, t) { var i = e.nodeName.toLowerCase(); if (-1 !== z.inArray(i, t)) return -1 === z.inArray(i, r) || Boolean(e.nodeValue.match(l) || e.nodeValue.match(a)); for (var s = z(t).filter(function (e, t) { return t instanceof RegExp }), n = 0, o = s.length; n < o; n++)if (i.match(s[n])) return !0; return !1 } function P(e, t, i) { if (i && "function" == typeof i) return i(e); for (var s = Object.keys(t), n = 0, o = e.length; n < o; n++)for (var r = e[n].querySelectorAll("*"), l = 0, a = r.length; l < a; l++) { var c = r[l], d = c.nodeName.toLowerCase(); if (-1 !== s.indexOf(d)) for (var h = [].slice.call(c.attributes), p = [].concat(t["*"] || [], t[d] || []), u = 0, f = h.length; u < f; u++) { var m = h[u]; v(m, p) || c.removeAttribute(m.nodeName) } else c.parentNode.removeChild(c) } } "classList" in document.createElement("_") || function (e) { if ("Element" in e) { var t = "classList", i = "prototype", s = e.Element[i], n = Object, o = function () { var i = z(this); return { add: function (e) { return e = Array.prototype.slice.call(arguments).join(" "), i.addClass(e) }, remove: function (e) { return e = Array.prototype.slice.call(arguments).join(" "), i.removeClass(e) }, toggle: function (e, t) { return i.toggleClass(e, t) }, contains: function (e) { return i.hasClass(e) } } }; if (n.defineProperty) { var r = { get: o, enumerable: !0, configurable: !0 }; try { n.defineProperty(s, t, r) } catch (e) { void 0 !== e.number && -2146823252 !== e.number || (r.enumerable = !1, n.defineProperty(s, t, r)) } } else n[i].__defineGetter__ && s.__defineGetter__(t, o) } }(window); var t, c, i = document.createElement("_"); if (i.classList.add("c1", "c2"), !i.classList.contains("c2")) { var s = DOMTokenList.prototype.add, n = DOMTokenList.prototype.remove; DOMTokenList.prototype.add = function () { Array.prototype.forEach.call(arguments, s.bind(this)) }, DOMTokenList.prototype.remove = function () { Array.prototype.forEach.call(arguments, n.bind(this)) } } if (i.classList.toggle("c3", !1), i.classList.contains("c3")) { var o = DOMTokenList.prototype.toggle; DOMTokenList.prototype.toggle = function (e, t) { return 1 in arguments && !this.contains(e) == !t ? t : o.call(this, e) } } function h(e) { if (null == this) throw new TypeError; var t = String(this); if (e && "[object RegExp]" == c.call(e)) throw new TypeError; var i = t.length, s = String(e), n = s.length, o = 1 < arguments.length ? arguments[1] : void 0, r = o ? Number(o) : 0; r != r && (r = 0); var l = Math.min(Math.max(r, 0), i); if (i < n + l) return !1; for (var a = -1; ++a < n;)if (t.charCodeAt(l + a) != s.charCodeAt(a)) return !1; return !0 } function O(e, t) { var i, s = e.selectedOptions, n = []; if (t) { for (var o = 0, r = s.length; o < r; o++)(i = s[o]).disabled || "OPTGROUP" === i.parentNode.tagName && i.parentNode.disabled || n.push(i); return n } return s } function T(e, t) { for (var i, s = [], n = t || e.selectedOptions, o = 0, r = n.length; o < r; o++)(i = n[o]).disabled || "OPTGROUP" === i.parentNode.tagName && i.parentNode.disabled || s.push(i.value); return e.multiple ? s : s.length ? s[0] : null } i = null, String.prototype.startsWith || (t = function () { try { var e = {}, t = Object.defineProperty, i = t(e, e, e) && t } catch (e) { } return i }(), c = {}.toString, t ? t(String.prototype, "startsWith", { value: h, configurable: !0, writable: !0 }) : String.prototype.startsWith = h), Object.keys || (Object.keys = function (e, t, i) { for (t in i = [], e) i.hasOwnProperty.call(e, t) && i.push(t); return i }), HTMLSelectElement && !HTMLSelectElement.prototype.hasOwnProperty("selectedOptions") && Object.defineProperty(HTMLSelectElement.prototype, "selectedOptions", { get: function () { return this.querySelectorAll(":checked") } }); var p = { useDefault: !1, _set: z.valHooks.select.set }; z.valHooks.select.set = function (e, t) { return t && !p.useDefault && z(e).data("selected", !0), p._set.apply(this, arguments) }; var A = null, u = function () { try { return new Event("change"), !0 } catch (e) { return !1 } }(); function k(e, t, i, s) { for (var n = ["display", "subtext", "tokens"], o = !1, r = 0; r < n.length; r++) { var l = n[r], a = e[l]; if (a && (a = a.toString(), "display" === l && (a = a.replace(/<[^>]+>/g, "")), s && (a = w(a)), a = a.toUpperCase(), o = "contains" === i ? 0 <= a.indexOf(t) : a.startsWith(t))) break } return o } function L(e) { return parseInt(e, 10) || 0 } z.fn.triggerNative = function (e) { var t, i = this[0]; i.dispatchEvent ? (u ? t = new Event(e, { bubbles: !0 }) : (t = document.createEvent("Event")).initEvent(e, !0, !1), i.dispatchEvent(t)) : i.fireEvent ? ((t = document.createEventObject()).eventType = e, i.fireEvent("on" + e, t)) : this.trigger(e) }; var f = { "\xc0": "A", "\xc1": "A", "\xc2": "A", "\xc3": "A", "\xc4": "A", "\xc5": "A", "\xe0": "a", "\xe1": "a", "\xe2": "a", "\xe3": "a", "\xe4": "a", "\xe5": "a", "\xc7": "C", "\xe7": "c", "\xd0": "D", "\xf0": "d", "\xc8": "E", "\xc9": "E", "\xca": "E", "\xcb": "E", "\xe8": "e", "\xe9": "e", "\xea": "e", "\xeb": "e", "\xcc": "I", "\xcd": "I", "\xce": "I", "\xcf": "I", "\xec": "i", "\xed": "i", "\xee": "i", "\xef": "i", "\xd1": "N", "\xf1": "n", "\xd2": "O", "\xd3": "O", "\xd4": "O", "\xd5": "O", "\xd6": "O", "\xd8": "O", "\xf2": "o", "\xf3": "o", "\xf4": "o", "\xf5": "o", "\xf6": "o", "\xf8": "o", "\xd9": "U", "\xda": "U", "\xdb": "U", "\xdc": "U", "\xf9": "u", "\xfa": "u", "\xfb": "u", "\xfc": "u", "\xdd": "Y", "\xfd": "y", "\xff": "y", "\xc6": "Ae", "\xe6": "ae", "\xde": "Th", "\xfe": "th", "\xdf": "ss", "\u0100": "A", "\u0102": "A", "\u0104": "A", "\u0101": "a", "\u0103": "a", "\u0105": "a", "\u0106": "C", "\u0108": "C", "\u010a": "C", "\u010c": "C", "\u0107": "c", "\u0109": "c", "\u010b": "c", "\u010d": "c", "\u010e": "D", "\u0110": "D", "\u010f": "d", "\u0111": "d", "\u0112": "E", "\u0114": "E", "\u0116": "E", "\u0118": "E", "\u011a": "E", "\u0113": "e", "\u0115": "e", "\u0117": "e", "\u0119": "e", "\u011b": "e", "\u011c": "G", "\u011e": "G", "\u0120": "G", "\u0122": "G", "\u011d": "g", "\u011f": "g", "\u0121": "g", "\u0123": "g", "\u0124": "H", "\u0126": "H", "\u0125": "h", "\u0127": "h", "\u0128": "I", "\u012a": "I", "\u012c": "I", "\u012e": "I", "\u0130": "I", "\u0129": "i", "\u012b": "i", "\u012d": "i", "\u012f": "i", "\u0131": "i", "\u0134": "J", "\u0135": "j", "\u0136": "K", "\u0137": "k", "\u0138": "k", "\u0139": "L", "\u013b": "L", "\u013d": "L", "\u013f": "L", "\u0141": "L", "\u013a": "l", "\u013c": "l", "\u013e": "l", "\u0140": "l", "\u0142": "l", "\u0143": "N", "\u0145": "N", "\u0147": "N", "\u014a": "N", "\u0144": "n", "\u0146": "n", "\u0148": "n", "\u014b": "n", "\u014c": "O", "\u014e": "O", "\u0150": "O", "\u014d": "o", "\u014f": "o", "\u0151": "o", "\u0154": "R", "\u0156": "R", "\u0158": "R", "\u0155": "r", "\u0157": "r", "\u0159": "r", "\u015a": "S", "\u015c": "S", "\u015e": "S", "\u0160": "S", "\u015b": "s", "\u015d": "s", "\u015f": "s", "\u0161": "s", "\u0162": "T", "\u0164": "T", "\u0166": "T", "\u0163": "t", "\u0165": "t", "\u0167": "t", "\u0168": "U", "\u016a": "U", "\u016c": "U", "\u016e": "U", "\u0170": "U", "\u0172": "U", "\u0169": "u", "\u016b": "u", "\u016d": "u", "\u016f": "u", "\u0171": "u", "\u0173": "u", "\u0174": "W", "\u0175": "w", "\u0176": "Y", "\u0177": "y", "\u0178": "Y", "\u0179": "Z", "\u017b": "Z", "\u017d": "Z", "\u017a": "z", "\u017c": "z", "\u017e": "z", "\u0132": "IJ", "\u0133": "ij", "\u0152": "Oe", "\u0153": "oe", "\u0149": "'n", "\u017f": "s" }, m = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g, g = RegExp("[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\u1ab0-\\u1aff\\u1dc0-\\u1dff]", "g"); function b(e) { return f[e] } function w(e) { return (e = e.toString()) && e.replace(m, b).replace(g, "") } var I, x, y, $, S = (I = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" }, x = "(?:" + Object.keys(I).join("|") + ")", y = RegExp(x), $ = RegExp(x, "g"), function (e) { return e = null == e ? "" : "" + e, y.test(e) ? e.replace($, E) : e }); function E(e) { return I[e] } var C = { 32: " ", 48: "0", 49: "1", 50: "2", 51: "3", 52: "4", 53: "5", 54: "6", 55: "7", 56: "8", 57: "9", 59: ";", 65: "A", 66: "B", 67: "C", 68: "D", 69: "E", 70: "F", 71: "G", 72: "H", 73: "I", 74: "J", 75: "K", 76: "L", 77: "M", 78: "N", 79: "O", 80: "P", 81: "Q", 82: "R", 83: "S", 84: "T", 85: "U", 86: "V", 87: "W", 88: "X", 89: "Y", 90: "Z", 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 104: "8", 105: "9" }, N = 27, D = 13, H = 32, W = 9, B = 38, M = 40, R = { success: !1, major: "3" }; try { R.full = (z.fn.dropdown.Constructor.VERSION || "").split(" ")[0].split("."), R.major = R.full[0], R.success = !0 } catch (e) { } var U = 0, j = ".bs.select", V = { DISABLED: "disabled", DIVIDER: "divider", SHOW: "open", DROPUP: "dropup", MENU: "dropdown-menu", MENURIGHT: "dropdown-menu-right", MENULEFT: "dropdown-menu-left", BUTTONCLASS: "btn-default", POPOVERHEADER: "popover-title", ICONBASE: "glyphicon", TICKICON: "glyphicon-ok" }, F = { MENU: "." + V.MENU }, _ = { span: document.createElement("span"), i: document.createElement("i"), subtext: document.createElement("small"), a: document.createElement("a"), li: document.createElement("li"), whitespace: document.createTextNode("\xa0"), fragment: document.createDocumentFragment() }; _.a.setAttribute("role", "option"), "4" === R.major && (_.a.className = "dropdown-item"), _.subtext.className = "text-muted", _.text = _.span.cloneNode(!1), _.text.className = "text", _.checkMark = _.span.cloneNode(!1); var G = new RegExp(B + "|" + M), q = new RegExp("^" + W + "$|" + N), K = { li: function (e, t, i) { var s = _.li.cloneNode(!1); return e && (1 === e.nodeType || 11 === e.nodeType ? s.appendChild(e) : s.innerHTML = e), void 0 !== t && "" !== t && (s.className = t), null != i && s.classList.add("optgroup-" + i), s }, a: function (e, t, i) { var s = _.a.cloneNode(!0); return e && (11 === e.nodeType ? s.appendChild(e) : s.insertAdjacentHTML("beforeend", e)), void 0 !== t && "" !== t && s.classList.add.apply(s.classList, t.split(" ")), i && s.setAttribute("style", i), s }, text: function (e, t) { var i, s, n = _.text.cloneNode(!1); if (e.content) n.innerHTML = e.content; else { if (n.textContent = e.text, e.icon) { var o = _.whitespace.cloneNode(!1); (s = (!0 === t ? _.i : _.span).cloneNode(!1)).className = this.options.iconBase + " " + e.icon, _.fragment.appendChild(s), _.fragment.appendChild(o) } e.subtext && ((i = _.subtext.cloneNode(!1)).textContent = e.subtext, n.appendChild(i)) } if (!0 === t) for (; 0 < n.childNodes.length;)_.fragment.appendChild(n.childNodes[0]); else _.fragment.appendChild(n); return _.fragment }, label: function (e) { var t, i, s = _.text.cloneNode(!1); if (s.innerHTML = e.display, e.icon) { var n = _.whitespace.cloneNode(!1); (i = _.span.cloneNode(!1)).className = this.options.iconBase + " " + e.icon, _.fragment.appendChild(i), _.fragment.appendChild(n) } return e.subtext && ((t = _.subtext.cloneNode(!1)).textContent = e.subtext, s.appendChild(t)), _.fragment.appendChild(s), _.fragment } }, Y = function (e, t) { var i = this; p.useDefault || (z.valHooks.select.set = p._set, p.useDefault = !0), this.$element = z(e), this.$newElement = null, this.$button = null, this.$menu = null, this.options = t, this.selectpicker = { main: {}, search: {}, current: {}, view: {}, isSearching: !1, keydown: { keyHistory: "", resetKeyHistory: { start: function () { return setTimeout(function () { i.selectpicker.keydown.keyHistory = "" }, 800) } } } }, this.sizeInfo = {}, null === this.options.title && (this.options.title = this.$element.attr("title")); var s = this.options.windowPadding; "number" == typeof s && (this.options.windowPadding = [s, s, s, s]), this.val = Y.prototype.val, this.render = Y.prototype.render, this.refresh = Y.prototype.refresh, this.setStyle = Y.prototype.setStyle, this.selectAll = Y.prototype.selectAll, this.deselectAll = Y.prototype.deselectAll, this.destroy = Y.prototype.destroy, this.remove = Y.prototype.remove, this.show = Y.prototype.show, this.hide = Y.prototype.hide, this.init() }; function Z(e) { var l, a = arguments, c = e; if ([].shift.apply(a), !R.success) { try { R.full = (z.fn.dropdown.Constructor.VERSION || "").split(" ")[0].split(".") } catch (e) { Y.BootstrapVersion ? R.full = Y.BootstrapVersion.split(" ")[0].split(".") : (R.full = [R.major, "0", "0"], console.warn("There was an issue retrieving Bootstrap's version. Ensure Bootstrap is being loaded before bootstrap-select and there is no namespace collision. If loading Bootstrap asynchronously, the version may need to be manually specified via $.fn.selectpicker.Constructor.BootstrapVersion.", e)) } R.major = R.full[0], R.success = !0 } if ("4" === R.major) { var t = []; Y.DEFAULTS.style === V.BUTTONCLASS && t.push({ name: "style", className: "BUTTONCLASS" }), Y.DEFAULTS.iconBase === V.ICONBASE && t.push({ name: "iconBase", className: "ICONBASE" }), Y.DEFAULTS.tickIcon === V.TICKICON && t.push({ name: "tickIcon", className: "TICKICON" }), V.DIVIDER = "dropdown-divider", V.SHOW = "show", V.BUTTONCLASS = "btn-light", V.POPOVERHEADER = "popover-header", V.ICONBASE = "", V.TICKICON = "bs-ok-default"; for (var i = 0; i < t.length; i++) { e = t[i]; Y.DEFAULTS[e.name] = V[e.className] } } var s = this.each(function () { var e = z(this); if (e.is("select")) { var t = e.data("selectpicker"), i = "object" == typeof c && c; if (t) { if (i) for (var s in i) i.hasOwnProperty(s) && (t.options[s] = i[s]) } else { var n = e.data(); for (var o in n) n.hasOwnProperty(o) && -1 !== z.inArray(o, d) && delete n[o]; var r = z.extend({}, Y.DEFAULTS, z.fn.selectpicker.defaults || {}, n, i); r.template = z.extend({}, Y.DEFAULTS.template, z.fn.selectpicker.defaults ? z.fn.selectpicker.defaults.template : {}, n.template, i.template), e.data("selectpicker", t = new Y(this, r)) } "string" == typeof c && (l = t[c] instanceof Function ? t[c].apply(t, a) : t.options[c]) } }); return void 0 !== l ? l : s } Y.VERSION = "1.13.14", Y.DEFAULTS = { noneSelectedText: "Nothing selected", noneResultsText: "No results matched {0}", countSelectedText: function (e, t) { return 1 == e ? "{0} item selected" : "{0} items selected" }, maxOptionsText: function (e, t) { return [1 == e ? "Limit reached ({n} item max)" : "Limit reached ({n} items max)", 1 == t ? "Group limit reached ({n} item max)" : "Group limit reached ({n} items max)"] }, selectAllText: "Select All", deselectAllText: "Deselect All", doneButton: !1, doneButtonText: "Close", multipleSeparator: ", ", styleBase: "btn", style: V.BUTTONCLASS, size: "auto", title: null, selectedTextFormat: "values", width: !1, container: !1, hideDisabled: !1, showSubtext: !1, showIcon: !0, showContent: !0, dropupAuto: !0, header: !1, liveSearch: !1, liveSearchPlaceholder: null, liveSearchNormalize: !1, liveSearchStyle: "contains", actionsBox: !1, iconBase: V.ICONBASE, tickIcon: V.TICKICON, showTick: !1, template: { caret: '<span class="caret"></span>' }, maxOptions: !1, mobile: !1, selectOnTab: !1, dropdownAlignRight: !1, windowPadding: 0, virtualScroll: 600, display: !1, sanitize: !0, sanitizeFn: null, whiteList: e }, Y.prototype = { constructor: Y, init: function () { var i = this, e = this.$element.attr("id"); U++, this.selectId = "bs-select-" + U, this.$element[0].classList.add("bs-select-hidden"), this.multiple = this.$element.prop("multiple"), this.autofocus = this.$element.prop("autofocus"), this.$element[0].classList.contains("show-tick") && (this.options.showTick = !0), this.$newElement = this.createDropdown(), this.buildData(), this.$element.after(this.$newElement).prependTo(this.$newElement), this.$button = this.$newElement.children("button"), this.$menu = this.$newElement.children(F.MENU), this.$menuInner = this.$menu.children(".inner"), this.$searchbox = this.$menu.find("input"), this.$element[0].classList.remove("bs-select-hidden"), !0 === this.options.dropdownAlignRight && this.$menu[0].classList.add(V.MENURIGHT), void 0 !== e && this.$button.attr("data-id", e), this.checkDisabled(), this.clickListener(), this.options.liveSearch ? (this.liveSearchListener(), this.focusedParent = this.$searchbox[0]) : this.focusedParent = this.$menuInner[0], this.setStyle(), this.render(), this.setWidth(), this.options.container ? this.selectPosition() : this.$element.on("hide" + j, function () { if (i.isVirtual()) { var e = i.$menuInner[0], t = e.firstChild.cloneNode(!1); e.replaceChild(t, e.firstChild), e.scrollTop = 0 } }), this.$menu.data("this", this), this.$newElement.data("this", this), this.options.mobile && this.mobile(), this.$newElement.on({ "hide.bs.dropdown": function (e) { i.$element.trigger("hide" + j, e) }, "hidden.bs.dropdown": function (e) { i.$element.trigger("hidden" + j, e) }, "show.bs.dropdown": function (e) { i.$element.trigger("show" + j, e) }, "shown.bs.dropdown": function (e) { i.$element.trigger("shown" + j, e) } }), i.$element[0].hasAttribute("required") && this.$element.on("invalid" + j, function () { i.$button[0].classList.add("bs-invalid"), i.$element.on("shown" + j + ".invalid", function () { i.$element.val(i.$element.val()).off("shown" + j + ".invalid") }).on("rendered" + j, function () { this.validity.valid && i.$button[0].classList.remove("bs-invalid"), i.$element.off("rendered" + j) }), i.$button.on("blur" + j, function () { i.$element.trigger("focus").trigger("blur"), i.$button.off("blur" + j) }) }), setTimeout(function () { i.buildList(), i.$element.trigger("loaded" + j) }) }, createDropdown: function () { var e = this.multiple || this.options.showTick ? " show-tick" : "", t = this.multiple ? ' aria-multiselectable="true"' : "", i = "", s = this.autofocus ? " autofocus" : ""; R.major < 4 && this.$element.parent().hasClass("input-group") && (i = " input-group-btn"); var n, o = "", r = "", l = "", a = ""; return this.options.header && (o = '<div class="' + V.POPOVERHEADER + '"><button type="button" class="close" aria-hidden="true">&times;</button>' + this.options.header + "</div>"), this.options.liveSearch && (r = '<div class="bs-searchbox"><input type="search" class="form-control" autocomplete="off"' + (null === this.options.liveSearchPlaceholder ? "" : ' placeholder="' + S(this.options.liveSearchPlaceholder) + '"') + ' role="combobox" aria-label="Search" aria-controls="' + this.selectId + '" aria-autocomplete="list"></div>'), this.multiple && this.options.actionsBox && (l = '<div class="bs-actionsbox"><div class="btn-group btn-group-sm btn-block"><button type="button" class="actions-btn bs-select-all btn ' + V.BUTTONCLASS + '">' + this.options.selectAllText + '</button><button type="button" class="actions-btn bs-deselect-all btn ' + V.BUTTONCLASS + '">' + this.options.deselectAllText + "</button></div></div>"), this.multiple && this.options.doneButton && (a = '<div class="bs-donebutton"><div class="btn-group btn-block"><button type="button" class="btn btn-sm ' + V.BUTTONCLASS + '">' + this.options.doneButtonText + "</button></div></div>"), n = '<div class="dropdown bootstrap-select' + e + i + '"><button type="button" class="' + this.options.styleBase + ' dropdown-toggle" ' + ("static" === this.options.display ? 'data-display="static"' : "") + 'data-toggle="dropdown"' + s + ' role="combobox" aria-owns="' + this.selectId + '" aria-haspopup="listbox" aria-expanded="false"><div class="filter-option"><div class="filter-option-inner"><div class="filter-option-inner-inner"></div></div> </div>' + ("4" === R.major ? "" : '<span class="bs-caret">' + this.options.template.caret + "</span>") + '</button><div class="' + V.MENU + " " + ("4" === R.major ? "" : V.SHOW) + '">' + o + r + l + '<div class="inner ' + V.SHOW + '" role="listbox" id="' + this.selectId + '" tabindex="-1" ' + t + '><ul class="' + V.MENU + " inner " + ("4" === R.major ? V.SHOW : "") + '" role="presentation"></ul></div>' + a + "</div></div>", z(n) }, setPositionData: function () { this.selectpicker.view.canHighlight = []; for (var e = this.selectpicker.view.size = 0; e < this.selectpicker.current.data.length; e++) { var t = this.selectpicker.current.data[e], i = !0; "divider" === t.type ? (i = !1, t.height = this.sizeInfo.dividerHeight) : "optgroup-label" === t.type ? (i = !1, t.height = this.sizeInfo.dropdownHeaderHeight) : t.height = this.sizeInfo.liHeight, t.disabled && (i = !1), this.selectpicker.view.canHighlight.push(i), i && (this.selectpicker.view.size++, t.posinset = this.selectpicker.view.size), t.position = (0 === e ? 0 : this.selectpicker.current.data[e - 1].position) + t.height } }, isVirtual: function () { return !1 !== this.options.virtualScroll && this.selectpicker.main.elements.length >= this.options.virtualScroll || !0 === this.options.virtualScroll }, createView: function (A, e, t) { var L, N, D = this, i = 0, H = []; if (this.selectpicker.isSearching = A, this.selectpicker.current = A ? this.selectpicker.search : this.selectpicker.main, this.setPositionData(), e) if (t) i = this.$menuInner[0].scrollTop; else if (!D.multiple) { var s = D.$element[0], n = (s.options[s.selectedIndex] || {}).liIndex; if ("number" == typeof n && !1 !== D.options.size) { var o = D.selectpicker.main.data[n], r = o && o.position; r && (i = r - (D.sizeInfo.menuInnerHeight + D.sizeInfo.liHeight) / 2) } } function l(e, t) { var i, s, n, o, r, l, a, c, d = D.selectpicker.current.elements.length, h = [], p = !0, u = D.isVirtual(); D.selectpicker.view.scrollTop = e, i = Math.ceil(D.sizeInfo.menuInnerHeight / D.sizeInfo.liHeight * 1.5), s = Math.round(d / i) || 1; for (var f = 0; f < s; f++) { var m = (f + 1) * i; if (f === s - 1 && (m = d), h[f] = [f * i + (f ? 1 : 0), m], !d) break; void 0 === r && e - 1 <= D.selectpicker.current.data[m - 1].position - D.sizeInfo.menuInnerHeight && (r = f) } if (void 0 === r && (r = 0), l = [D.selectpicker.view.position0, D.selectpicker.view.position1], n = Math.max(0, r - 1), o = Math.min(s - 1, r + 1), D.selectpicker.view.position0 = !1 === u ? 0 : Math.max(0, h[n][0]) || 0, D.selectpicker.view.position1 = !1 === u ? d : Math.min(d, h[o][1]) || 0, a = l[0] !== D.selectpicker.view.position0 || l[1] !== D.selectpicker.view.position1, void 0 !== D.activeIndex && (N = D.selectpicker.main.elements[D.prevActiveIndex], H = D.selectpicker.main.elements[D.activeIndex], L = D.selectpicker.main.elements[D.selectedIndex], t && (D.activeIndex !== D.selectedIndex && D.defocusItem(H), D.activeIndex = void 0), D.activeIndex && D.activeIndex !== D.selectedIndex && D.defocusItem(L)), void 0 !== D.prevActiveIndex && D.prevActiveIndex !== D.activeIndex && D.prevActiveIndex !== D.selectedIndex && D.defocusItem(N), (t || a) && (c = D.selectpicker.view.visibleElements ? D.selectpicker.view.visibleElements.slice() : [], D.selectpicker.view.visibleElements = !1 === u ? D.selectpicker.current.elements : D.selectpicker.current.elements.slice(D.selectpicker.view.position0, D.selectpicker.view.position1), D.setOptionStatus(), (A || !1 === u && t) && (p = !function (e, i) { return e.length === i.length && e.every(function (e, t) { return e === i[t] }) }(c, D.selectpicker.view.visibleElements)), (t || !0 === u) && p)) { var v, g, b = D.$menuInner[0], w = document.createDocumentFragment(), I = b.firstChild.cloneNode(!1), x = D.selectpicker.view.visibleElements, k = []; b.replaceChild(I, b.firstChild); f = 0; for (var y = x.length; f < y; f++) { var $, S, E = x[f]; D.options.sanitize && ($ = E.lastChild) && (S = D.selectpicker.current.data[f + D.selectpicker.view.position0]) && S.content && !S.sanitized && (k.push($), S.sanitized = !0), w.appendChild(E) } if (D.options.sanitize && k.length && P(k, D.options.whiteList, D.options.sanitizeFn), !0 === u ? (v = 0 === D.selectpicker.view.position0 ? 0 : D.selectpicker.current.data[D.selectpicker.view.position0 - 1].position, g = D.selectpicker.view.position1 > d - 1 ? 0 : D.selectpicker.current.data[d - 1].position - D.selectpicker.current.data[D.selectpicker.view.position1 - 1].position, b.firstChild.style.marginTop = v + "px", b.firstChild.style.marginBottom = g + "px") : (b.firstChild.style.marginTop = 0, b.firstChild.style.marginBottom = 0), b.firstChild.appendChild(w), !0 === u && D.sizeInfo.hasScrollBar) { var C = b.firstChild.offsetWidth; if (t && C < D.sizeInfo.menuInnerInnerWidth && D.sizeInfo.totalMenuWidth > D.sizeInfo.selectWidth) b.firstChild.style.minWidth = D.sizeInfo.menuInnerInnerWidth + "px"; else if (C > D.sizeInfo.menuInnerInnerWidth) { D.$menu[0].style.minWidth = 0; var O = b.firstChild.offsetWidth; O > D.sizeInfo.menuInnerInnerWidth && (D.sizeInfo.menuInnerInnerWidth = O, b.firstChild.style.minWidth = D.sizeInfo.menuInnerInnerWidth + "px"), D.$menu[0].style.minWidth = "" } } } if (D.prevActiveIndex = D.activeIndex, D.options.liveSearch) { if (A && t) { var z, T = 0; D.selectpicker.view.canHighlight[T] || (T = 1 + D.selectpicker.view.canHighlight.slice(1).indexOf(!0)), z = D.selectpicker.view.visibleElements[T], D.defocusItem(D.selectpicker.view.currentActive), D.activeIndex = (D.selectpicker.current.data[T] || {}).index, D.focusItem(z) } } else D.$menuInner.trigger("focus") } l(i, !0), this.$menuInner.off("scroll.createView").on("scroll.createView", function (e, t) { D.noScroll || l(this.scrollTop, t), D.noScroll = !1 }), z(window).off("resize" + j + "." + this.selectId + ".createView").on("resize" + j + "." + this.selectId + ".createView", function () { D.$newElement.hasClass(V.SHOW) && l(D.$menuInner[0].scrollTop) }) }, focusItem: function (e, t, i) { if (e) { t = t || this.selectpicker.main.data[this.activeIndex]; var s = e.firstChild; s && (s.setAttribute("aria-setsize", this.selectpicker.view.size), s.setAttribute("aria-posinset", t.posinset), !0 !== i && (this.focusedParent.setAttribute("aria-activedescendant", s.id), e.classList.add("active"), s.classList.add("active"))) } }, defocusItem: function (e) { e && (e.classList.remove("active"), e.firstChild && e.firstChild.classList.remove("active")) }, setPlaceholder: function () { var e = !1; if (this.options.title && !this.multiple) { this.selectpicker.view.titleOption || (this.selectpicker.view.titleOption = document.createElement("option")), e = !0; var t = this.$element[0], i = !1, s = !this.selectpicker.view.titleOption.parentNode; if (s) this.selectpicker.view.titleOption.className = "bs-title-option", this.selectpicker.view.titleOption.value = "", i = void 0 === z(t.options[t.selectedIndex]).attr("selected") && void 0 === this.$element.data("selected"); !s && 0 === this.selectpicker.view.titleOption.index || t.insertBefore(this.selectpicker.view.titleOption, t.firstChild), i && (t.selectedIndex = 0) } return e }, buildData: function () { var p = ':not([hidden]):not([data-hidden="true"])', u = [], f = 0, e = this.setPlaceholder() ? 1 : 0; this.options.hideDisabled && (p += ":not(:disabled)"); var t = this.$element[0].querySelectorAll("select > *" + p); function m(e) { var t = u[u.length - 1]; t && "divider" === t.type && (t.optID || e.optID) || ((e = e || {}).type = "divider", u.push(e)) } function v(e, t) { if ((t = t || {}).divider = "true" === e.getAttribute("data-divider"), t.divider) m({ optID: t.optID }); else { var i = u.length, s = e.style.cssText, n = s ? S(s) : "", o = (e.className || "") + (t.optgroupClass || ""); t.optID && (o = "opt " + o), t.optionClass = o.trim(), t.inlineStyle = n, t.text = e.textContent, t.content = e.getAttribute("data-content"), t.tokens = e.getAttribute("data-tokens"), t.subtext = e.getAttribute("data-subtext"), t.icon = e.getAttribute("data-icon"), e.liIndex = i, t.display = t.content || t.text, t.type = "option", t.index = i, t.option = e, t.selected = !!e.selected, t.disabled = t.disabled || !!e.disabled, u.push(t) } } function i(e, t) { var i = t[e], s = t[e - 1], n = t[e + 1], o = i.querySelectorAll("option" + p); if (o.length) { var r, l, a = { display: S(i.label), subtext: i.getAttribute("data-subtext"), icon: i.getAttribute("data-icon"), type: "optgroup-label", optgroupClass: " " + (i.className || "") }; f++, s && m({ optID: f }), a.optID = f, u.push(a); for (var c = 0, d = o.length; c < d; c++) { var h = o[c]; 0 === c && (l = (r = u.length - 1) + d), v(h, { headerIndex: r, lastIndex: l, optID: a.optID, optgroupClass: a.optgroupClass, disabled: i.disabled }) } n && m({ optID: f }) } } for (var s = t.length; e < s; e++) { var n = t[e]; "OPTGROUP" !== n.tagName ? v(n, {}) : i(e, t) } this.selectpicker.main.data = this.selectpicker.current.data = u }, buildList: function () { var s = this, e = this.selectpicker.main.data, n = [], o = 0; function t(e) { var t, i = 0; switch (e.type) { case "divider": t = K.li(!1, V.DIVIDER, e.optID ? e.optID + "div" : void 0); break; case "option": (t = K.li(K.a(K.text.call(s, e), e.optionClass, e.inlineStyle), "", e.optID)).firstChild && (t.firstChild.id = s.selectId + "-" + e.index); break; case "optgroup-label": t = K.li(K.label.call(s, e), "dropdown-header" + e.optgroupClass, e.optID) }n.push(t), e.display && (i += e.display.length), e.subtext && (i += e.subtext.length), e.icon && (i += 1), o < i && (o = i, s.selectpicker.view.widestOption = n[n.length - 1]) } !s.options.showTick && !s.multiple || _.checkMark.parentNode || (_.checkMark.className = this.options.iconBase + " " + s.options.tickIcon + " check-mark", _.a.appendChild(_.checkMark)); for (var i = e.length, r = 0; r < i; r++) { t(e[r]) } this.selectpicker.main.elements = this.selectpicker.current.elements = n }, findLis: function () { return this.$menuInner.find(".inner > li") }, render: function () { var e, t = this, i = this.$element[0], s = this.setPlaceholder() && 0 === i.selectedIndex, n = O(i, this.options.hideDisabled), o = n.length, r = this.$button[0], l = r.querySelector(".filter-option-inner-inner"), a = document.createTextNode(this.options.multipleSeparator), c = _.fragment.cloneNode(!1), d = !1; if (r.classList.toggle("bs-placeholder", t.multiple ? !o : !T(i, n)), this.tabIndex(), "static" === this.options.selectedTextFormat) c = K.text.call(this, { text: this.options.title }, !0); else if (!1 === (this.multiple && -1 !== this.options.selectedTextFormat.indexOf("count") && 1 < o && (1 < (e = this.options.selectedTextFormat.split(">")).length && o > e[1] || 1 === e.length && 2 <= o))) { if (!s) { for (var h = 0; h < o && h < 50; h++) { var p = n[h], u = this.selectpicker.main.data[p.liIndex], f = {}; this.multiple && 0 < h && c.appendChild(a.cloneNode(!1)), p.title ? f.text = p.title : u && (u.content && t.options.showContent ? (f.content = u.content.toString(), d = !0) : (t.options.showIcon && (f.icon = u.icon), t.options.showSubtext && !t.multiple && u.subtext && (f.subtext = " " + u.subtext), f.text = p.textContent.trim())), c.appendChild(K.text.call(this, f, !0)) } 49 < o && c.appendChild(document.createTextNode("...")) } } else { var m = ':not([hidden]):not([data-hidden="true"]):not([data-divider="true"])'; this.options.hideDisabled && (m += ":not(:disabled)"); var v = this.$element[0].querySelectorAll("select > option" + m + ", optgroup" + m + " option" + m).length, g = "function" == typeof this.options.countSelectedText ? this.options.countSelectedText(o, v) : this.options.countSelectedText; c = K.text.call(this, { text: g.replace("{0}", o.toString()).replace("{1}", v.toString()) }, !0) } if (null == this.options.title && (this.options.title = this.$element.attr("title")), c.childNodes.length || (c = K.text.call(this, { text: void 0 !== this.options.title ? this.options.title : this.options.noneSelectedText }, !0)), r.title = c.textContent.replace(/<[^>]*>?/g, "").trim(), this.options.sanitize && d && P([c], t.options.whiteList, t.options.sanitizeFn), l.innerHTML = "", l.appendChild(c), R.major < 4 && this.$newElement[0].classList.contains("bs3-has-addon")) { var b = r.querySelector(".filter-expand"), w = l.cloneNode(!0); w.className = "filter-expand", b ? r.replaceChild(w, b) : r.appendChild(w) } this.$element.trigger("rendered" + j) }, setStyle: function (e, t) { var i, s = this.$button[0], n = this.$newElement[0], o = this.options.style.trim(); this.$element.attr("class") && this.$newElement.addClass(this.$element.attr("class").replace(/selectpicker|mobile-device|bs-select-hidden|validate\[.*\]/gi, "")), R.major < 4 && (n.classList.add("bs3"), n.parentNode.classList.contains("input-group") && (n.previousElementSibling || n.nextElementSibling) && (n.previousElementSibling || n.nextElementSibling).classList.contains("input-group-addon") && n.classList.add("bs3-has-addon")), i = e ? e.trim() : o, "add" == t ? i && s.classList.add.apply(s.classList, i.split(" ")) : "remove" == t ? i && s.classList.remove.apply(s.classList, i.split(" ")) : (o && s.classList.remove.apply(s.classList, o.split(" ")), i && s.classList.add.apply(s.classList, i.split(" "))) }, liHeight: function (e) { if (e || !1 !== this.options.size && !Object.keys(this.sizeInfo).length) { var t = document.createElement("div"), i = document.createElement("div"), s = document.createElement("div"), n = document.createElement("ul"), o = document.createElement("li"), r = document.createElement("li"), l = document.createElement("li"), a = document.createElement("a"), c = document.createElement("span"), d = this.options.header && 0 < this.$menu.find("." + V.POPOVERHEADER).length ? this.$menu.find("." + V.POPOVERHEADER)[0].cloneNode(!0) : null, h = this.options.liveSearch ? document.createElement("div") : null, p = this.options.actionsBox && this.multiple && 0 < this.$menu.find(".bs-actionsbox").length ? this.$menu.find(".bs-actionsbox")[0].cloneNode(!0) : null, u = this.options.doneButton && this.multiple && 0 < this.$menu.find(".bs-donebutton").length ? this.$menu.find(".bs-donebutton")[0].cloneNode(!0) : null, f = this.$element.find("option")[0]; if (this.sizeInfo.selectWidth = this.$newElement[0].offsetWidth, c.className = "text", a.className = "dropdown-item " + (f ? f.className : ""), t.className = this.$menu[0].parentNode.className + " " + V.SHOW, t.style.width = 0, "auto" === this.options.width && (i.style.minWidth = 0), i.className = V.MENU + " " + V.SHOW, s.className = "inner " + V.SHOW, n.className = V.MENU + " inner " + ("4" === R.major ? V.SHOW : ""), o.className = V.DIVIDER, r.className = "dropdown-header", c.appendChild(document.createTextNode("\u200b")), a.appendChild(c), l.appendChild(a), r.appendChild(c.cloneNode(!0)), this.selectpicker.view.widestOption && n.appendChild(this.selectpicker.view.widestOption.cloneNode(!0)), n.appendChild(l), n.appendChild(o), n.appendChild(r), d && i.appendChild(d), h) { var m = document.createElement("input"); h.className = "bs-searchbox", m.className = "form-control", h.appendChild(m), i.appendChild(h) } p && i.appendChild(p), s.appendChild(n), i.appendChild(s), u && i.appendChild(u), t.appendChild(i), document.body.appendChild(t); var v, g = l.offsetHeight, b = r ? r.offsetHeight : 0, w = d ? d.offsetHeight : 0, I = h ? h.offsetHeight : 0, x = p ? p.offsetHeight : 0, k = u ? u.offsetHeight : 0, y = z(o).outerHeight(!0), $ = !!window.getComputedStyle && window.getComputedStyle(i), S = i.offsetWidth, E = $ ? null : z(i), C = { vert: L($ ? $.paddingTop : E.css("paddingTop")) + L($ ? $.paddingBottom : E.css("paddingBottom")) + L($ ? $.borderTopWidth : E.css("borderTopWidth")) + L($ ? $.borderBottomWidth : E.css("borderBottomWidth")), horiz: L($ ? $.paddingLeft : E.css("paddingLeft")) + L($ ? $.paddingRight : E.css("paddingRight")) + L($ ? $.borderLeftWidth : E.css("borderLeftWidth")) + L($ ? $.borderRightWidth : E.css("borderRightWidth")) }, O = { vert: C.vert + L($ ? $.marginTop : E.css("marginTop")) + L($ ? $.marginBottom : E.css("marginBottom")) + 2, horiz: C.horiz + L($ ? $.marginLeft : E.css("marginLeft")) + L($ ? $.marginRight : E.css("marginRight")) + 2 }; s.style.overflowY = "scroll", v = i.offsetWidth - S, document.body.removeChild(t), this.sizeInfo.liHeight = g, this.sizeInfo.dropdownHeaderHeight = b, this.sizeInfo.headerHeight = w, this.sizeInfo.searchHeight = I, this.sizeInfo.actionsHeight = x, this.sizeInfo.doneButtonHeight = k, this.sizeInfo.dividerHeight = y, this.sizeInfo.menuPadding = C, this.sizeInfo.menuExtras = O, this.sizeInfo.menuWidth = S, this.sizeInfo.menuInnerInnerWidth = S - C.horiz, this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth, this.sizeInfo.scrollBarWidth = v, this.sizeInfo.selectHeight = this.$newElement[0].offsetHeight, this.setPositionData() } }, getSelectPosition: function () { var e, t = z(window), i = this.$newElement.offset(), s = z(this.options.container); this.options.container && s.length && !s.is("body") ? ((e = s.offset()).top += parseInt(s.css("borderTopWidth")), e.left += parseInt(s.css("borderLeftWidth"))) : e = { top: 0, left: 0 }; var n = this.options.windowPadding; this.sizeInfo.selectOffsetTop = i.top - e.top - t.scrollTop(), this.sizeInfo.selectOffsetBot = t.height() - this.sizeInfo.selectOffsetTop - this.sizeInfo.selectHeight - e.top - n[2], this.sizeInfo.selectOffsetLeft = i.left - e.left - t.scrollLeft(), this.sizeInfo.selectOffsetRight = t.width() - this.sizeInfo.selectOffsetLeft - this.sizeInfo.selectWidth - e.left - n[1], this.sizeInfo.selectOffsetTop -= n[0], this.sizeInfo.selectOffsetLeft -= n[3] }, setMenuSize: function (e) { this.getSelectPosition(); var t, i, s, n, o, r, l, a, c = this.sizeInfo.selectWidth, d = this.sizeInfo.liHeight, h = this.sizeInfo.headerHeight, p = this.sizeInfo.searchHeight, u = this.sizeInfo.actionsHeight, f = this.sizeInfo.doneButtonHeight, m = this.sizeInfo.dividerHeight, v = this.sizeInfo.menuPadding, g = 0; if (this.options.dropupAuto && (l = d * this.selectpicker.current.elements.length + v.vert, a = this.sizeInfo.selectOffsetTop - this.sizeInfo.selectOffsetBot > this.sizeInfo.menuExtras.vert && l + this.sizeInfo.menuExtras.vert + 50 > this.sizeInfo.selectOffsetBot, !0 === this.selectpicker.isSearching && (a = this.selectpicker.dropup), this.$newElement.toggleClass(V.DROPUP, a), this.selectpicker.dropup = a), "auto" === this.options.size) n = 3 < this.selectpicker.current.elements.length ? 3 * this.sizeInfo.liHeight + this.sizeInfo.menuExtras.vert - 2 : 0, i = this.sizeInfo.selectOffsetBot - this.sizeInfo.menuExtras.vert, s = n + h + p + u + f, r = Math.max(n - v.vert, 0), this.$newElement.hasClass(V.DROPUP) && (i = this.sizeInfo.selectOffsetTop - this.sizeInfo.menuExtras.vert), t = (o = i) - h - p - u - f - v.vert; else if (this.options.size && "auto" != this.options.size && this.selectpicker.current.elements.length > this.options.size) { for (var b = 0; b < this.options.size; b++)"divider" === this.selectpicker.current.data[b].type && g++; t = (i = d * this.options.size + g * m + v.vert) - v.vert, o = i + h + p + u + f, s = r = "" } this.$menu.css({ "max-height": o + "px", overflow: "hidden", "min-height": s + "px" }), this.$menuInner.css({ "max-height": t + "px", "overflow-y": "auto", "min-height": r + "px" }), this.sizeInfo.menuInnerHeight = Math.max(t, 1), this.selectpicker.current.data.length && this.selectpicker.current.data[this.selectpicker.current.data.length - 1].position > this.sizeInfo.menuInnerHeight && (this.sizeInfo.hasScrollBar = !0, this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth + this.sizeInfo.scrollBarWidth), "auto" === this.options.dropdownAlignRight && this.$menu.toggleClass(V.MENURIGHT, this.sizeInfo.selectOffsetLeft > this.sizeInfo.selectOffsetRight && this.sizeInfo.selectOffsetRight < this.sizeInfo.totalMenuWidth - c), this.dropdown && this.dropdown._popper && this.dropdown._popper.update() }, setSize: function (e) { if (this.liHeight(e), this.options.header && this.$menu.css("padding-top", 0), !1 !== this.options.size) { var t = this, i = z(window); this.setMenuSize(), this.options.liveSearch && this.$searchbox.off("input.setMenuSize propertychange.setMenuSize").on("input.setMenuSize propertychange.setMenuSize", function () { return t.setMenuSize() }), "auto" === this.options.size ? i.off("resize" + j + "." + this.selectId + ".setMenuSize scroll" + j + "." + this.selectId + ".setMenuSize").on("resize" + j + "." + this.selectId + ".setMenuSize scroll" + j + "." + this.selectId + ".setMenuSize", function () { return t.setMenuSize() }) : this.options.size && "auto" != this.options.size && this.selectpicker.current.elements.length > this.options.size && i.off("resize" + j + "." + this.selectId + ".setMenuSize scroll" + j + "." + this.selectId + ".setMenuSize") } this.createView(!1, !0, e) }, setWidth: function () { var i = this; "auto" === this.options.width ? requestAnimationFrame(function () { i.$menu.css("min-width", "0"), i.$element.on("loaded" + j, function () { i.liHeight(), i.setMenuSize(); var e = i.$newElement.clone().appendTo("body"), t = e.css("width", "auto").children("button").outerWidth(); e.remove(), i.sizeInfo.selectWidth = Math.max(i.sizeInfo.totalMenuWidth, t), i.$newElement.css("width", i.sizeInfo.selectWidth + "px") }) }) : "fit" === this.options.width ? (this.$menu.css("min-width", ""), this.$newElement.css("width", "").addClass("fit-width")) : this.options.width ? (this.$menu.css("min-width", ""), this.$newElement.css("width", this.options.width)) : (this.$menu.css("min-width", ""), this.$newElement.css("width", "")), this.$newElement.hasClass("fit-width") && "fit" !== this.options.width && this.$newElement[0].classList.remove("fit-width") }, selectPosition: function () { this.$bsContainer = z('<div class="bs-container" />'); function e(e) { var t = {}, i = r.options.display || !!z.fn.dropdown.Constructor.Default && z.fn.dropdown.Constructor.Default.display; r.$bsContainer.addClass(e.attr("class").replace(/form-control|fit-width/gi, "")).toggleClass(V.DROPUP, e.hasClass(V.DROPUP)), s = e.offset(), l.is("body") ? n = { top: 0, left: 0 } : ((n = l.offset()).top += parseInt(l.css("borderTopWidth")) - l.scrollTop(), n.left += parseInt(l.css("borderLeftWidth")) - l.scrollLeft()), o = e.hasClass(V.DROPUP) ? 0 : e[0].offsetHeight, (R.major < 4 || "static" === i) && (t.top = s.top - n.top + o, t.left = s.left - n.left), t.width = e[0].offsetWidth, r.$bsContainer.css(t) } var s, n, o, r = this, l = z(this.options.container); this.$button.on("click.bs.dropdown.data-api", function () { r.isDisabled() || (e(r.$newElement), r.$bsContainer.appendTo(r.options.container).toggleClass(V.SHOW, !r.$button.hasClass(V.SHOW)).append(r.$menu)) }), z(window).off("resize" + j + "." + this.selectId + " scroll" + j + "." + this.selectId).on("resize" + j + "." + this.selectId + " scroll" + j + "." + this.selectId, function () { r.$newElement.hasClass(V.SHOW) && e(r.$newElement) }), this.$element.on("hide" + j, function () { r.$menu.data("height", r.$menu.height()), r.$bsContainer.detach() }) }, setOptionStatus: function (e) { var t = this; if (t.noScroll = !1, t.selectpicker.view.visibleElements && t.selectpicker.view.visibleElements.length) for (var i = 0; i < t.selectpicker.view.visibleElements.length; i++) { var s = t.selectpicker.current.data[i + t.selectpicker.view.position0], n = s.option; n && (!0 !== e && t.setDisabled(s.index, s.disabled), t.setSelected(s.index, n.selected)) } }, setSelected: function (e, t) { var i, s, n = this.selectpicker.main.elements[e], o = this.selectpicker.main.data[e], r = void 0 !== this.activeIndex, l = this.activeIndex === e || t && !this.multiple && !r; o.selected = t, s = n.firstChild, t && (this.selectedIndex = e), n.classList.toggle("selected", t), l ? (this.focusItem(n, o), this.selectpicker.view.currentActive = n, this.activeIndex = e) : this.defocusItem(n), s && (s.classList.toggle("selected", t), t ? s.setAttribute("aria-selected", !0) : this.multiple ? s.setAttribute("aria-selected", !1) : s.removeAttribute("aria-selected")), l || r || !t || void 0 === this.prevActiveIndex || (i = this.selectpicker.main.elements[this.prevActiveIndex], this.defocusItem(i)) }, setDisabled: function (e, t) { var i, s = this.selectpicker.main.elements[e]; this.selectpicker.main.data[e].disabled = t, i = s.firstChild, s.classList.toggle(V.DISABLED, t), i && ("4" === R.major && i.classList.toggle(V.DISABLED, t), t ? (i.setAttribute("aria-disabled", t), i.setAttribute("tabindex", -1)) : (i.removeAttribute("aria-disabled"), i.setAttribute("tabindex", 0))) }, isDisabled: function () { return this.$element[0].disabled }, checkDisabled: function () { this.isDisabled() ? (this.$newElement[0].classList.add(V.DISABLED), this.$button.addClass(V.DISABLED).attr("tabindex", -1).attr("aria-disabled", !0)) : (this.$button[0].classList.contains(V.DISABLED) && (this.$newElement[0].classList.remove(V.DISABLED), this.$button.removeClass(V.DISABLED).attr("aria-disabled", !1)), -1 != this.$button.attr("tabindex") || this.$element.data("tabindex") || this.$button.removeAttr("tabindex")) }, tabIndex: function () { this.$element.data("tabindex") !== this.$element.attr("tabindex") && -98 !== this.$element.attr("tabindex") && "-98" !== this.$element.attr("tabindex") && (this.$element.data("tabindex", this.$element.attr("tabindex")), this.$button.attr("tabindex", this.$element.data("tabindex"))), this.$element.attr("tabindex", -98) }, clickListener: function () { var C = this, t = z(document); function e() { C.options.liveSearch ? C.$searchbox.trigger("focus") : C.$menuInner.trigger("focus") } function i() { C.dropdown && C.dropdown._popper && C.dropdown._popper.state.isCreated ? e() : requestAnimationFrame(i) } t.data("spaceSelect", !1), this.$button.on("keyup", function (e) { /(32)/.test(e.keyCode.toString(10)) && t.data("spaceSelect") && (e.preventDefault(), t.data("spaceSelect", !1)) }), this.$newElement.on("show.bs.dropdown", function () { 3 < R.major && !C.dropdown && (C.dropdown = C.$button.data("bs.dropdown"), C.dropdown._menu = C.$menu[0]) }), this.$button.on("click.bs.dropdown.data-api", function () { C.$newElement.hasClass(V.SHOW) || C.setSize() }), this.$element.on("shown" + j, function () { C.$menuInner[0].scrollTop !== C.selectpicker.view.scrollTop && (C.$menuInner[0].scrollTop = C.selectpicker.view.scrollTop), 3 < R.major ? requestAnimationFrame(i) : e() }), this.$menuInner.on("mouseenter", "li a", function (e) { var t = this.parentElement, i = C.isVirtual() ? C.selectpicker.view.position0 : 0, s = Array.prototype.indexOf.call(t.parentElement.children, t), n = C.selectpicker.current.data[s + i]; C.focusItem(t, n, !0) }), this.$menuInner.on("click", "li a", function (e, t) { var i = z(this), s = C.$element[0], n = C.isVirtual() ? C.selectpicker.view.position0 : 0, o = C.selectpicker.current.data[i.parent().index() + n], r = o.index, l = T(s), a = s.selectedIndex, c = s.options[a], d = !0; if (C.multiple && 1 !== C.options.maxOptions && e.stopPropagation(), e.preventDefault(), !C.isDisabled() && !i.parent().hasClass(V.DISABLED)) { var h = o.option, p = z(h), u = h.selected, f = p.parent("optgroup"), m = f.find("option"), v = C.options.maxOptions, g = f.data("maxOptions") || !1; if (r === C.activeIndex && (t = !0), t || (C.prevActiveIndex = C.activeIndex, C.activeIndex = void 0), C.multiple) { if (h.selected = !u, C.setSelected(r, !u), i.trigger("blur"), !1 !== v || !1 !== g) { var b = v < O(s).length, w = g < f.find("option:selected").length; if (v && b || g && w) if (v && 1 == v) s.selectedIndex = -1, h.selected = !0, C.setOptionStatus(!0); else if (g && 1 == g) { for (var I = 0; I < m.length; I++) { var x = m[I]; x.selected = !1, C.setSelected(x.liIndex, !1) } h.selected = !0, C.setSelected(r, !0) } else { var k = "string" == typeof C.options.maxOptionsText ? [C.options.maxOptionsText, C.options.maxOptionsText] : C.options.maxOptionsText, y = "function" == typeof k ? k(v, g) : k, $ = y[0].replace("{n}", v), S = y[1].replace("{n}", g), E = z('<div class="notify"></div>'); y[2] && ($ = $.replace("{var}", y[2][1 < v ? 0 : 1]), S = S.replace("{var}", y[2][1 < g ? 0 : 1])), h.selected = !1, C.$menu.append(E), v && b && (E.append(z("<div>" + $ + "</div>")), d = !1, C.$element.trigger("maxReached" + j)), g && w && (E.append(z("<div>" + S + "</div>")), d = !1, C.$element.trigger("maxReachedGrp" + j)), setTimeout(function () { C.setSelected(r, !1) }, 10), E[0].classList.add("fadeOut"), setTimeout(function () { E.remove() }, 1050) } } } else c && (c.selected = !1), h.selected = !0, C.setSelected(r, !0); !C.multiple || C.multiple && 1 === C.options.maxOptions ? C.$button.trigger("focus") : C.options.liveSearch && C.$searchbox.trigger("focus"), d && (!C.multiple && a === s.selectedIndex || (A = [h.index, p.prop("selected"), l], C.$element.triggerNative("change"))) } }), this.$menu.on("click", "li." + V.DISABLED + " a, ." + V.POPOVERHEADER + ", ." + V.POPOVERHEADER + " :not(.close)", function (e) { e.currentTarget == this && (e.preventDefault(), e.stopPropagation(), C.options.liveSearch && !z(e.target).hasClass("close") ? C.$searchbox.trigger("focus") : C.$button.trigger("focus")) }), this.$menuInner.on("click", ".divider, .dropdown-header", function (e) { e.preventDefault(), e.stopPropagation(), C.options.liveSearch ? C.$searchbox.trigger("focus") : C.$button.trigger("focus") }), this.$menu.on("click", "." + V.POPOVERHEADER + " .close", function () { C.$button.trigger("click") }), this.$searchbox.on("click", function (e) { e.stopPropagation() }), this.$menu.on("click", ".actions-btn", function (e) { C.options.liveSearch ? C.$searchbox.trigger("focus") : C.$button.trigger("focus"), e.preventDefault(), e.stopPropagation(), z(this).hasClass("bs-select-all") ? C.selectAll() : C.deselectAll() }), this.$element.on("change" + j, function () { C.render(), C.$element.trigger("changed" + j, A), A = null }).on("focus" + j, function () { C.options.mobile || C.$button.trigger("focus") }) }, liveSearchListener: function () { var u = this, f = document.createElement("li"); this.$button.on("click.bs.dropdown.data-api", function () { u.$searchbox.val() && u.$searchbox.val("") }), this.$searchbox.on("click.bs.dropdown.data-api focus.bs.dropdown.data-api touchend.bs.dropdown.data-api", function (e) { e.stopPropagation() }), this.$searchbox.on("input propertychange", function () { var e = u.$searchbox.val(); if (u.selectpicker.search.elements = [], u.selectpicker.search.data = [], e) { var t = [], i = e.toUpperCase(), s = {}, n = [], o = u._searchStyle(), r = u.options.liveSearchNormalize; r && (i = w(i)); for (var l = 0; l < u.selectpicker.main.data.length; l++) { var a = u.selectpicker.main.data[l]; s[l] || (s[l] = k(a, i, o, r)), s[l] && void 0 !== a.headerIndex && -1 === n.indexOf(a.headerIndex) && (0 < a.headerIndex && (s[a.headerIndex - 1] = !0, n.push(a.headerIndex - 1)), s[a.headerIndex] = !0, n.push(a.headerIndex), s[a.lastIndex + 1] = !0), s[l] && "optgroup-label" !== a.type && n.push(l) } l = 0; for (var c = n.length; l < c; l++) { var d = n[l], h = n[l - 1], p = (a = u.selectpicker.main.data[d], u.selectpicker.main.data[h]); ("divider" !== a.type || "divider" === a.type && p && "divider" !== p.type && c - 1 !== l) && (u.selectpicker.search.data.push(a), t.push(u.selectpicker.main.elements[d])) } u.activeIndex = void 0, u.noScroll = !0, u.$menuInner.scrollTop(0), u.selectpicker.search.elements = t, u.createView(!0), t.length || (f.className = "no-results", f.innerHTML = u.options.noneResultsText.replace("{0}", '"' + S(e) + '"'), u.$menuInner[0].firstChild.appendChild(f)) } else u.$menuInner.scrollTop(0), u.createView(!1) }) }, _searchStyle: function () { return this.options.liveSearchStyle || "contains" }, val: function (e) { var t = this.$element[0]; if (void 0 === e) return this.$element.val(); var i = T(t); if (A = [null, null, i], this.$element.val(e).trigger("changed" + j, A), this.$newElement.hasClass(V.SHOW)) if (this.multiple) this.setOptionStatus(!0); else { var s = (t.options[t.selectedIndex] || {}).liIndex; "number" == typeof s && (this.setSelected(this.selectedIndex, !1), this.setSelected(s, !0)) } return this.render(), A = null, this.$element }, changeAll: function (e) { if (this.multiple) { void 0 === e && (e = !0); var t = this.$element[0], i = 0, s = 0, n = T(t); t.classList.add("bs-select-hidden"); for (var o = 0, r = this.selectpicker.current.data, l = r.length; o < l; o++) { var a = r[o], c = a.option; c && !a.disabled && "divider" !== a.type && (a.selected && i++, !0 === (c.selected = e) && s++) } t.classList.remove("bs-select-hidden"), i !== s && (this.setOptionStatus(), A = [null, null, n], this.$element.triggerNative("change")) } }, selectAll: function () { return this.changeAll(!0) }, deselectAll: function () { return this.changeAll(!1) }, toggle: function (e) { (e = e || window.event) && e.stopPropagation(), this.$button.trigger("click.bs.dropdown.data-api") }, keydown: function (e) { var t, i, s, n, o, r = z(this), l = r.hasClass("dropdown-toggle"), a = (l ? r.closest(".dropdown") : r.closest(F.MENU)).data("this"), c = a.findLis(), d = !1, h = e.which === W && !l && !a.options.selectOnTab, p = G.test(e.which) || h, u = a.$menuInner[0].scrollTop, f = !0 === a.isVirtual() ? a.selectpicker.view.position0 : 0; if (!(112 <= e.which && e.which <= 123)) if (!(i = a.$newElement.hasClass(V.SHOW)) && (p || 48 <= e.which && e.which <= 57 || 96 <= e.which && e.which <= 105 || 65 <= e.which && e.which <= 90) && (a.$button.trigger("click.bs.dropdown.data-api"), a.options.liveSearch)) a.$searchbox.trigger("focus"); else { if (e.which === N && i && (e.preventDefault(), a.$button.trigger("click.bs.dropdown.data-api").trigger("focus")), p) { if (!c.length) return; -1 !== (t = (s = a.selectpicker.main.elements[a.activeIndex]) ? Array.prototype.indexOf.call(s.parentElement.children, s) : -1) && a.defocusItem(s), e.which === B ? (-1 !== t && t--, t + f < 0 && (t += c.length), a.selectpicker.view.canHighlight[t + f] || -1 === (t = a.selectpicker.view.canHighlight.slice(0, t + f).lastIndexOf(!0) - f) && (t = c.length - 1)) : e.which !== M && !h || (++t + f >= a.selectpicker.view.canHighlight.length && (t = 0), a.selectpicker.view.canHighlight[t + f] || (t = t + 1 + a.selectpicker.view.canHighlight.slice(t + f + 1).indexOf(!0))), e.preventDefault(); var m = f + t; e.which === B ? 0 === f && t === c.length - 1 ? (a.$menuInner[0].scrollTop = a.$menuInner[0].scrollHeight, m = a.selectpicker.current.elements.length - 1) : d = (o = (n = a.selectpicker.current.data[m]).position - n.height) < u : e.which !== M && !h || (0 === t ? m = a.$menuInner[0].scrollTop = 0 : d = u < (o = (n = a.selectpicker.current.data[m]).position - a.sizeInfo.menuInnerHeight)), s = a.selectpicker.current.elements[m], a.activeIndex = a.selectpicker.current.data[m].index, a.focusItem(s), a.selectpicker.view.currentActive = s, d && (a.$menuInner[0].scrollTop = o), a.options.liveSearch ? a.$searchbox.trigger("focus") : r.trigger("focus") } else if (!r.is("input") && !q.test(e.which) || e.which === H && a.selectpicker.keydown.keyHistory) { var v, g, b = []; e.preventDefault(), a.selectpicker.keydown.keyHistory += C[e.which], a.selectpicker.keydown.resetKeyHistory.cancel && clearTimeout(a.selectpicker.keydown.resetKeyHistory.cancel), a.selectpicker.keydown.resetKeyHistory.cancel = a.selectpicker.keydown.resetKeyHistory.start(), g = a.selectpicker.keydown.keyHistory, /^(.)\1+$/.test(g) && (g = g.charAt(0)); for (var w = 0; w < a.selectpicker.current.data.length; w++) { var I = a.selectpicker.current.data[w]; k(I, g, "startsWith", !0) && a.selectpicker.view.canHighlight[w] && b.push(I.index) } if (b.length) { var x = 0; c.removeClass("active").find("a").removeClass("active"), 1 === g.length && (-1 === (x = b.indexOf(a.activeIndex)) || x === b.length - 1 ? x = 0 : x++), v = b[x], d = 0 < u - (n = a.selectpicker.main.data[v]).position ? (o = n.position - n.height, !0) : (o = n.position - a.sizeInfo.menuInnerHeight, n.position > u + a.sizeInfo.menuInnerHeight), s = a.selectpicker.main.elements[v], a.activeIndex = b[x], a.focusItem(s), s && s.firstChild.focus(), d && (a.$menuInner[0].scrollTop = o), r.trigger("focus") } } i && (e.which === H && !a.selectpicker.keydown.keyHistory || e.which === D || e.which === W && a.options.selectOnTab) && (e.which !== H && e.preventDefault(), a.options.liveSearch && e.which === H || (a.$menuInner.find(".active a").trigger("click", !0), r.trigger("focus"), a.options.liveSearch || (e.preventDefault(), z(document).data("spaceSelect", !0)))) } }, mobile: function () { this.$element[0].classList.add("mobile-device") }, refresh: function () { var e = z.extend({}, this.options, this.$element.data()); this.options = e, this.checkDisabled(), this.setStyle(), this.render(), this.buildData(), this.buildList(), this.setWidth(), this.setSize(!0), this.$element.trigger("refreshed" + j) }, hide: function () { this.$newElement.hide() }, show: function () { this.$newElement.show() }, remove: function () { this.$newElement.remove(), this.$element.remove() }, destroy: function () { this.$newElement.before(this.$element).remove(), this.$bsContainer ? this.$bsContainer.remove() : this.$menu.remove(), this.$element.off(j).removeData("selectpicker").removeClass("bs-select-hidden selectpicker"), z(window).off(j + "." + this.selectId) } }; var J = z.fn.selectpicker; z.fn.selectpicker = Z, z.fn.selectpicker.Constructor = Y, z.fn.selectpicker.noConflict = function () { return z.fn.selectpicker = J, this }; var Q = z.fn.dropdown.Constructor._dataApiKeydownHandler || z.fn.dropdown.Constructor.prototype.keydown; z(document).off("keydown.bs.dropdown.data-api").on("keydown.bs.dropdown.data-api", ':not(.bootstrap-select) > [data-toggle="dropdown"]', Q).on("keydown.bs.dropdown.data-api", ":not(.bootstrap-select) > .dropdown-menu", Q).on("keydown" + j, '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bootstrap-select .bs-searchbox input', Y.prototype.keydown).on("focusin.modal", '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bootstrap-select .bs-searchbox input', function (e) { e.stopPropagation() }), z(window).on("load" + j + ".data-api", function () { z(".selectpicker").each(function () { var e = z(this); Z.call(e, e.data()) }) }) }(e) });

function debounce(func, wait, immediate) {
  var timeout, args, context, timestamp, result;
  if (null == wait) wait = 100;

  function later() {
    var last = Date.now() - timestamp;

    if (last < wait && last >= 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      if (!immediate) {
        result = func.apply(context, args);
        context = args = null;
      }
    }
  };

  var debounced = function () {
    context = this;
    args = arguments;
    timestamp = Date.now();
    var callNow = immediate && !timeout;
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };

  debounced.clear = function () {
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
  };

  debounced.flush = function () {
    if (timeout) {
      result = func.apply(context, args);
      context = args = null;

      clearTimeout(timeout);
      timeout = null;
    }
  };

  return debounced;
};

/**
 * @name MarkerClustererPlus for Google Maps V3
 * @version 2.1.11
 * @author Gary Little
 * @fileoverview
 * The library creates and manages per-zoom-level clusters for large amounts of markers.
 * <p>
 * This is an enhanced V3 implementation of the V2 MarkerClusterer by Xiaoxi Wu. It is
 * based on the V3 MarkerClusterer port by Luke Mahe. MarkerClustererPlus was created
 * by Gary Little.
 * <p>
 * v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It
 *  adds support for the <code>ignoreHidden</code>, <code>title</code>, <code>batchSizeIE</code>,
 *  and <code>calculator</code> properties as well as support for four more events. It also allows
 *  greater control over the styling of the text that appears on the cluster marker. The
 *  documentation has been significantly improved and the overall code has been simplified and
 *  polished. Very large numbers of markers can now be managed without causing Javascript timeout
 *  errors on Internet Explorer. Note that the name of the <code>clusterclick</code> event has been
 *  deprecated. The new name is <code>click</code>, so please change your application code now.
 */

/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//2023-07-18 : if (user_ip == '108.180.234.14') console.log('2188 - ');

/**
 * @name ClusterIconStyle
 * @class This class represents the object for values in the <code>styles</code> array passed
 *  to the {@link MarkerClusterer} constructor. The element in this array that is used to
 *  style the cluster icon is determined by calling the <code>calculator</code> function.
 *
 * @property {string} url The URL of the cluster icon image file. Required.
 * @property {number} height The display height (in pixels) of the cluster icon. Required.
 * @property {number} width The display width (in pixels) of the cluster icon. Required.
 * @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to
 *  where the text label is to be centered and drawn. The format is <code>[yoffset, xoffset]</code>
 *  where <code>yoffset</code> increases as you go down from center and <code>xoffset</code>
 *  increases to the right of center. The default is <code>[0, 0]</code>.
 * @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the
 *  spot on the cluster icon that is to be aligned with the cluster position. The format is
 *  <code>[yoffset, xoffset]</code> where <code>yoffset</code> increases as you go down and
 *  <code>xoffset</code> increases to the right of the top-left corner of the icon. The default
 *  anchor position is the center of the cluster icon.
 * @property {string} [textColor="black"] The color of the label text shown on the
 *  cluster icon.
 * @property {number} [textSize=11] The size (in pixels) of the label text shown on the
 *  cluster icon.
 * @property {string} [textDecoration="none"] The value of the CSS <code>text-decoration</code>
 *  property for the label text shown on the cluster icon.
 * @property {string} [fontWeight="bold"] The value of the CSS <code>font-weight</code>
 *  property for the label text shown on the cluster icon.
 * @property {string} [fontStyle="normal"] The value of the CSS <code>font-style</code>
 *  property for the label text shown on the cluster icon.
 * @property {string} [fontFamily="Arial,sans-serif"] The value of the CSS <code>font-family</code>
 *  property for the label text shown on the cluster icon.
 * @property {string} [backgroundPosition="0 0"] The position of the cluster icon image
 *  within the image defined by <code>url</code>. The format is <code>"xpos ypos"</code>
 *  (the same format as for the CSS <code>background-position</code> property). You must set
 *  this property appropriately when the image defined by <code>url</code> represents a sprite
 *  containing multiple images. Note that the position <i>must</i> be specified in px units.
 */
/**
 * @name ClusterIconInfo
 * @class This class is an object containing general information about a cluster icon. This is
 *  the object that a <code>calculator</code> function returns.
 *
 * @property {string} text The text of the label to be shown on the cluster icon.
 * @property {number} index The index plus 1 of the element in the <code>styles</code>
 *  array to be used to style the cluster icon.
 * @property {string} title The tooltip to display when the mouse moves over the cluster icon.
 *  If this value is <code>undefined</code> or <code>""</code>, <code>title</code> is set to the
 *  value of the <code>title</code> property passed to the MarkerClusterer.
 */
/**
 * A cluster icon.
 *
 * @constructor
 * @extends google.maps.OverlayView
 * @param {Cluster} cluster The cluster with which the icon is to be associated.
 * @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons
 *  to use for various cluster sizes.
 * @private
 */
function ClusterIcon(cluster, styles) {
  cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView);

  this.cluster_ = cluster;
  this.className_ = cluster.getMarkerClusterer().getClusterClass();
  this.styles_ = styles;
  this.center_ = null;
  this.div_ = null;
  this.sums_ = null;
  this.visible_ = false;

  this.setMap(cluster.getMap()); // Note: this causes onAdd to be called
}


/**
 * Adds the icon to the DOM.
 */
ClusterIcon.prototype.onAdd = function () {
  var cClusterIcon = this;
  var cMouseDownInCluster;
  var cDraggingMapByCluster;
  var gmVersion = google.maps.version.split(".");

  gmVersion = parseInt(gmVersion[0] * 100, 10) + parseInt(gmVersion[1], 10);

  this.div_ = document.createElement("div");
  this.div_.className = this.className_;
  if (this.visible_) {
    this.show();
  }

  this.getPanes().overlayMouseTarget.appendChild(this.div_);

  // Fix for Issue 157
  this.boundsChangedListener_ = google.maps.event.addListener(this.getMap(), "bounds_changed", function () {
    cDraggingMapByCluster = cMouseDownInCluster;
  });

  google.maps.event.addDomListener(this.div_, "mousedown", function () {
    cMouseDownInCluster = true;
    cDraggingMapByCluster = false;
  });

  // March 1, 2018: Fix for this 3.32 exp bug, https://issuetracker.google.com/issues/73571522
  // But it doesn't work with earlier releases so do a version check.
  if (gmVersion >= 332) { // Ugly version-dependent code
    google.maps.event.addDomListener(this.div_, "touchstart", function (e) {
      e.stopPropagation();
    });
  }

  google.maps.event.addDomListener(this.div_, "click", function (e) {
    cMouseDownInCluster = false;
    if (!cDraggingMapByCluster) {
      var theBounds;
      var mz;
      var mc = cClusterIcon.cluster_.getMarkerClusterer();
      /**
       * This event is fired when a cluster marker is clicked.
       * @name MarkerClusterer#click
       * @param {Cluster} c The cluster that was clicked.
       * @event
       */
      google.maps.event.trigger(mc, "click", cClusterIcon.cluster_);
      google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name

      // The default click handler follows. Disable it by setting
      // the zoomOnClick property to false.
      if (mc.getZoomOnClick()) {
        // Zoom into the cluster.
        mz = mc.getMaxZoom();
        theBounds = cClusterIcon.cluster_.getBounds();
        mc.getMap().fitBounds(theBounds);
        // There is a fix for Issue 170 here:
        setTimeout(function () {
          mc.getMap().fitBounds(theBounds);
          // Don't zoom beyond the max zoom level
          if (mz !== null && (mc.getMap().getZoom() > mz)) {
            mc.getMap().setZoom(mz + 1);
          }
        }, 100);
      }

      // Prevent event propagation to the map:
      e.cancelBubble = true;
      if (e.stopPropagation) {
        e.stopPropagation();
      }
    }
  });

  google.maps.event.addDomListener(this.div_, "mouseover", function () {
    var mc = cClusterIcon.cluster_.getMarkerClusterer();
    /**
     * This event is fired when the mouse moves over a cluster marker.
     * @name MarkerClusterer#mouseover
     * @param {Cluster} c The cluster that the mouse moved over.
     * @event
     */
    google.maps.event.trigger(mc, "mouseover", cClusterIcon.cluster_);
  });

  google.maps.event.addDomListener(this.div_, "mouseout", function () {
    var mc = cClusterIcon.cluster_.getMarkerClusterer();
    /**
     * This event is fired when the mouse moves out of a cluster marker.
     * @name MarkerClusterer#mouseout
     * @param {Cluster} c The cluster that the mouse moved out of.
     * @event
     */
    google.maps.event.trigger(mc, "mouseout", cClusterIcon.cluster_);
  });
};


/**
 * Removes the icon from the DOM.
 */
ClusterIcon.prototype.onRemove = function () {
  if (this.div_ && this.div_.parentNode) {
    this.hide();
    google.maps.event.removeListener(this.boundsChangedListener_);
    google.maps.event.clearInstanceListeners(this.div_);
    this.div_.parentNode.removeChild(this.div_);
    this.div_ = null;
  }
};


/**
 * Draws the icon.
 */
ClusterIcon.prototype.draw = function () {
  if (this.visible_) {
    var pos = this.getPosFromLatLng_(this.center_);
    this.div_.style.top = pos.y + "px";
    this.div_.style.left = pos.x + "px";
    this.div_.style.zIndex = google.maps.Marker.MAX_ZINDEX + 1; // Put above all unclustered markers
  }
};


/**
 * Hides the icon.
 */
ClusterIcon.prototype.hide = function () {
  if (this.div_) {
    this.div_.style.display = "none";
  }
  this.visible_ = false;
};


/**
 * Positions and shows the icon.
 *
 * @since 6.0.0
 */
ClusterIcon.prototype.show = function () {
  if (this.div_) {
    var img = "";
    // NOTE: values must be specified in px units
    var bp = this.backgroundPosition_.split(" ");
    var spriteH = parseInt(bp[0].replace(/^\s+|\s+$/g, ""), 10);
    var spriteV = parseInt(bp[1].replace(/^\s+|\s+$/g, ""), 10);
    var pos = this.getPosFromLatLng_(this.center_);
    this.div_.style.cssText = this.createCss(pos);
    img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; ";
    if (this.cluster_.getMarkerClusterer().enableRetinaIcons_) {
      img += "width: " + this.width_ + "px; height: " + this.height_ + "px;";
    } else {
      img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " +
        ((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);";
    }
    img += "'>";
    this.div_.innerHTML = "<div data-marker='' style='" +
      "position: absolute;" +
      "top: 0px;" +
      "left: 0px;" +
      "color: " + this.textColor_ + ";" +
      "font-size: " + this.textSize_ + "px;" +
      "font-family: " + this.fontFamily_ + ";" +
      "font-weight: " + this.fontWeight_ + ";" +
      "font-style: " + this.fontStyle_ + ";" +
      "text-decoration: " + this.textDecoration_ + ";" +
      "text-align: center;" +
      "width: 100%;" +
      "'>" + this.sums_.text + "</div>";
    if (typeof this.sums_.title === "undefined" || this.sums_.title === "") {
      this.div_.title = this.cluster_.getMarkerClusterer().getTitle();
    } else {
      this.div_.title = this.sums_.title;
    }
    this.div_.style.display = "";
  }
  this.visible_ = true;
};

/**
 * Positions and shows the icon.
 *
 * @since 6.0.0
 *
ClusterIcon.prototype.show = function () {
  if (this.div_) {
    var img = "";
    // NOTE: values must be specified in px units
    var bp = this.backgroundPosition_.split(" ");
    var spriteH = parseInt(bp[0].replace(/^\s+|\s+$/g, ""), 10);
    var spriteV = parseInt(bp[1].replace(/^\s+|\s+$/g, ""), 10);
    var pos = this.getPosFromLatLng_(this.center_);
    this.div_.style.cssText = this.createCss(pos);
    img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; ";
    if (this.cluster_.getMarkerClusterer().enableRetinaIcons_) {
      img += "width: " + this.width_ + "px; height: " + this.height_ + "px;";
    } else {
      img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " +
          ((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);";
    }
    img += "'>";
    this.div_.innerHTML = img + "<div style='" +
        "position: absolute;" +
        "top: " + this.anchorText_[0] + "px;" +
        "left: " + this.anchorText_[1] + "px;" +
        "color: " + this.textColor_ + ";" +
        "font-size: " + this.textSize_ + "px;" +
        "font-family: " + this.fontFamily_ + ";" +
        "font-weight: " + this.fontWeight_ + ";" +
        "font-style: " + this.fontStyle_ + ";" +
        "text-decoration: " + this.textDecoration_ + ";" +
        "text-align: center;" +
        "width: " + this.width_ + "px;" +
        "line-height:" + this.height_ + "px;" +
        "'>" + this.sums_.text + "</div>";
    if (typeof this.sums_.title === "undefined" || this.sums_.title === "") {
      this.div_.title = this.cluster_.getMarkerClusterer().getTitle();
    } else {
      this.div_.title = this.sums_.title;
    }
    this.div_.style.display = "";
  }
  this.visible_ = true;
};
*/

/**
 * Sets the icon styles to the appropriate element in the styles array.
 *
 * @param {ClusterIconInfo} sums The icon label text and styles index.
 */
ClusterIcon.prototype.useStyle = function (sums) {
  this.sums_ = sums;
  var index = Math.max(0, sums.index - 1);
  index = Math.min(this.styles_.length - 1, index);
  var style = this.styles_[index];
  this.url_ = style.url;
  this.height_ = style.height;
  this.width_ = style.width;
  this.anchorText_ = style.anchorText || [0, 0];
  this.anchorIcon_ = style.anchorIcon || [parseInt(this.height_ / 2, 10), parseInt(this.width_ / 2, 10)];
  this.textColor_ = style.textColor || "white";
  this.textSize_ = style.textSize || 11;
  this.textDecoration_ = style.textDecoration || "none";
  this.fontWeight_ = style.fontWeight || "bold";
  this.fontStyle_ = style.fontStyle || "normal";
  this.fontFamily_ = style.fontFamily || "Arial,sans-serif";
  this.backgroundPosition_ = style.backgroundPosition || "0 0";
};
//2023-07-18 : if (user_ip == '108.180.234.14') console.log('2516 - ');


/**
 * Sets the position at which to center the icon.
 *
 * @param {google.maps.LatLng} center The latlng to set as the center.
 */
ClusterIcon.prototype.setCenter = function (center) {
  this.center_ = center;
};


/**
 * Create the css text based on the position of the icon.
 *
 * @since 6.0.0
 * @param {google.maps.Point} pos The position.
 * @return {string} The css style text.
 */
ClusterIcon.prototype.createCss = function (pos) {
  var size = 15;
  if (this.cluster_.getMarkers().length < 10) { size = 15; }
  if (this.cluster_.getMarkers().length > 10 && this.cluster_.getMarkers().length < 100) { size = 22; }
  if (this.cluster_.getMarkers().length > 100 && this.cluster_.getMarkers().length < 1000) { size = 30; }
  if (this.cluster_.getMarkers().length > 1000) { size = 37; }

  var cl = primary_color;
  if (primary_color == '#ffffff') {
    cl = secondary_color
  }
  style = ['border-radius : 50%',
    'cursor        : pointer',
    'position      : absolute',
    'top           : ' + pos.y + 'px',
    'left          : ' + pos.x + 'px',
    'width         : ' + size * 2 + 'px',
    'height        : ' + size * 2 + 'px',
    'line-height   : ' + (size * 2 + 1) + 'px',
    'text-align    : center',
    'background-color: ' + cl,
    'color: #ffffff',
    'font-size:14px'
  ];
  return style.join(";") + ';';
};

/**
 * Creates the cssText style parameter based on the position of the icon.
 *
 * @param {google.maps.Point} pos The position of the icon.
 * @return {string} The CSS style text.
 *
ClusterIcon.prototype.createCss = function (pos) {
  var style = [];
  style.push("cursor: pointer;");
  style.push("position: absolute; top: " + pos.y + "px; left: " + pos.x + "px;");
  style.push("width: " + this.width_ + "px; height: " + this.height_ + "px;");
  style.push("-webkit-user-select: none;");
  style.push("-khtml-user-select: none;");
  style.push("-moz-user-select: none;");
  style.push("-o-user-select: none;");
  style.push("user-select: none;");
  return style.join("");
};
*/

/**
 * Returns the position at which to place the DIV depending on the latlng.
 *
 * @param {google.maps.LatLng} latlng The position in latlng.
 * @return {google.maps.Point} The position in pixels.
 */
ClusterIcon.prototype.getPosFromLatLng_ = function (latlng) {
  var pos = this.getProjection().fromLatLngToDivPixel(latlng);
  pos.x -= this.anchorIcon_[1];
  pos.y -= this.anchorIcon_[0];
  pos.x = parseInt(pos.x, 10);
  pos.y = parseInt(pos.y, 10);
  return pos;
};


/**
 * Creates a single cluster that manages a group of proximate markers.
 *  Used internally, do not call this constructor directly.
 * @constructor
 * @param {MarkerClusterer} mc The <code>MarkerClusterer</code> object with which this
 *  cluster is associated.
 */
function Cluster(mc) {
  this.markerClusterer_ = mc;
  this.map_ = mc.getMap();
  this.gridSize_ = mc.getGridSize();
  this.minClusterSize_ = mc.getMinimumClusterSize();
  this.averageCenter_ = mc.getAverageCenter();
  this.markers_ = [];
  this.center_ = null;
  this.bounds_ = null;
  this.clusterIcon_ = new ClusterIcon(this, mc.getStyles());
}


/**
 * Returns the number of markers managed by the cluster. You can call this from
 * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
 * for the <code>MarkerClusterer</code> object.
 *
 * @return {number} The number of markers in the cluster.
 */
Cluster.prototype.getSize = function () {
  return this.markers_.length;
};


/**
 * Returns the array of markers managed by the cluster. You can call this from
 * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
 * for the <code>MarkerClusterer</code> object.
 *
 * @return {Array} The array of markers in the cluster.
 */
Cluster.prototype.getMarkers = function () {
  return this.markers_;
};


/**
 * Returns the center of the cluster. You can call this from
 * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
 * for the <code>MarkerClusterer</code> object.
 *
 * @return {google.maps.LatLng} The center of the cluster.
 */
Cluster.prototype.getCenter = function () {
  return this.center_;
};


/**
 * Returns the map with which the cluster is associated.
 *
 * @return {google.maps.Map} The map.
 * @ignore
 */
Cluster.prototype.getMap = function () {
  return this.map_;
};


/**
 * Returns the <code>MarkerClusterer</code> object with which the cluster is associated.
 *
 * @return {MarkerClusterer} The associated marker clusterer.
 * @ignore
 */
Cluster.prototype.getMarkerClusterer = function () {
  return this.markerClusterer_;
};


/**
 * Returns the bounds of the cluster.
 *
 * @return {google.maps.LatLngBounds} the cluster bounds.
 * @ignore
 */
Cluster.prototype.getBounds = function () {
  var i;
  var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
  var markers = this.getMarkers();
  for (i = 0; i < markers.length; i++) {
    bounds.extend(markers[i].getPosition());
  }
  return bounds;
};


/**
 * Removes the cluster from the map.
 *
 * @ignore
 */
Cluster.prototype.remove = function () {
  this.clusterIcon_.setMap(null);
  this.markers_ = [];
  delete this.markers_;
};


/**
 * Adds a marker to the cluster.
 *
 * @param {google.maps.Marker} marker The marker to be added.
 * @return {boolean} True if the marker was added.
 * @ignore
 */
Cluster.prototype.addMarker = function (marker) {
  var i;
  var mCount;
  var mz;

  if (this.ischoolMarkerAlreadyAdded_(marker)) {
    return false;
  }

  if (!this.center_) {
    this.center_ = marker.getPosition();
    this.calculateBounds_();
  } else {
    if (this.averageCenter_) {
      var l = this.markers_.length + 1;
      var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l;
      var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l;
      this.center_ = new google.maps.LatLng(lat, lng);
      this.calculateBounds_();
    }
  }

  marker.isAdded = true;
  this.markers_.push(marker);

  mCount = this.markers_.length;
  mz = this.markerClusterer_.getMaxZoom();
  if (mz !== null && this.map_.getZoom() > mz) {
    // Zoomed in past max zoom, so show the marker.
    if (marker.getMap() !== this.map_) {
      marker.setMap(this.map_);
    }
  } else if (mCount < this.minClusterSize_) {
    // Min cluster size not reached so show the marker.
    if (marker.getMap() !== this.map_) {
      marker.setMap(this.map_);
    }
  } else if (mCount === this.minClusterSize_) {
    // Hide the markers that were showing.
    for (i = 0; i < mCount; i++) {
      this.markers_[i].setMap(null);
    }
  } else {
    marker.setMap(null);
  }

  this.updateIcon_();
  return true;
};


/**
 * Determines if a marker lies within the cluster's bounds.
 *
 * @param {google.maps.Marker} marker The marker to check.
 * @return {boolean} True if the marker lies in the bounds.
 * @ignore
 */
Cluster.prototype.ischoolMarkerInClusterBounds = function (marker) {
  return this.bounds_.contains(marker.getPosition());
};


/**
 * Calculates the extended bounds of the cluster with the grid.
 */
Cluster.prototype.calculateBounds_ = function () {
  var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
  this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds);
};


/**
 * Updates the cluster icon.
 */
Cluster.prototype.updateIcon_ = function () {
  var mCount = this.markers_.length;
  var mz = this.markerClusterer_.getMaxZoom();

  if (mz !== null && this.map_.getZoom() > mz) {
    this.clusterIcon_.hide();
    return;
  }

  if (mCount < this.minClusterSize_) {
    // Min cluster size not yet reached.
    this.clusterIcon_.hide();
    return;
  }

  var numStyles = this.markerClusterer_.getStyles().length;
  var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles);
  this.clusterIcon_.setCenter(this.center_);
  this.clusterIcon_.useStyle(sums);
  this.clusterIcon_.show();
};


/**
 * Determines if a marker has already been added to the cluster.
 *
 * @param {google.maps.Marker} marker The marker to check.
 * @return {boolean} True if the marker has already been added.
 */
Cluster.prototype.ischoolMarkerAlreadyAdded_ = function (marker) {
  var i;
  if (this.markers_.indexOf) {
    return this.markers_.indexOf(marker) !== -1;
  } else {
    for (i = 0; i < this.markers_.length; i++) {
      if (marker === this.markers_[i]) {
        return true;
      }
    }
  }
  return false;
};


/**
 * @name MarkerClustererOptions
 * @class This class represents the optional parameter passed to
 *  the {@link MarkerClusterer} constructor.
 * @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square.
 * @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or
 *  <code>null</code> if clustering is to be enabled at all zoom levels.
 * @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is
 *  clicked. You may want to set this to <code>false</code> if you have installed a handler
 *  for the <code>click</code> event and it deals with zooming on its own.
 * @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be
 *  the average position of all markers in the cluster. If set to <code>false</code>, the
 *  cluster marker is positioned at the location of the first marker added to the cluster.
 * @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster
 *  before the markers are hidden and a cluster marker appears.
 * @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You
 *  may want to set this to <code>true</code> to ensure that hidden markers are not included
 *  in the marker count that appears on a cluster marker (this count is the value of the
 *  <code>text</code> property of the result returned by the default <code>calculator</code>).
 *  If set to <code>true</code> and you change the visibility of a marker being clustered, be
 *  sure to also call <code>MarkerClusterer.repaint()</code>.
 * @property {string} [title=""] The tooltip to display when the mouse moves over a cluster
 *  marker. (Alternatively, you can use a custom <code>calculator</code> function to specify a
 *  different tooltip for each cluster marker.)
 * @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine
 *  the text to be displayed on a cluster marker and the index indicating which style to use
 *  for the cluster marker. The input parameters for the function are (1) the array of markers
 *  represented by a cluster marker and (2) the number of cluster icon styles. It returns a
 *  {@link ClusterIconInfo} object. The default <code>calculator</code> returns a
 *  <code>text</code> property which is the number of markers in the cluster and an
 *  <code>index</code> property which is one higher than the lowest integer such that
 *  <code>10^i</code> exceeds the number of markers in the cluster, or the size of the styles
 *  array, whichever is less. The <code>styles</code> array element used has an index of
 *  <code>index</code> minus 1. For example, the default <code>calculator</code> returns a
 *  <code>text</code> value of <code>"125"</code> and an <code>index</code> of <code>3</code>
 *  for a cluster icon representing 125 markers so the element used in the <code>styles</code>
 *  array is <code>2</code>. A <code>calculator</code> may also return a <code>title</code>
 *  property that contains the text of the tooltip to be used for the cluster marker. If
 *   <code>title</code> is not defined, the tooltip is set to the value of the <code>title</code>
 *   property for the MarkerClusterer.
 * @property {string} [clusterClass="cluster"] The name of the CSS class defining general styles
 *  for the cluster markers. Use this class to define CSS styles that are not set up by the code
 *  that processes the <code>styles</code> array.
 * @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles
 *  of the cluster markers to be used. The element to be used to style a given cluster marker
 *  is determined by the function defined by the <code>calculator</code> property.
 *  The default is an array of {@link ClusterIconStyle} elements whose properties are derived
 *  from the values for <code>imagePath</code>, <code>imageExtension</code>, and
 *  <code>imageSizes</code>.
 * @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that
 * have sizes that are some multiple (typically double) of their actual display size. Icons such
 * as these look better when viewed on high-resolution monitors such as Apple's Retina displays.
 * Note: if this property is <code>true</code>, sprites cannot be used as cluster icons.
 * @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the
 *  number of markers to be processed in a single batch when using a browser other than
 *  Internet Explorer (for Internet Explorer, use the batchSizeIE property instead).
 * @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is
 *  being used, markers are processed in several batches with a small delay inserted between
 *  each batch in an attempt to avoid Javascript timeout errors. Set this property to the
 *  number of markers to be processed in a single batch; select as high a number as you can
 *  without causing a timeout error in the browser. This number might need to be as low as 100
 *  if 15,000 markers are being managed, for example.
 * @property {string} [imagePath=MarkerClusterer.IMAGE_PATH]
 *  The full URL of the root name of the group of image files to use for cluster icons.
 *  The complete file name is of the form <code>imagePath</code>n.<code>imageExtension</code>
 *  where n is the image file number (1, 2, etc.).
 * @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION]
 *  The extension name for the cluster icon image files (e.g., <code>"png"</code> or
 *  <code>"jpg"</code>).
 * @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES]
 *  An array of numbers containing the widths of the group of
 *  <code>imagePath</code>n.<code>imageExtension</code> image files.
 *  (The images are assumed to be square.)
 */
/**
 * Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}.
 * @constructor
 * @extends google.maps.OverlayView
 * @param {google.maps.Map} map The Google map to attach to.
 * @param {Array.<google.maps.Marker>} [opt_markers] The markers to be added to the cluster.
 * @param {MarkerClustererOptions} [opt_options] The optional parameters.
 */
function MarkerClusterer(map, opt_markers, opt_options) {
  // MarkerClusterer implements google.maps.OverlayView interface. We use the
  // extend function to extend MarkerClusterer with google.maps.OverlayView
  // because it might not always be available when the code is defined so we
  // look for it at the last possible moment. If it doesn't exist now then
  // there is no point going ahead :)
  this.extend(MarkerClusterer, google.maps.OverlayView);

  opt_markers = opt_markers || [];
  opt_options = opt_options || {};

  this.markers_ = [];
  this.clusters_ = [];
  this.listeners_ = [];
  this.activeMap_ = null;
  this.ready_ = false;

  this.gridSize_ = opt_options.gridSize || 60;
  this.minClusterSize_ = opt_options.minimumClusterSize || 2;
  this.maxZoom_ = opt_options.maxZoom || null;
  this.styles_ = opt_options.styles || [];
  this.title_ = opt_options.title || "";
  this.zoomOnClick_ = true;
  if (opt_options.zoomOnClick !== undefined) {
    this.zoomOnClick_ = opt_options.zoomOnClick;
  }
  this.averageCenter_ = false;
  if (opt_options.averageCenter !== undefined) {
    this.averageCenter_ = opt_options.averageCenter;
  }
  this.ignoreHidden_ = false;
  if (opt_options.ignoreHidden !== undefined) {
    this.ignoreHidden_ = opt_options.ignoreHidden;
  }
  this.enableRetinaIcons_ = false;
  if (opt_options.enableRetinaIcons !== undefined) {
    this.enableRetinaIcons_ = opt_options.enableRetinaIcons;
  }
  this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH;
  this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION;
  this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES;
  this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR;
  this.batchSize_ = opt_options.batchSize || MarkerClusterer.BATCH_SIZE;
  this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE;
  this.clusterClass_ = opt_options.clusterClass || "cluster";

  if (navigator.userAgent.toLowerCase().indexOf("msie") !== -1) {
    // Try to avoid IE timeout when processing a huge number of markers:
    this.batchSize_ = this.batchSizeIE_;
  }

  this.setupStyles_();

  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('2939            --------------------------------------------');

  this.addMarkers(opt_markers, true);
  this.setMap(map); // Note: this causes onAdd to be called
}


/**
 * Implementation of the onAdd interface method.
 * @ignore
 */
MarkerClusterer.prototype.onAdd = function () {
  var cMarkerClusterer = this;

  this.activeMap_ = this.getMap();
  this.ready_ = true;

  this.repaint();

  this.prevZoom_ = this.getMap().getZoom();

  // Add the map event listeners
  this.listeners_ = [
    google.maps.event.addListener(this.getMap(), "zoom_changed", function () {
      // Fix for bug #407
      // Determines map type and prevents illegal zoom levels
      var zoom = this.getMap().getZoom();
      var minZoom = this.getMap().minZoom || 0;
      var maxZoom = Math.min(this.getMap().maxZoom || 100,
        this.getMap().mapTypes[this.getMap().getMapTypeId()].maxZoom);
      zoom = Math.min(Math.max(zoom, minZoom), maxZoom);

      if (this.prevZoom_ != zoom) {
        this.prevZoom_ = zoom;
        this.resetViewport_(false);
      }
    }.bind(this)),
    google.maps.event.addListener(this.getMap(), "idle", function () {
      cMarkerClusterer.redraw_();
    })
  ];
};


/**
 * Implementation of the onRemove interface method.
 * Removes map event listeners and all cluster icons from the DOM.
 * All managed markers are also put back on the map.
 * @ignore
 */
MarkerClusterer.prototype.onRemove = function () {
  var i;

  // Put all the managed markers back on the map:
  for (i = 0; i < this.markers_.length; i++) {
    if (this.markers_[i].getMap() !== this.activeMap_) {
      this.markers_[i].setMap(this.activeMap_);
    }
  }

  // Remove all clusters:
  for (i = 0; i < this.clusters_.length; i++) {
    this.clusters_[i].remove();
  }
  this.clusters_ = [];

  // Remove map event listeners:
  for (i = 0; i < this.listeners_.length; i++) {
    google.maps.event.removeListener(this.listeners_[i]);
  }
  this.listeners_ = [];

  this.activeMap_ = null;
  this.ready_ = false;
};


/**
 * Implementation of the draw interface method.
 * @ignore
 */
MarkerClusterer.prototype.draw = function () { };


/**
 * Sets up the styles object.
 */
MarkerClusterer.prototype.setupStyles_ = function () {
  var i, size;
  if (this.styles_.length > 0) {
    return;
  }

  for (i = 0; i < this.imageSizes_.length; i++) {
    size = this.imageSizes_[i];
    this.styles_.push({
      url: this.imagePath_ + (i + 1) + "." + this.imageExtension_,
      height: size,
      width: size
    });
  }
};


/**
 *  Fits the map to the bounds of the markers managed by the clusterer.
 */
MarkerClusterer.prototype.fitMapToMarkers = function () {
  var i;
  var markers = this.getMarkers();
  var bounds = new google.maps.LatLngBounds();
  for (i = 0; i < markers.length; i++) {
    // March 3, 2018: Bug fix -- honor the ignoreHidden property
    if (markers[i].getVisible() || !this.getIgnoreHidden()) {
      bounds.extend(markers[i].getPosition());
    }
  }

  this.getMap().fitBounds(bounds);
};


/**
 * Returns the value of the <code>gridSize</code> property.
 *
 * @return {number} The grid size.
 */
MarkerClusterer.prototype.getGridSize = function () {
  return this.gridSize_;
};


/**
 * Sets the value of the <code>gridSize</code> property.
 *
 * @param {number} gridSize The grid size.
 */
MarkerClusterer.prototype.setGridSize = function (gridSize) {
  this.gridSize_ = gridSize;
};


/**
 * Returns the value of the <code>minimumClusterSize</code> property.
 *
 * @return {number} The minimum cluster size.
 */
MarkerClusterer.prototype.getMinimumClusterSize = function () {
  return this.minClusterSize_;
};

/**
 * Sets the value of the <code>minimumClusterSize</code> property.
 *
 * @param {number} minimumClusterSize The minimum cluster size.
 */
MarkerClusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) {
  this.minClusterSize_ = minimumClusterSize;
};


/**
 *  Returns the value of the <code>maxZoom</code> property.
 *
 *  @return {number} The maximum zoom level.
 */
MarkerClusterer.prototype.getMaxZoom = function () {
  return this.maxZoom_;
};


/**
 *  Sets the value of the <code>maxZoom</code> property.
 *
 *  @param {number} maxZoom The maximum zoom level.
 */
MarkerClusterer.prototype.setMaxZoom = function (maxZoom) {
  this.maxZoom_ = maxZoom;
};


/**
 *  Returns the value of the <code>styles</code> property.
 *
 *  @return {Array} The array of styles defining the cluster markers to be used.
 */
MarkerClusterer.prototype.getStyles = function () {
  return this.styles_;
};


/**
 *  Sets the value of the <code>styles</code> property.
 *
 *  @param {Array.<ClusterIconStyle>} styles The array of styles to use.
 */
MarkerClusterer.prototype.setStyles = function (styles) {
  this.styles_ = styles;
};


/**
 * Returns the value of the <code>title</code> property.
 *
 * @return {string} The content of the title text.
 */
MarkerClusterer.prototype.getTitle = function () {
  return this.title_;
};


/**
 *  Sets the value of the <code>title</code> property.
 *
 *  @param {string} title The value of the title property.
 */
MarkerClusterer.prototype.setTitle = function (title) {
  this.title_ = title;
};


/**
 * Returns the value of the <code>zoomOnClick</code> property.
 *
 * @return {boolean} True if zoomOnClick property is set.
 */
MarkerClusterer.prototype.getZoomOnClick = function () {
  return this.zoomOnClick_;
};


/**
 *  Sets the value of the <code>zoomOnClick</code> property.
 *
 *  @param {boolean} zoomOnClick The value of the zoomOnClick property.
 */
MarkerClusterer.prototype.setZoomOnClick = function (zoomOnClick) {
  this.zoomOnClick_ = zoomOnClick;
};


/**
 * Returns the value of the <code>averageCenter</code> property.
 *
 * @return {boolean} True if averageCenter property is set.
 */
MarkerClusterer.prototype.getAverageCenter = function () {
  return this.averageCenter_;
};


/**
 *  Sets the value of the <code>averageCenter</code> property.
 *
 *  @param {boolean} averageCenter The value of the averageCenter property.
 */
MarkerClusterer.prototype.setAverageCenter = function (averageCenter) {
  this.averageCenter_ = averageCenter;
};


/**
 * Returns the value of the <code>ignoreHidden</code> property.
 *
 * @return {boolean} True if ignoreHidden property is set.
 */
MarkerClusterer.prototype.getIgnoreHidden = function () {
  return this.ignoreHidden_;
};


/**
 *  Sets the value of the <code>ignoreHidden</code> property.
 *
 *  @param {boolean} ignoreHidden The value of the ignoreHidden property.
 */
MarkerClusterer.prototype.setIgnoreHidden = function (ignoreHidden) {
  this.ignoreHidden_ = ignoreHidden;
};


/**
 * Returns the value of the <code>enableRetinaIcons</code> property.
 *
 * @return {boolean} True if enableRetinaIcons property is set.
 */
MarkerClusterer.prototype.getEnableRetinaIcons = function () {
  return this.enableRetinaIcons_;
};


/**
 *  Sets the value of the <code>enableRetinaIcons</code> property.
 *
 *  @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property.
 */
MarkerClusterer.prototype.setEnableRetinaIcons = function (enableRetinaIcons) {
  this.enableRetinaIcons_ = enableRetinaIcons;
};


/**
 * Returns the value of the <code>imageExtension</code> property.
 *
 * @return {string} The value of the imageExtension property.
 */
MarkerClusterer.prototype.getImageExtension = function () {
  return this.imageExtension_;
};


/**
 *  Sets the value of the <code>imageExtension</code> property.
 *
 *  @param {string} imageExtension The value of the imageExtension property.
 */
MarkerClusterer.prototype.setImageExtension = function (imageExtension) {
  this.imageExtension_ = imageExtension;
};


/**
 * Returns the value of the <code>imagePath</code> property.
 *
 * @return {string} The value of the imagePath property.
 */
MarkerClusterer.prototype.getImagePath = function () {
  return this.imagePath_;
};


/**
 *  Sets the value of the <code>imagePath</code> property.
 *
 *  @param {string} imagePath The value of the imagePath property.
 */
MarkerClusterer.prototype.setImagePath = function (imagePath) {
  this.imagePath_ = imagePath;
};


/**
 * Returns the value of the <code>imageSizes</code> property.
 *
 * @return {Array} The value of the imageSizes property.
 */
MarkerClusterer.prototype.getImageSizes = function () {
  return this.imageSizes_;
};


/**
 *  Sets the value of the <code>imageSizes</code> property.
 *
 *  @param {Array} imageSizes The value of the imageSizes property.
 */
MarkerClusterer.prototype.setImageSizes = function (imageSizes) {
  this.imageSizes_ = imageSizes;
};


/**
 * Returns the value of the <code>calculator</code> property.
 *
 * @return {function} the value of the calculator property.
 */
MarkerClusterer.prototype.getCalculator = function () {
  return this.calculator_;
};


/**
 * Sets the value of the <code>calculator</code> property.
 *
 * @param {function(Array.<google.maps.Marker>, number)} calculator The value
 *  of the calculator property.
 */
MarkerClusterer.prototype.setCalculator = function (calculator) {
  this.calculator_ = calculator;
};


/**
 * Returns the value of the <code>batchSizeIE</code> property.
 *
 * @return {number} the value of the batchSizeIE property.
 */
MarkerClusterer.prototype.getBatchSizeIE = function () {
  return this.batchSizeIE_;
};


/**
 * Sets the value of the <code>batchSizeIE</code> property.
 *
 *  @param {number} batchSizeIE The value of the batchSizeIE property.
 */
MarkerClusterer.prototype.setBatchSizeIE = function (batchSizeIE) {
  this.batchSizeIE_ = batchSizeIE;
};


/**
 * Returns the value of the <code>clusterClass</code> property.
 *
 * @return {string} the value of the clusterClass property.
 */
MarkerClusterer.prototype.getClusterClass = function () {
  return this.clusterClass_;
};


/**
 * Sets the value of the <code>clusterClass</code> property.
 *
 *  @param {string} clusterClass The value of the clusterClass property.
 */
MarkerClusterer.prototype.setClusterClass = function (clusterClass) {
  this.clusterClass_ = clusterClass;
};


/**
 *  Returns the array of markers managed by the clusterer.
 *
 *  @return {Array} The array of markers managed by the clusterer.
 */
MarkerClusterer.prototype.getMarkers = function () {
  return this.markers_;
};


/**
 *  Returns the number of markers managed by the clusterer.
 *
 *  @return {number} The number of markers.
 */
MarkerClusterer.prototype.getTotalMarkers = function () {
  return this.markers_.length;
};


/**
 * Returns the current array of clusters formed by the clusterer.
 *
 * @return {Array} The array of clusters formed by the clusterer.
 */
MarkerClusterer.prototype.getClusters = function () {
  return this.clusters_;
};


/**
 * Returns the number of clusters formed by the clusterer.
 *
 * @return {number} The number of clusters formed by the clusterer.
 */
MarkerClusterer.prototype.getTotalClusters = function () {
  return this.clusters_.length;
};


/**
 * Adds a marker to the clusterer. The clusters are redrawn unless
 *  <code>opt_nodraw</code> is set to <code>true</code>.
 *
 * @param {google.maps.Marker} marker The marker to add.
 * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
 */
MarkerClusterer.prototype.addMarker = function (marker, opt_nodraw) {
  this.pushMarkerTo_(marker);
  if (!opt_nodraw) {
    this.redraw_();
  }
};


/**
 * Adds an array of markers to the clusterer. The clusters are redrawn unless
 *  <code>opt_nodraw</code> is set to <code>true</code>.
 *
 * @param {Array.<google.maps.Marker>} markers The markers to add.
 * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
 */
MarkerClusterer.prototype.addMarkers = function (markers, opt_nodraw) {
  var key;
  for (key in markers) {
    if (markers.hasOwnProperty(key)) {
      this.pushMarkerTo_(markers[key]);
    }
  }
  if (!opt_nodraw) {
    this.redraw_();
  }
};


/**
 * Pushes a marker to the clusterer.
 *
 * @param {google.maps.Marker} marker The marker to add.
 */
MarkerClusterer.prototype.pushMarkerTo_ = function (marker) {
  // If the marker is draggable add a listener so we can update the clusters on the dragend:
  if (marker.getDraggable()) {
    var cMarkerClusterer = this;
    google.maps.event.addListener(marker, "dragend", function () {
      if (cMarkerClusterer.ready_) {
        this.isAdded = false;
        cMarkerClusterer.repaint();
      }
    });
  }
  marker.isAdded = false;
  this.markers_.push(marker);
};


/**
 * Removes a marker from the cluster.  The clusters are redrawn unless
 *  <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if the
 *  marker was removed from the clusterer.
 *
 * @param {google.maps.Marker} marker The marker to remove.
 * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
 * @return {boolean} True if the marker was removed from the clusterer.
 */
MarkerClusterer.prototype.removeMarker = function (marker, opt_nodraw) {
  var removed = this.removeMarker_(marker);

  if (!opt_nodraw && removed) {
    this.repaint();
  }

  return removed;
};


/**
 * Removes an array of markers from the cluster. The clusters are redrawn unless
 *  <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if markers
 *  were removed from the clusterer.
 *
 * @param {Array.<google.maps.Marker>} markers The markers to remove.
 * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
 * @return {boolean} True if markers were removed from the clusterer.
 */
MarkerClusterer.prototype.removeMarkers = function (markers, opt_nodraw) {
  var i, r;
  var removed = false;

  for (i = 0; i < markers.length; i++) {
    r = this.removeMarker_(markers[i]);
    removed = removed || r;
  }

  if (!opt_nodraw && removed) {
    this.repaint();
  }

  return removed;
};


/**
 * Removes a marker and returns true if removed, false if not.
 *
 * @param {google.maps.Marker} marker The marker to remove
 * @return {boolean} Whether the marker was removed or not
 */
MarkerClusterer.prototype.removeMarker_ = function (marker) {
  var i;
  var index = -1;
  if (this.markers_.indexOf) {
    index = this.markers_.indexOf(marker);
  } else {
    for (i = 0; i < this.markers_.length; i++) {
      if (marker === this.markers_[i]) {
        index = i;
        break;
      }
    }
  }

  if (index === -1) {
    // Marker is not in our list of markers, so do nothing:
    return false;
  }

  marker.setMap(null);
  this.markers_.splice(index, 1); // Remove the marker from the list of managed markers
  return true;
};


/**
 * Removes all clusters and markers from the map and also removes all markers
 *  managed by the clusterer.
 */
MarkerClusterer.prototype.clearMarkers = function () {
  this.resetViewport_(true);
  this.markers_ = [];
};


/**
 * Recalculates and redraws all the marker clusters from scratch.
 *  Call this after changing any properties.
 */
MarkerClusterer.prototype.repaint = function () {
  var oldClusters = this.clusters_.slice();
  this.clusters_ = [];
  this.resetViewport_(false);
  this.redraw_();

  // Remove the old clusters.
  // Do it in a timeout to prevent blinking effect.
  setTimeout(function () {
    var i;
    for (i = 0; i < oldClusters.length; i++) {
      oldClusters[i].remove();
    }
  }, 0);
};


/**
 * Returns the current bounds extended by the grid size.
 *
 * @param {google.maps.LatLngBounds} bounds The bounds to extend.
 * @return {google.maps.LatLngBounds} The extended bounds.
 * @ignore
 */
MarkerClusterer.prototype.getExtendedBounds = function (bounds) {
  var projection = this.getProjection();

  // Turn the bounds into latlng.
  var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),
    bounds.getNorthEast().lng());
  var bl = new google.maps.LatLng(bounds.getSouthWest().lat(),
    bounds.getSouthWest().lng());

  // Convert the points to pixels and the extend out by the grid size.
  var trPix = projection.fromLatLngToDivPixel(tr);
  trPix.x += this.gridSize_;
  trPix.y -= this.gridSize_;

  var blPix = projection.fromLatLngToDivPixel(bl);
  blPix.x -= this.gridSize_;
  blPix.y += this.gridSize_;

  // Convert the pixel points back to LatLng
  var ne = projection.fromDivPixelToLatLng(trPix);
  var sw = projection.fromDivPixelToLatLng(blPix);

  // Extend the bounds to contain the new bounds.
  bounds.extend(ne);
  bounds.extend(sw);

  return bounds;
};


/**
 * Redraws all the clusters.
 */
MarkerClusterer.prototype.redraw_ = function () {
  this.createClusters_(0);
};


/**
 * Removes all clusters from the map. The markers are also removed from the map
 *  if <code>opt_hide</code> is set to <code>true</code>.
 *
 * @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers
 *  from the map.
 */
MarkerClusterer.prototype.resetViewport_ = function (opt_hide) {
  var i, marker;
  // Remove all the clusters
  for (i = 0; i < this.clusters_.length; i++) {
    this.clusters_[i].remove();
  }
  this.clusters_ = [];

  // Reset the markers to not be added and to be removed from the map.
  for (i = 0; i < this.markers_.length; i++) {
    marker = this.markers_[i];
    marker.isAdded = false;
    if (opt_hide) {
      marker.setMap(null);
    }
  }
};


/**
 * Calculates the distance between two latlng locations in km.
 *
 * @param {google.maps.LatLng} p1 The first lat lng point.
 * @param {google.maps.LatLng} p2 The second lat lng point.
 * @return {number} The distance between the two points in km.
 * @see http://www.movable-type.co.uk/scripts/latlong.html
*/
MarkerClusterer.prototype.distanceBetweenPoints_ = function (p1, p2) {
  var R = 6371; // Radius of the Earth in km
  var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
  var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;
  return d;
};


/**
 * Determines if a marker is contained in a bounds.
 *
 * @param {google.maps.Marker} marker The marker to check.
 * @param {google.maps.LatLngBounds} bounds The bounds to check against.
 * @return {boolean} True if the marker is in the bounds.
 */
MarkerClusterer.prototype.ischoolMarkerInBounds_ = function (marker, bounds) {
  return bounds.contains(marker.getPosition());
};


/**
 * Adds a marker to a cluster, or creates a new cluster.
 *
 * @param {google.maps.Marker} marker The marker to add.
 */
MarkerClusterer.prototype.addToClosestCluster_ = function (marker) {
  var i, d, cluster, center;
  var distance = 40000; // Some large number
  var clusterToAddTo = null;
  for (i = 0; i < this.clusters_.length; i++) {
    cluster = this.clusters_[i];
    center = cluster.getCenter();
    if (center) {
      d = this.distanceBetweenPoints_(center, marker.getPosition());
      if (d < distance) {
        distance = d;
        clusterToAddTo = cluster;
      }
    }
  }

  if (clusterToAddTo && clusterToAddTo.ischoolMarkerInClusterBounds(marker)) {
    clusterToAddTo.addMarker(marker);
  } else {
    cluster = new Cluster(this);
    cluster.addMarker(marker);
    this.clusters_.push(cluster);
  }
};


/**
 * Creates the clusters. This is done in batches to avoid timeout errors
 *  in some browsers when there is a huge number of markers.
 *
 * @param {number} iFirst The index of the first marker in the batch of
 *  markers to be added to clusters.
 */
MarkerClusterer.prototype.createClusters_ = function (iFirst) {
  var i, marker;
  var mapBounds;
  var cMarkerClusterer = this;
  if (!this.ready_) {
    return;
  }

  // Cancel previous batch processing if we're working on the first batch:
  if (iFirst === 0) {
    /**
     * This event is fired when the <code>MarkerClusterer</code> begins
     *  clustering markers.
     * @name MarkerClusterer#clusteringbegin
     * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
     * @event
     */
    google.maps.event.trigger(this, "clusteringbegin", this);

    if (typeof this.timerRefStatic !== "undefined") {
      clearTimeout(this.timerRefStatic);
      delete this.timerRefStatic;
    }
  }

  // Get our current map view bounds.
  // Create a new bounds object so we don't affect the map.
  //
  // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:
  if (this.getMap().getZoom() > 3) {
    mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),
      this.getMap().getBounds().getNorthEast());
  } else {
    mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));
  }
  var bounds = this.getExtendedBounds(mapBounds);

  var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length);

  for (i = iFirst; i < iLast; i++) {
    marker = this.markers_[i];
    if (!marker.isAdded && this.ischoolMarkerInBounds_(marker, bounds)) {
      if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) {
        this.addToClosestCluster_(marker);
      }
    }
  }

  if (iLast < this.markers_.length) {
    this.timerRefStatic = setTimeout(function () {
      cMarkerClusterer.createClusters_(iLast);
    }, 0);
  } else {
    delete this.timerRefStatic;

    /**
     * This event is fired when the <code>MarkerClusterer</code> stops
     *  clustering markers.
     * @name MarkerClusterer#clusteringend
     * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
     * @event
     */
    google.maps.event.trigger(this, "clusteringend", this);
  }
};


/**
 * Extends an object's prototype by another's.
 *
 * @param {Object} obj1 The object to be extended.
 * @param {Object} obj2 The object to extend with.
 * @return {Object} The new extended object.
 * @ignore
 */
MarkerClusterer.prototype.extend = function (obj1, obj2) {
  return (function (object) {
    var property;
    for (property in object.prototype) {
      this.prototype[property] = object.prototype[property];
    }
    return this;
  }).apply(obj1, [obj2]);
};


/**
 * The default function for determining the label text and style
 * for a cluster icon.
 *
 * @param {Array.<google.maps.Marker>} markers The array of markers represented by the cluster.
 * @param {number} numStyles The number of marker styles available.
 * @return {ClusterIconInfo} The information resource for the cluster.
 * @constant
 * @ignore
 */
MarkerClusterer.CALCULATOR = function (markers, numStyles) {
  var index = 0;
  var title = "";
  var count = markers.length.toString();

  var dv = count;
  while (dv !== 0) {
    dv = parseInt(dv / 10, 10);
    index++;
  }

  index = Math.min(index, numStyles);
  return {
    text: count,
    index: index,
    title: title
  };
};


/**
 * The number of markers to process in one batch.
 *
 * @type {number}
 * @constant
 */
MarkerClusterer.BATCH_SIZE = 2000;


/**
 * The number of markers to process in one batch (IE only).
 *
 * @type {number}
 * @constant
 */
MarkerClusterer.BATCH_SIZE_IE = 500;


/**
 * The default root name for the marker cluster images.
 *
 * @type {string}
 * @constant
 */
MarkerClusterer.IMAGE_PATH = "../images/m";


/**
 * The default extension name for the marker cluster images.
 *
 * @type {string}
 * @constant
 */
MarkerClusterer.IMAGE_EXTENSION = "png";


/**
 * The default array of sizes for the marker cluster images.
 *
 * @type {Array.<number>}
 * @constant
 */
MarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90];

if (typeof module == 'object') {
  module.exports = MarkerClusterer;
}

debug = false;

var radiusCenter = null,
  mapInfoPopupDiv = null,
  mapCenter = null,
  markerClusterer = null,
  polygon_line = null,
  partner_id = null,
  infowindow = null,
  listing_ids = '',
  offset_down = 125, // in pixels
  mapHeight = 920, // in pixels
  percentDown = offset_down * 100 / mapHeight,  // in percent
  gettingLocationFromValue = false;
var lat_offset_down = 0,
  minZoomLevel = 2, //== 64km
  minDefaultZoomLevel = 14,
  latDiff = 0,
  lngDiff = 0,
  radius_meters = 0,
  inner = {},
  outer = {},
  multiplier = 1;

/*if(units != '') {
      get_user_loc(function(unit){
          units = unit;
      });
  }*/

if (units != undefined && units == 'mi') {
  multiplier = 0.621371;
}

var listingMarkers = [],
  schoolMarker = null,
  radiusDistanceMarker = [],
  kmDisplayed = ["512 km", "256 km", "128 km", "64 km", "32 km", "16 km", "8 km", "4 km", "2 km", "1 km", "500 m", "250 m", "125 m", "64 m", "32 m", "16 m", "8 m", "4 m"],
  miDisplayed = ["512 mi", "256 mi", "128 mi", "64 mi", "32 mi", "16 mi", "8 mi", "4 mi", "2 mi", "1 mi", "880 yds", "440 yds", "220 yds", "110 yds", "55 yds", "28 yds", "42 ft", "21 ft"],
  displayArrPos = 18,
  faded_markers = [],
  full_markers = [],
  radiusLine = [],
  full_markers_count = 0,
  line = [],
  distanceOverlay,
  minBed,
  maxBed,

  // PROPERTY VARIABLES
  prop_type = {
    20: ['Apartment Bldg / Complex'],
    21: ['Condo'],
    35: ['Dormitory'],
    37: ['Executive'],
    7523: ['Frat / Sorority'],
    28: ['Furnished'],
    1192: ['Furnished'],
    24: ['House'],
    25: ['Mobile Home'],
    23: ['Multiplex'],
    32: ['Other'],
    26: ['Room & Board'],
    31: ['Room in Home'],
    27: ['Roommate'],
    1191: ['Short Term'],
    29: ['Suite'],
    30: ['Townhouse'],
    1130: ['Townhouse']
  },
  propTypes = [20, 21, 35, 37, 7523, 28, 1192, 24, 25, 23, 32, 26, 31, 27, 1191, 29, 30, 1130],
  propTypesSelected = [20, 21, 35, 37, 7523, 28, 1192, 24, 25, 23, 32, 26, 31, 27, 1191, 29, 30, 1130],
  propTypeHTML = '',

  // NEIGHBOURHOOD VARIABLES
  //neighbours = [],
  //neighboursSelected = [],
  //neighboursHTML = '',

  // PARTNERS VARIABLES
  //partners = [],
  //partnersSelected = [],
  //partnersHTML = '',

  order_listings = '',
  comma = '';
var rtime = new Date(1, 1, 2000, 12, 0, 0),
  timeout = true,
  delta = 500;

/////////////////////////////////////////////////////////
//
//  Initialize
//
/////////////////////////////////////////////////////////
function initialize() {
  // Create the map
  ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('XXinitialize xxx');
  ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('initialize: done');

  if (typeof map_center_lat != 'undefined' && typeof map_center_lng != 'undefined')
    mapCenter = new google.maps.LatLng(map_center_lat, map_center_lng);
  else
    mapCenter = new google.maps.LatLng(user_lat, user_long);

    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('4004 - mapCenter - ', mapCenter);

    radiusCenter = mapCenter;

  if (typeof polygon_is_active == 'undefined')
    polygon_is_active = false;

  geocoder = new google.maps.Geocoder();
  infowindow = new google.maps.InfoWindow();

  var is_internetExplorer11 = navigator.userAgent.toLowerCase().indexOf('trident') > -1;
  var marker_url = (is_internetExplorer11) ? 'img/cd-icon-location.png' : 'img/cd-icon-location.svg';

  var main_color = '#2d313f',
    saturation_value = -20,
    brightness_value = 5;

  var style = [
    {
      //set saturation for the labels on the map
      elementType: "labels",
      stylers: [
        { saturation: saturation_value }
      ]
    },
    {	//poi stands for point of interest - don't show these lables on the map
      featureType: "poi",
      elementType: "labels",
      stylers: [
        { visibility: "off" }
      ]
    },
    {
      //don't show highways lables on the map
      featureType: 'road.highway',
      elementType: 'labels',
      stylers: [
        { visibility: "off" }
      ]
    },
    {
      //don't show local road lables on the map
      featureType: "road.local",
      elementType: "labels.icon",
      stylers: [
        { visibility: "off" }
      ]
    },
    {
      //don't show arterial road lables on the map
      featureType: "road.arterial",
      elementType: "labels.icon",
      stylers: [
        { visibility: "off" }
      ]
    },
    {
      //don't show road lables on the map
      featureType: "road",
      elementType: "geometry.stroke",
      stylers: [
        { visibility: "off" }
      ]
    },
    //style different elements on the map
    {
      featureType: "transit",
      elementType: "geometry.fill",
      stylers: [
        { hue: main_color },
        { visibility: "on" },
        { lightness: brightness_value },
        { saturation: saturation_value }
      ]
    },
    {
      featureType: "poi",
      elementType: "geometry.fill",
      stylers: [
        { hue: main_color },
        { visibility: "on" },
        { lightness: brightness_value },
        { saturation: saturation_value }
      ]
    },
    {
      featureType: "poi.government",
      elementType: "geometry.fill",
      stylers: [
        { hue: main_color },
        { visibility: "on" },
        { lightness: brightness_value },
        { saturation: saturation_value }
      ]
    },
    {
      featureType: "poi.attraction",
      elementType: "geometry.fill",
      stylers: [
        { hue: main_color },
        { visibility: "on" },
        { lightness: brightness_value },
        { saturation: saturation_value }
      ]
    },
    {
      featureType: "poi.business",
      elementType: "geometry.fill",
      stylers: [
        { hue: main_color },
        { visibility: "on" },
        { lightness: brightness_value },
        { saturation: saturation_value }
      ]
    },
    {
      featureType: "transit",
      elementType: "geometry.fill",
      stylers: [
        { hue: main_color },
        { visibility: "on" },
        { lightness: brightness_value },
        { saturation: saturation_value }
      ]
    },
    {
      featureType: "transit.station",
      elementType: "geometry.fill",
      stylers: [
        { hue: main_color },
        { visibility: "on" },
        { lightness: brightness_value },
        { saturation: saturation_value }
      ]
    },
    {
      featureType: "landscape",
      stylers: [
        { hue: main_color },
        { visibility: "on" },
        { lightness: brightness_value },
        { saturation: saturation_value }
      ]

    },
    {
      featureType: "road",
      elementType: "geometry.fill",
      stylers: [
        { hue: main_color },
        { visibility: "on" },
        { lightness: brightness_value },
        { saturation: saturation_value }
      ]
    },
    {
      featureType: "road.highway",
      elementType: "geometry.fill",
      stylers: [
        { hue: main_color },
        { visibility: "on" },
        { lightness: brightness_value },
        { saturation: saturation_value }
      ]
    },
    {
      featureType: "water",
      elementType: "geometry",
      stylers: [
        { hue: main_color },
        { visibility: "on" },
        { lightness: brightness_value },
        { saturation: saturation_value }
      ]
    }
  ];

  var zoomLevel = google_map_zoom_level - 1;

  var mapOptions = {
    zoom: zoomLevel,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: mapCenter,
    panControl: false,
    panControlOptions: {
      position: google.maps.ControlPosition.RIGHT_BOTTOM
    },
    scaleControl: false,
    streetViewControl: false,
    mapTypeControl: false,
    scrollwheel: false,
    rotateControl: false,
    overviewMapControl: false,
    // styles: style,
    zoomControl: false,
    zoomControlOptions:
    {
      style: google.maps.ZoomControlStyle.LARGE,
      position: google.maps.ControlPosition.RIGHT_CENTER
    }
  };

  // make it global by 'map' not 'var map'
  map = new google.maps.Map(map_canvas, mapOptions);

  //add custom buttons for the zoom-in/zoom-out on the map
  function CustomZoomControl(controlDiv, map) {
    //grap the zoom elements from the DOM and insert them in the map
    var controlUIzoomIn = document.getElementById('mapZoomIn'),
      controlUIzoomOut = document.getElementById('mapZoomOut');
    ////2023-07-18 : if (user_ip == '108.180.234.14') console.log(controlUIzoomIn, controlUIzoomOut);
    if (controlUIzoomOut != null && controlUIzoomIn != null) {
      controlDiv.appendChild(controlUIzoomIn);
      controlDiv.appendChild(controlUIzoomOut);

      // Setup the click event listeners and zoom-in or out according to the clicked element
      google.maps.event.addDomListener(controlUIzoomIn, 'click', function () {
        map.setZoom(map.getZoom() + 1)
      });
      google.maps.event.addDomListener(controlUIzoomOut, 'click', function () {
        map.setZoom(map.getZoom() - 1)
      });
    }

  }

  var zoomControlDiv = document.createElement('div');
  var zoomControl = new CustomZoomControl(zoomControlDiv, map);

  //insert the zoom div on the top left of the map
  if (!isMobile()) {
    map.controls[google.maps.ControlPosition.LEFT_TOP].push(zoomControlDiv);
  }

  // if Polygon map
  if (polygon_is_active && polygon_coordinates) {
    ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('polygon_is_active', polygon_coordinates);
    // TODO: Change to pull from site settings.
    // Define the LatLng coordinates for the polygon's path.
    // Construct the polygon.
    var polygon_path = [];
    for (var i = 0; i < polygon_coordinates.length; i++) {
      polygon_path.push(new google.maps.LatLng(polygon_coordinates[i].lat, polygon_coordinates[i].lng));
    }
    polygon_line = new google.maps.Polygon({
      paths: polygon_path,
      strokeColor: '#FF0000',
      strokeOpacity: 1.0,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.1,
      map: map
    });

    var polygon_bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < polygon_line.getPath().length; i++) {
      var point = new google.maps.LatLng(polygon_path[i].lat(), polygon_path[i].lng());
      polygon_bounds.extend(point);
    }

    map.fitBounds(polygon_bounds);
    zoomChangeBoundsListener =
      google.maps.event.addListenerOnce(map, 'bounds_changed', function (event) {
        if (this.getZoom()) {
          this.setZoom(google_map_zoom_level);
        }
      });
    setTimeout(function () { google.maps.event.removeListener(zoomChangeBoundsListener) }, 2000);
  }

  // If Map exists
  if ($('#gmap').length > 0) {

    /*
       * Lat Long is set
       * Check if LAT/LONG is already set (Listing is in URL)
       */
    if ($('[name=listing_lat]').length > 0) {
      //28.11.2022////2023-07-18 : if (user_ip == '108.180.234.14') console.log('#gmap, listing_lat set');
      var position = {
        coords: {
          latitude: $('[name=listing_lat]').val(),
          longitude: $('[name=listing_long]').val()
        }
      },
        listing_id = $('[name=listing_id]').val();
      geocoder = new google.maps.Geocoder();
      handle_geolocation_query(position);
    }

    /*
       * City ID is set
       * Check if CITY/PROV is already set (Location is in URL)
       */
    else if ($('[name=cur_city]').length > 0) {
      //28.11.2022////2023-07-18 : if (user_ip == '108.180.234.14') console.log('#gmap cur_city set');
      var address = $('[name=cur_city]').val();
      polygon_is_active = false;
      address = address.replace(/\//g, ', ');
      $('#search_bar input[type=search]').val(address);
      $('#global_search_bar input[type=search]').val(address);
      codeAddress({ address: address, loadListings: true });
    }

    /*
   * Default City ID is set
   * Check if CITY/PROV is already set (Location is in URL)
   */
    else if ($('[name=default_city]').length > 0) {
      //28.11.2022////2023-07-18 : if (user_ip == '108.180.234.14') console.log('#gmap default_city set');
      var address = $('[name=default_city]').val();
      polygon_is_active = false;
      $body.find('#search_bar input[type=search]').focus();
      $body.find('#global_search_bar input[type=search]').focus();
      // geocoder = new google.maps.Geocoder();
      codeAddress({ address: address, loadListings: false });
    }

    /*
   * Partner ID is set
   * Load the map and listings with listings from the current partner
   */
    else if ($('[name=partner_id]').length > 0) {

      partner_id = $('[name=partner_id]').val(); // set the global partner_id
      //2023-07-18 : if (user_ip == '108.180.234.14') console.log('4309 partner_id set to  ' + partner_id);

      var partner_name = $body.find('#partner-info h1').text();
      $body.find('#partner_listings [role=NavigationController] h1').text(partner_name);
    } else if (typeof map_center_lat != 'undefined' && typeof map_center_lng != 'undefined') {

      var position = {
        coords: {
          latitude: map_center_lat,
          longitude: map_center_lng
        }
      };
      handle_geolocation_query(position);
    }

    /*
     * Add mapPopUp
     *
     */

    $('#gmap').append('<div id="mapInfoPopupDiv"></div>');
    mapInfoPopupDiv = $('body').find('#mapInfoPopupDiv');
    var mapDiv = document.getElementById('map-canvas').getElementsByTagName('div')[0];
    mapDiv.appendChild(document.getElementById("mapInfoPopupDiv"));
  }

  var service = new google.maps.places.AutocompleteService();

  $search_bar_input = $('#search_bar input[type=search]');

  $('#search_bar input[type=search]').autocomplete({
    source: function (request, response) {
      if (geocoder == null) {
        geocoder = new google.maps.Geocoder();
      }
      var finalresult = [],
        ecomdata = [],
        termrequest = { input: request.term };
      service.getPlacePredictions(termrequest, function (results, status) {
        //28.11.2022////2023-07-18 : if (user_ip == '108.180.234.14') console.log(results, status);
        if (status == 'OK') {
          finalresult = results;
          response(
            $.map(finalresult, function (loc) {

              return {
                label: loc.description,
                value: loc.value,
                lat: loc.lat,
                long: loc.long,
                id: loc.id,
                location: loc.location
              }
            })
          );
        }
      });
    },
    minLength: 1,
    delay: 1500,
    autoFocus: true,
    select: function (event, ui) {
      $('body').find('#search_bar input[type=search]').blur();
      codethis = ui.item.value || ui.item.label;
      //28.11.2022////2023-07-18 : if (user_ip == '108.180.234.14') console.log(codethis, 'codeThis');
      if (isNumeric($('body').find('#search_bar input[type=search]').val())) {
        getLocationFromValue(ui.item.location);
      } else {
        getLocationFromValue(codethis);
      }

      if (ui.item.id != null) {
        if (ui.item.id.length == 40) {
          var url = '?search=' + ui.item.value;
        } else {
          var url = ui.item.id;
        }
        history.pushState({}, url, url);
      }
    }
  });


  $global_search_bar_input = $('#global_search_bar input[type=search]');
  // using for global och101 sites
  // this is almost the same like search_bar but we need do redirect to found location
  $('#global_search_bar input[type=search]').autocomplete({
    source: function (request, response) {
      if (geocoder == null) {
        geocoder = new google.maps.Geocoder();
      }
      var finalresult = [],
        ecomdata = [],
        termrequest = { input: request.term };
      service.getPlacePredictions(termrequest, function (results, status) {
        //28.11.2022////2023-07-18 : if (user_ip == '108.180.234.14') console.log(results, status);
        if (status == 'OK') {
          finalresult = results;
          response(
            $.map(finalresult, function (loc) {
              return {
                label: loc.description,
                value: loc.value,
                lat: loc.lat,
                long: loc.long,
                id: loc.id,
                location: loc.location
              }
            })
          );
        }
      });
    },
    minLength: 1,
    delay: 1500,
    autoFocus: true,
    select: function (event, ui) {
      $('body').find('#global_search_bar input[type=search]').blur();

      history.pushState({}, ui.item.value, '?search=' + ui.item.value);
      window.location.reload()
      // codethis = ui.item.value || ui.item.label;
      // //2023-07-18 : if (user_ip == '108.180.234.14') console.log(codethis, 'codeThis 222');
      // if (isNumeric($('body').find('#global_search_bar input[type=search]').val())) {
      //   getLocationFromValue(ui.item.location);
      // } else {
      //   getLocationFromValue(codethis);
      // }
      //
      // if (ui.item.id != null) {
      //   if (ui.item.id.length == 40) {
      //     var url = '?search=' + ui.item.value;
      //   } else {
      //     var url = ui.item.id;
      //   }
      // }
    }
  });

  $('#global_search_bar').on('submit', function (e) {
    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('global_search_bar submit');
    $this = $(this);
    e.preventDefault();

    if ($('.ui-autocomplete .ui-menu-item:first').length > 0) {
      history.pushState({}, 'Search Results for ' + $('body').find('#global_search_bar input[type=search]').val(), '?search=' + $('body').find('#global_search_bar input[type=search]').val());
      window.location.reload()
    }
  });

  $('#search_bar').on('submit', function (e) {
    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('search_bar submit');
    $this = $(this);
    e.preventDefault();

    if ($('.ui-autocomplete .ui-menu-item:first').length > 0) {
      if (!gettingLocationFromValue)
        getLocationFromValue($('body').find('#search_bar input[type=search]').val());
    } else {
      if ($('#search_bar').find('input[type=search]').val().length > 2) {
        if (!gettingLocationFromValue)
          getLocationFromValue($('body').find('#search_bar input[type=search]').val());
      }
    }
  });

  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('4491 listing-load ');

  //onmouseleave="un_bounce_pin('<?=$listing_id?>')" onmouseenter="bounce_pin('<?=$listing_id?>')"
  $('#listing-load').on('mouseover', '.listing', function (e) {
    bounce_pin($(this).data('listing'));
    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('4496: ', e.pageX, e.pageY);
  });
  $('#listing-load').on('mouseout', '.listing', function (e) {
    un_bounce_pin($(this).data('listing'));
    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('4500: ', e.pageX, e.pageY);
  });

  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('4503 listing-load ');

  $search_bar.on('input keyup', '#loc_search', function () {
    term = $(this).val();
  });

  $global_search_bar_input.on('input keyup', '#loc_search', function () {
    term = $(this).val();
  });

  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('2516 - ');

  /////////////////////////////////////////////////////////
  //
  //  Map Bounds Changed
  //
  /////////////////////////////////////////////////////////
  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('4522 - ');

  google.maps.event.addListener(map, 'bounds_changed', function () {
    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('map, ev:bounds_changed');

    //2023-07-18 : if (user_ip == '108.180.234.14') console.log(' - ');

    // Re-center map on schoolMarker - to fix position problem on Android
    if (!polygon_is_active && partner_id == null && schoolMarker != null) {
      rtime = new Date();
      var mapCenter = map.getCenter(),

        bounds = map.getBounds(),
        ne = bounds.getNorthEast(), // LatLng of the north-east corner
        middleRight = new google.maps.LatLng(mapCenter.lat(), ne.lng()),
        distanceCenterToRightInMeters = google.maps.geometry.spherical.computeDistanceBetween(mapCenter, middleRight);

        //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5006 - mapCenter - ', mapCenter);

      radiusCenter = mapCenter;
      radius_meters = appropriate_distance(distanceCenterToRightInMeters) * 1000;
      var marker_pos = schoolMarker.getPosition().lat() + ',' + schoolMarker.getPosition().lng();
    }

    if (timeout === false) {
      timeout = true;
      setTimeout(bounds_changed, delta);
    }
  });
  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('4548 - ');


  /**
   * bounds_changed function.
   *
   * @access public
   * @return void
   */
  function bounds_changed() {
    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('fn:bounds_changed');

    if (new Date() - rtime < delta) {
      setTimeout(bounds_changed, delta);
    } else {

      if (!gettingLocationFromValue) {
        redraw_map({ radius: radius_meters, json: jSon });
      }
      timeout = false;
    }
  }




  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('4575 - ');


















  /////////////////////////////////////////////////////////
  //
  //  Map Zoom Changed
  /////////////////////////////////////////////////////////
  google.maps.event.addListener(map, 'zoom_changed', function () {
    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('zoom_changed');

    if (map.getZoom() < minZoomLevel) {
      map.setZoom(minZoomLevel);
    }
    var zoomLevel = map.getZoom(map);
  });

  /////////////////////////////////////////////////////////
  //
  //  Map Idle
  /////////////////////////////////////////////////////////
  google.maps.event.addListener(map, "idle", function () {
    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('get listing 1-2-3')
    // send the new bounds back to your server
    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('map, idle');

    $('#lat').val(map.getBounds().getCenter().lat());
    $('#long').val(map.getBounds().getCenter().lng());

    if (!gettingLocationFromValue && loadListings) {
      gettingLocationFromValue = true;

      openAlert({ message: 'loading', icon: 'spinner', duration: 6000 });
      //2023-07-18 : if (user_ip == '108.180.234.14') console.log('openAlert: r686');
      var load_data = {
        bounds: "" + map.getBounds()
      };


      if (partner_id != null) {
        load_data.type = 'partner';
        load_data.partner = partner_id;
      }

      $.post("/__inc/includes/get_listings.php", load_data)
        .done(function (str) {
          jSon = jQuery.parseJSON(str);
          listing_ids = '',
            comma = '',
            // get mas and mins for bedrooms and price
            minAmt = 9999999,
            maxAmt = 0,
            minBed = 9999999,
            maxBed = 0,
            //neighbours = [],
            //partners = [],
            order_listings = 'price desc';
          propTypes = [];
          if (jSon != null) {
            propTypeHTML = '';
            //partnersHTML = '',
            //neighboursHTML = '';
            for (a = 0; a < jSon.length; a++) {
              $(".total_property").remove();
              $('#map-canvas').append(
                '<div class="total_property" style="position: absolute; z-index: 999; bottom: 0; right: 0; background: #fff; margin-right: 20px; font-size: 18px; padding: 5px;">Listing Found: <b> ' + jSon.length + '</b></div>')
              if (minBed > jSon[a].bed)
                minBed = jSon[a].bed;

              if (maxBed < jSon[a].bed)
                maxBed = jSon[a].bed;

              if (minAmt > jSon[a].amt)
                minAmt = jSon[a].amt;

              if (maxAmt < jSon[a].amt)
                maxAmt = jSon[a].amt;

              // Display Property Types
              propTyp = jSon[a].typ;
              if (propTypes.indexOf(propTyp) < 0) {
                propTypes.push(propTyp);
                if (propTypesSelected.indexOf(Number(propTyp)) > -1) {
                  checked = 'checked';
                } else {
                  checked = '';
                }


                ////2023-07-18 : if (user_ip == '108.180.234.14') console.log("---------------> " + propTyp + " <-----------------");
                //alert("testing please ignore");

                if ($('#p_type_' + propTyp, '#refinements').length === 0) {
                  propTypeHTML += '<div class="refineoption custom-control custom-switch"><input type="checkbox" name="p_type_' + propTyp + '" id="p_type_' + propTyp + '" value="' + propTyp + '" ' + checked + ' class="custom-control-input"> <label for="p_type_' + propTyp + '" class="custom-control-label"><span class="property-type property-type-' + propTyp + '">' + prop_type[propTyp] + '</span></label></div>';
                }
              }
            }

            // check if the new propTypes exist in HTML
            // if yes, do nothing
            // if not, append
            // if not in newPropTypes but in HTML, remove
            $('#prop_type').html(propTypeHTML);

            for (var i = 0; i < propTypes.length; i++) {
              if (
                ($('#prop_type input', '#refinements').not('#p_type_' + propTypes[i])) &&
                ($('#p_type_' + propTypes[i], '#refinements').length === 0)
              ) {
                $('#p_type_' + propTypes[i], '#refinements').remove();
              }
            }
            $('#priceSlider').slider("option", "min", 0);
            $('#priceSlider').slider("option", "max", maxAmt);

            var priceMin = Number($('#priceSlider').data('min')) || minAmt,
              priceMax = Number($('#priceSlider').data('max')) || maxAmt;

            $('#priceSlider').slider("option", "values", [priceMin, priceMax]);

            $("#priceSliderValue").val("$" + priceMin + " - $" + priceMax);

            order_listings = $('#sortoptions li.active').data('option');
          }
          redraw_map({ radius: radius_meters, json: jSon });
        })
        .fail(
          function () {
            openAlert({ remove: true });
          }
        );
    }
  });

  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('4723 - ');

  /////////////////////////////////////////////////////////
  //
  //  Map Idle
  /////////////////////////////////////////////////////////

  if ($('#roommate-load').length > 0) {
    google.maps.event.addListener(map, "idle", function () {
      //2023-07-18 : if (user_ip == '108.180.234.14') console.log('get roommate 5-6-7')
      // send the new bounds back to your server
      //2023-07-18 : if (user_ip == '108.180.234.14') console.log('map, idle');

      // сюда даже не заходит
      if (!gettingLocationFromValue && loadListings) {
        gettingLocationFromValue = true;

        openAlert({}); // open loading bar
        var load_data = {
          bounds: "" + map.getBounds()
        };

        //2023-07-18 : if (user_ip == '108.180.234.14') console.log('123 get_roommates.php')
        $.post("/__inc/includes/get_roommates.php", load_data)
          .done(function (str) {
            jSon = jQuery.parseJSON(str);
            listing_ids = '',
              comma = '',
              // get mas and mins for bedrooms and price
              minAmt = 9999999,
              maxAmt = 0,
              minBed = 9999999,
              maxBed = 0,
              //neighbours = [],
              //partners = [],
              order_listings = 'price desc';
            propTypes = [];
            if (jSon != null) {
              propTypeHTML = '';
              //partnersHTML = '',
              //neighboursHTML = '';
              for (a = 0; a < jSon.length; a++) {
                if (minBed > jSon[a].bed)
                  minBed = jSon[a].bed;

                if (maxBed < jSon[a].bed)
                  maxBed = jSon[a].bed;

                if (minAmt > jSon[a].amt)
                  minAmt = jSon[a].amt;

                if (maxAmt < jSon[a].amt)
                  maxAmt = jSon[a].amt;

                // Display Property Types
                propTyp = jSon[a].typ;
                if (propTypes.indexOf(propTyp) < 0) {
                  propTypes.push(propTyp);
                  if (propTypesSelected.indexOf(Number(propTyp)) > -1) {
                    checked = 'checked';
                  } else {
                    checked = '';
                  }

                  if ($('#p_type_' + propTyp, '#refinements').length === 0) {
                    propTypeHTML += '<div class="refineoption custom-control custom-switch">' + propTyp + '<input type="checkbox" name="p_type_' + propTyp + '" id="p_type_' + propTyp + '" value="' + propTyp + '" ' + checked + ' class="custom-control-input"> <label for="p_type_' + propTyp + '" class="custom-control-label"><span class="property-type property-type-' + propTyp + '">' + prop_type[propTyp] + '</span></label></div>';
                  }
                }
              }

              // check if the new propTypes exist in HTML
              // if yes, do nothing
              // if not, append
              // if not in newPropTypes but in HTML, remove
              $('#prop_type').html(propTypeHTML);

              for (var i = 0; i < propTypes.length; i++) {
                if (
                  ($('#prop_type input', '#refinements').not('#p_type_' + propTypes[i])) &&
                  ($('#p_type_' + propTypes[i], '#refinements').length === 0)
                ) {
                  $('#p_type_' + propTypes[i], '#refinements').remove();
                }
              }
              $('#priceSlider').slider("option", "min", 0);
              $('#priceSlider').slider("option", "max", maxAmt);

              var priceMin = Number($('#priceSlider').data('min')) || minAmt,
                priceMax = Number($('#priceSlider').data('max')) || maxAmt;

              $('#priceSlider').slider("option", "values", [priceMin, priceMax]);

              $("#priceSliderValue").val("$" + priceMin + " - $" + priceMax);

              order_listings = $('#sortoptions li.active').data('option');
            }
            redraw_map({ radius: radius_meters, json: jSon });
          })
          .fail(
            function () {
              openAlert({ remove: true });
            }
          );
      }
    });
  }

  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('4830 - ');

  /////////////////////////////////////////////////////////
  //
  //  Map Drag End
  /////////////////////////////////////////////////////////
  if (schoolMarker != undefined) {


    google.maps.event.addListener(schoolMarker, 'dragend', function () {
      //2023-07-18 : if (user_ip == '108.180.234.14') console.log('dragend');
      var mapCenter = map.getCenter();

      //2023-07-18 : if (user_ip == '108.180.234.14') console.log('4843 - mapCenter - ', mapCenter);

      var bounds = map.getBounds();
      var ne = bounds.getNorthEast(); // LatLng of the north-east corner
      var middleRight = new google.maps.LatLng(mapCenter.lat(), ne.lng());
      var distanceCenterToRightInMeters = google.maps.geometry.spherical.computeDistanceBetween(mapCenter, middleRight);
      radius_meters = appropriate_distance(distanceCenterToRightInMeters);

      cityCircle.setMap(null);
      if (typeof radiusLine == 'object') {
        radiusLine.setMap(null);
      }

      $('#lat').val(schoolMarker.position.lat());
      $('#long').val(schoolMarker.position.lng());

      radiusCenter = this.getPosition();
      mapCenter = new google.maps.LatLng(radiusCenter.lat(), radiusCenter.lng());
      map.setCenter(mapCenter);

      redraw_map({ radius: radius_meters, json: jSon });
    });

  }

  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('4865 - ');

  // if search bar is already filled

  if ($search_bar_input.val() != '') {
    if (!gettingLocationFromValue) getLocationFromValue($search_bar_input.val());
  }

  if ($global_search_bar_input.val() != '') {
    if (!gettingLocationFromValue) getLocationFromValue($global_search_bar_input.val());
  }

  $('body').on('mouseenter', '#map-canvas', function (e) {
    ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('4787: map mouseenter', e.pageX, e.pageY);
    //mapInfoPopupDiv.css({ 'left': e.pageX, 'top': e.pageY });
  });

  mapInfoPopupDiv.on('mouseleave', function () {
    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('4793: mapInfoPopupDiv mouseleave');
    mapInfoPopupDiv.hide();
    mapInfoPopupDiv.popover('dispose');
  });

}


/**
 * add_drag_marker function.
 *
 * @access public
 * @return void
 */
function add_drag_marker(lat, lng) {
  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('add_drag_marker', lat, lng);
  if (schoolMarker != null) {
    schoolMarker.setMap(null);
  }
  if (lat == null && lng == null) {
    var new_position = radiusCenter;
  } else {
    var new_position = new google.maps.LatLng(lat, lng)
  }
  schoolMarker = new google.maps.Marker(
    {
      position: new_position,
      map: map,
      draggable: true,
      animation: google.maps.Animation.DROP,
      'icon': site_location_pin,
      'title': 'Drag Me!',
      'cursor': 'move',
    });
  /////////////////////////////////////////////////////////
  //
  //  Map Drag End
  /////////////////////////////////////////////////////////
  google.maps.event.addListener(schoolMarker, 'dragend', function () {
    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('dragend');
    $('#lat').val(schoolMarker.position.lat());
    $('#long').val(schoolMarker.position.lng());

  });
}


//2023-07-18 : if (user_ip == '108.180.234.14') console.log('4930 - ');

/**
 * display_mouseover function.
 *
 * @access public
 * @param mixed id
 * @param mixed typ
 * @param mixed bed
 * @param mixed lat
 * @param mixed lng
 * @param mixed pet
 * @param mixed dis
 * @param mixed smo
 * @param mixed pic
 * @param mixed amt
 * @return void
 */
// function display_mouseover(id, typ, bed, lat, lng, pet, dis, smo, pic, amt) {
//   //2023-07-18 : if (user_ip == '108.180.234.14') console.log(id)
//   $body = $('body');
//   HTML = "<div class='map_pop_up'><div class='map_pop_up_price'><span class='b1'>$" + amt + "</span></div>" +
//     "	<div class='map_pop_up_img'><img src='/shared" + pic + "' width='150' height='80' style='width:150px; max-height:80px;'></div>" +
//     "	" +
//     "</div>";
//   if ($('#mapInfoPopupDiv').length > 0) {
//     $mapInfoPopupDiv = $('#mapInfoPopupDiv');
//     $mapInfoPopupDiv.show();
//     $mapInfoPopupDiv.html(HTML);
//   } else {
//     $('#map-canvas', 'body').after("<div id='mapInfoPopupDiv'>" + HTML + "</div>");
//   }
//   $body.on('mousemove', '#map-canvas', function (e) {
//     $body.find('#mapInfoPopupDiv').css({
//       'left': (e.pageX - 200),
//       'top': (e.pageY - 100)
//     });
//   });
// }


/**
 * redraw_map function.
 *
 * @access public
 * @param mixed options
 * @return void
 */
function redraw_map(options) {
  








  $('#map-canvas').show();
  if (user_ip == '101.188.67.134') console.log('4980 - redraw_map', options);

  gettingLocationFromValue = true;

  listingMarkers = [];
  if (markerClusterer) {
    markerClusterer.clearMarkers();
  }

  // TODO: Check if Polygon is set
  if (!polygon_is_active && partner_id == null && schoolMarker != null) {
    schoolMarker.setPosition(map.getCenter());
    
    if (user_ip == '101.188.67.134') console.log('4993 - ', options);
    draw_circle();

    //2023-07-18 : if (user_ip == '108.180.234.14') console.log('4996 - ');

    var radius_meters = options.radius || 'null';
      // jSon = options.jSon || 'null',
      // orderby = options.orderby || 'null',

      //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5002 - ');
      var   mapCenter = map.getCenter();

      //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5005 - ');
      //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5006 - mapCenter - ', mapCenter);

      //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5008 - ', map);
//      var bounds = map.getBounds();
      var bounds = new google.maps.LatLngBounds();




      //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5010 - ', bounds);
      var ne = bounds.getNorthEast(); // LatLng of the north-east corner
      //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5012 - ');
      var sw = bounds.getSouthWest(); // LatLng of the south-west corder
      //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5014 - ');
      // nw = new google.maps.LatLng(ne.lat(), sw.lng()),
      // se = new google.maps.LatLng(sw.lat(), ne.lng()),
      var middleRight = new google.maps.LatLng(mapCenter.lat(), ne.lng());

      var latDiff = ne.lat() - sw.lat();
      var lngDiff = ne.lng() - sw.lng();
      var lat_offset_down = ne.lat() + (latDiff / 2) + (latDiff / 100 * percentDown);

      // distance_vertical = google.maps.geometry.spherical.computeDistanceBetween(ne, se),
      // distance_horizontal = google.maps.geometry.spherical.computeDistanceBetween(ne, nw),
      // distanceCenterToRightInMeters = google.maps.geometry.spherical.computeDistanceBetween(mapCenter, middleRight),
      var middleRight = google.maps.geometry.spherical.computeOffset(mapCenter, radius_meters, 90);
      // lngDiffRadius = (mapCenter.lng() - middleRight.lng()),
      var radiusLineMiddle = new google.maps.LatLng(mapCenter.lat(), (mapCenter.lng() - ((mapCenter.lng() - middleRight.lng()) / 2)));

    var centerToOuterRight =
      [
        mapCenter,
        middleRight

      ];

    for (i = 0; i < line.length; i++) {
      line[i].setMap(null); //or line[i].setVisible(false);
    }
    radiusLine = new google.maps.Polyline(
      {
        path: centerToOuterRight,
        geodesic: true,
        strokeColor: '#ff0000',
        strokeOpacity: 1.0,
        strokeWeight: 2
      });
    line.push(radiusLine);
    radiusLine.setMap(map);


    // Overlay the radius distance on the radiusLine
    if (units == 'km') {
      if (kmDisplayed[displayArrPos + 1] != undefined) {
        var iconImage =
        {
          url: '/__inc/images/google_map_overlays/' + kmDisplayed[displayArrPos + 1].replace(/\s+/g, '') + '.png',
          anchor: new google.maps.Point(21, 7)
        };
      }
    } else if (miDisplayed[displayArrPos + 1] != undefined) {
      var iconImage =
      {
        url: '/__inc/images/google_map_overlays/' + miDisplayed[displayArrPos + 1].replace(/\s+/g, '') + '.png',
        anchor: new google.maps.Point(21, 7)
      };
    } else {
      var iconImage =
      {
        anchor: new google.maps.Point(21, 7)
      };
    }

    radiusDistanceMarker = new google.maps.Marker(
      {
        position: radiusLineMiddle,
        size: new google.maps.Size(42, 13),
        map: map,
        'zindex': -2,
        icon: iconImage
      });
    listingMarkers.push(radiusDistanceMarker);
  }


  redraw_markers();
  openAlert({ remove: true });
  return true;
}


/**
 * drawRadiusLine function.
 *
 * @access public
 * @return void
 */
function drawRadiusLine() {
  //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('drawRadiusLine');
  var flightPlanCoordinates = [];
  for (var key in markers) {
    flightPlanCoordinates.push(markers[key].position);
  }
  if (flightPath) {
    flightPath.setPath(flightPlanCoordinates);
  } else {
    flightPath = new google.maps.Polyline(
      {
        path: flightPlanCoordinates,
        strokeColor: '#ff0000',
        strokeOpacity: 1.0,
        strokeWeight: 2
      });
    flightPath.setMap(map);
  }
}


/**
 * appropriate_distance function.
 *
 * @access public
 * @param mixed distanceCenterToRightInMeters
 * @return void
 */
function appropriate_distance(distanceCenterToRightInMeters) {

  //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5115 - appropriate_distance()');
  // look for the best fit in meters

  var units = 'km';
  displayArrPos = 17;
  var m;

  if (units == 'mi') {
    var numbers = [823984.64, 411992.32, 205996.16, 102998.08, 51499.04, 25749.52, 12874.76, 6437.38, 3218.69, 1609.34, 804.67, 402.335, 201.1675, 100.58375, 50.291875, 25.1459375, 12.57296875, 6.286484375];	// Meters
    while (numbers[--displayArrPos]) {
      if (distanceCenterToRightInMeters < numbers[displayArrPos]) {
        break;
      }
    }
    $('#radiusSliderValue').html(miDisplayed[(displayArrPos + 1)]);
  } else {
    var numbers = [512000, 256000, 128000, 64000, 32000, 16000, 8000, 4000, 2000, 1000, 500, 250, 125, 62.5, 31.25, 15.625, 7.8125, 3.90625];		// Meters
    while (numbers[--displayArrPos]) {
      if (distanceCenterToRightInMeters < numbers[displayArrPos]) {
        break;
      }
    }
    $('#radiusSliderValue').html(kmDisplayed[(displayArrPos + 1)]);
  }
  return numbers[(displayArrPos + 1)] / 1000;
}


/**
 * redraw_markers function.
 *
 * @access public
 * @return void
 */
function redraw_markers() {
  //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('redraw_markers');
  /* if custom pin exists, add to map - for templated sites */
  if (typeof pin != 'undefined' && partner_id == null) {
    //var pin_latlong = new google.maps.LatLng(pin);

    cMarker = new google.maps.Marker(
      {
        position: { lat: parseFloat(pin_lat), lng: parseFloat(pin_long) },
        map: map,
        draggable: false,
        'icon': site_location_pin,
        'title': pin_name,
        'zIndex': 1
      });
  }
  full_markers = [];
  faded_markers = [];
  full_markers_count = 0
  removeMarkers();
  addMarkers(jSon);

}


/**
 * addMarkers function.
 *
 * @access public
 * @param mixed jSon
 * @return void
 */
function addMarkers(jSon) {
  // //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('addMarkers', jSon)

  full_markers_count = 0;
  listing_ids = '';

  var pets = 'all',
    disability = 'all',
    smoking = 'all',
    furnished = 'all',
    short_term = 'all';

  if ($('.pets_option').hasClass('no-pets')) pets = 0;
  else if ($('.pets_option').hasClass('pets')) pets = 1;

  if ($('.disability_option').hasClass('no-disability')) disability = 0;
  else if ($('.disability_option').hasClass('disability')) disability = 1;

  if ($('.smoking_option').hasClass('no-smoking')) smoking = 0;
  else if ($('.smoking_option').hasClass('smoking')) smoking = 1;

  if ($('.furnished_option').hasClass('no-furnished')) furnished = 0;
  else if ($('.furnished_option').hasClass('furnished')) furnished = 1;

  if ($('.short_term_option').hasClass('no-short_term')) short_term = 0;
  else if ($('.short_term_option').hasClass('short_term')) short_term = 1;


  if (jSon != null) {

    var minBedrooms = $('#selectMinBedrooms').val(),
      minPrice = $('#priceSlider').slider("values", 0),
      maxPrice = $('#priceSlider').slider("values", 1);
    comma = '';
    listing_ids = '',
      bounds = new google.maps.LatLngBounds();
    // jSon.sort(function (a, b) {
    //   return b.with_pic - a.with_pic
    // })

    for (a = 0; a < jSon.length; a++) {
      var markerPosition = new google.maps.LatLng(jSon[a].lat, jSon[a].lng);

      if (partner_id != null) {
        if (a == 0) map.setCenter(markerPosition);
        bounds.extend(markerPosition);
        distance = false;
      } else {
        distance = google.maps.geometry.spherical.computeDistanceBetween(radiusCenter, markerPosition);
      }


      // If Marker is within the radius
      if (map.getBounds().contains(markerPosition) == true || partner_id != null) {
        var image =
        {
          url: '/__inc/icons/map-' + jSon[a].typ + '.png',
          // This marker is 20 pixels wide by 32 pixels tall.
          size: new google.maps.Size(32, 37),
          // The origin for this image is 0,0.
          origin: new google.maps.Point(0, 0),
          // The anchor for this image is the center of the image.
          anchor: new google.maps.Point(16, 18)
        };

        if (furnished == 'all')
          furnishedInclude = true;
        else if (jSon[a].fur == furnished)
          furnishedInclude = true;
        else
          furnishedInclude = false;


        if (short_term == 'all')
          short_termInclude = true;
        else if (jSon[a].ter == short_term)
          short_termInclude = true;
        else
          short_termInclude = false;

        if (pets == 'all')
          petsInclude = true;
        else if (jSon[a].pet == pets)
          petsInclude = true;
        else
          petsInclude = false;

        if (disability == 'all')
          disabilityInclude = true;
        else if (jSon[a].dis == disability)
          disabilityInclude = true;
        else
          disabilityInclude = false;

        if (smoking == 'all')
          smokingInclude = true;
        else if (jSon[a].smo == smoking)
          smokingInclude = true;
        else
          smokingInclude = false;

        if (propTypesSelected.indexOf(Number(jSon[a].typ)) < 0)
          propTypeInclude = false;
        else
          propTypeInclude = true;

        /*if(neighboursSelected.indexOf(jSon[a].nei) < 0)
          neighbourInclude = false;
        else
          neighbourInclude = true;
          */
        /*if(partnersSelected.indexOf(jSon[a].par) < 0)
          partnerInclude = false;
        else
          partnerInclude = true;
        */
        var inPolygon = (polygon_is_active && polygon_line) ? google.maps.geometry.poly.containsLocation(markerPosition, polygon_line) : false;

        // TODO: move to global varable
        // If all criteria matches, show active pin
        if (((!polygon_is_active && (distance < radius_meters))
          || (polygon_is_active && inPolygon))
          && (jSon[a].bed > minBedrooms - 1)
          && (jSon[a].amt >= minPrice)
          && (jSon[a].amt <= maxPrice)
          && (petsInclude)
          && (disabilityInclude)
          && (smokingInclude)
          && (propTypeInclude)
          && (furnishedInclude)
          && (short_termInclude)) {
          $('#listing_' + jSon[a].id).slideDown(250);
          $('#listings #listing_' + jSon[a].id + ' + #listing_openxad').slideDown(250);

          // show full marker
          if (typeof full_markers[jSon[a].id] == 'undefined') {
            full_markers_count++;

            listing_ids += comma + jSon[a].id;
            comma = ',';

            var marker = new google.maps.Marker(
              {
                'id': jSon[a].id,
                'type': jSon[a].typ,
                'beds': jSon[a].bed,
                'lat': jSon[a].lat,
                'lng': jSon[a].lng,
                'pet': jSon[a].pet,
                'dis': jSon[a].dis,
                'smo': jSon[a].smo,
                'pic': jSon[a].pic,
                'amt': jSon[a].amt,
                'fur': jSon[a].fur,
                'ter': jSon[a].ter,
                'dir': jSon[a].dir,
                position: markerPosition,
                map: map,
                anchor: new google.maps.Point(16, 18),
                icon: image,
                title: '' + jSon[a].amt
              });

            google.maps.event.addListener(marker, 'click', function () {
              window.location = marker.dir;
            });

            // TODO: Move to display_mouseover function
            marker.addListener("mouseover", function (event) {
              var e = window.event;
              var posX = e.clientX;
              var posY = e.clientY;
              mapInfoPopupDiv.css({ 'left': posX, 'top': posY });
              //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5260: marker.mouseover ' + posX + ' ' + posY);


              // display_mouseover(marker)
              mapInfoPopupDiv.popover('dispose');

              var YNM_arr = { '1': 'Yes', '0': 'No' }

              var propertyTypes = {
                20: 'Apartment', 21: 'Condo', 23: 'Duplex', 24: 'House', 25: 'Mobile Home', 26: 'Room', 27: 'Room', 28: 'Furnished',
                29: 'Suite', 30: 'Townhouse', 35: 'Room', 37: 'Executive', 7523: 'Room', 1130: 'Townhouse'
              }
              // ALL IS Other

              var propertyName = '';
              if (propertyTypes[marker.type]) {
                propertyName = propertyTypes[marker.type]
              } else {
                propertyName = 'Other';
              }

              var beds;
              if (marker.beds == 0) {
                beds = "Studio";
              } else {
                beds = marker.beds + " Bedroom";
              }
              var price = 'Call'
              if (marker.amt != 0) {
                price = '$' + marker.amt;
              }
              //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log(marker);
              var popup_html = "<div class='map_pop_up2'>";
              popup_html += "<h5 class=\"card-title\">Listing # " + marker.id + "</h5>";
              popup_html += "<a href='" + marker.dir + "'><img src='" + marker.pic + "'></a>";
              popup_html += "<div class='map_pop_up_h1'><img src='" + marker.icon.url + "' style='vertical-align:middle'>" + propertyName + "</div>";
              popup_html += "<div class='map_pop_up_3_icons' style='float:right;'><img width=25 src='/shared/images/IMG-" + YNM_arr[marker.smo] + "Smoke.png' alt='" + YNM_arr[marker.smo] + " Smoking'><img width=25 src='/shared/images/IMG-" + YNM_arr[marker.dis] + "WheelChair.png' alt='" + YNM_arr[marker.dis] + " Disability Access'><img width=25 src='/shared/images/IMG-" + YNM_arr[marker.pet] + "Pets.png' alt='" + YNM_arr[marker.pet] + " pets'></div>";
              popup_html += "<div class='map_pop_up_bedrms'>" + beds + "</div>";
              popup_html += "<div class='map_pop_up_price'>Price <span class='b1'>" + price + "</span></div>";
              popup_html += "</div>";

              mapInfoPopupDiv.popover({
                container: '#mapInfoPopupDiv',
                content: popup_html,
                html: true,
                placement: 'auto',
                trigger: 'manual',
                delay: { show: 1000, hide: 500 }
              })



              mapInfoPopupDiv.show();
              mapInfoPopupDiv.popover('show');
            });

            marker.addListener('mouseout', function () {
              //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5308: marker.mouseout ');
              //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5308: marker.mouseout ', markerPosition.lat(), markerPosition.lng());
              //              mapInfoPopupDiv.hide();
              //              mapInfoPopupDiv.popover('hide');
            });

            marker.addListener('mouseenter', function () {


              var e = window.event;
              var posX = e.clientX;
              var posY = e.clientY;
              mapInfoPopupDiv.css({ 'left': posX, 'top': posY });
              //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5315: marker.mouseenter ' + posX + ' ' + posY);


            });

            marker.addListener('mouseleave', function () {
              //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5318: marker.mouseleave');
            });

            listingMarkers.push(marker);
            full_markers[jSon[a].id] = jSon[a].lat + ',' + jSon[a].lng + ',' + jSon[a].typ;
            inner['lat'] = jSon[a].lat;
            inner['lng'] = jSon[a].lng;
            inner['typ'] = jSon[a].typ;
            inner['bed'] = jSon[a].bed;
            inner['amt'] = jSon[a].amt;
            outer[jSon[a].id] = inner;

            delete faded_markers[jSon[a].id];
          }
        }
        // Else if marker does not match criteria, change to small icon and hide listing.
        else {
          if (!inPolygon && polygon_is_active) {
            delete full_markers[jSon[a].id];
          }
          // show small dot marker
          else if (typeof faded_markers[jSon[a].id] == 'undefined') {
            $('#listings #listing_' + jSon[a].id).slideUp(500, function () {
              //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('scroll listing true')
              $('#listing-load').trigger('scroll');
              console.log('5407 listing-load ');

            });
            $('#listings #listing_' + jSon[a].id + ' + #listing_openxad').slideUp(500);
            /*var marker = new google.maps.Marker({
  position: markerPosition,
  map: map,
  anchor: new google.maps.Point(16,18),
  icon: '/shared/images/icons/google_grey_dot_sm.png',
  opacity: 0.90,
  title: ''+jSon[a].amt,
  'zIndex': -1,
  id: jSon[a].id
            });*/

            //listingMarkers.push(marker);
            faded_markers[jSon[a].id] = jSon[a].lat + ',' + jSon[a].lng + ',' + jSon[a].typ;

            delete full_markers[jSon[a].id];
          }
        }
      } // endif map.getBounds().contains(markerPosition) == true

    } // for each map pin

    var markerClusterer = new MarkerClusterer(map, listingMarkers, {});

    /*google.maps.event.addListener(markerClusterer, 'click', function(cluster) {
      if(debug)//2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('clusterclick', cluster.pageX);
      // TODO: Change to just load full page
      //display_mouseover();
    });*/





    // Switch icon on marker mouseover and mouseout
    // TODO: Move to display_mouseover function
    google.maps.event.addListener(markerClusterer, "mouseover", function (cluster) {
      //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5381: markerClusterer.mouseover', cluster.center_.lat(), cluster.center_.lng());
      //      mapInfoPopupDiv.css({ 'left': X + 720, 'top': Y + 335 });

      mapInfoPopupDiv.popover('dispose');

      //2023-07-18 : //2023-07-18 : if (user_ip == '108.180.234.14') console.log('clustermouseover');

      var markers = cluster.getMarkers();

      var popup_html = "<div class='map_pop_up'>";
      popup_html += "<div class='row'>";
      if (markers.length > 20)
        maxReached = "<div id='maxMarkersReached'>Only 20 shown, <br>please zoom in to limit your results.</div>";
      else
        maxReached = "";
      var maxMarkers = (markers.length < 20) ? markers.length : 20;

      for (j = 0; j < maxMarkers; j++) {
        const lowLightArray = [0, 3, 4, 7, 8, 11, 12, 15, 16, 19];
        if (lowLightArray.includes(j))
          greyClass = ' greyClass ';
        else
          greyClass = ' ';
        var price = (markers[j].amt == 0) ? 'Call' : '$' + markers[j].amt;
        var beds = (markers[j].beds == 0 || typeof markers[j].beds == 'undefined') ? 'Studio' : markers[j].beds + ' <small>Bedroom</small>';
        popup_html += "<div class='col-6 card mb-1 listing listing-tiny " + greyClass + "' data - role='listing-tiny' >";
        popup_html += "  <a href='" + markers[j].dir + "'>";
        popup_html += "    <span class='row no-gutters' style='display: block;'>";
        popup_html += "      <div class='col-12'>";
        popup_html += "        <div class='listing-thumbnail' style='width: 200px; height: 120px;'>";
        popup_html += "          <img src='" + markers[j].pic + "' >";
        popup_html += "        </div>";
        popup_html += "      </div>";
        popup_html += "      <div class='card-body'><span class='card-text listing-price'>" + price + "</span>";
        popup_html += "        <ul class='list-group list-group-flush list-group-horizontal d-flex text-left text-muted'>";
        popup_html += "          <li class='list-group-item flex-fill p-0 " + greyClass + "'>" + beds + "</li>";
        popup_html += "        </ul>";
        popup_html += "      </div>";
        popup_html += "      </a>";
        popup_html += "    </span >";
        popup_html += "  </a >";
        popup_html += "</div >";
      }
      popup_html += "</div>";
      popup_html += maxReached;
      popup_html += "</div>";

      mapInfoPopupDiv.popover({
        container: '#mapInfoPopupDiv',
        content: popup_html,
        html: true,
        placement: 'auto',
        trigger: 'manual',
        offset: '10',
        delay: { show: 1000, hide: 0 }
      })

      mapInfoPopupDiv.show();
      mapInfoPopupDiv.popover('show');

      var e = window.event;
      var posX = e.clientX;
      var posY = e.clientY;
      mapInfoPopupDiv.css({ 'left': posX, 'top': posY });
      //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5449: markerClusterer ' + posX + ' ' + posY);



    });

    if ($('[name=partner_id]').length > 0) {
      partner_id = $('[name=partner_id]').val();
    }

    //2023-07-18 : if (user_ip == '108.180.234.14') console.log(5508);
    if (partner_id != null) {
      map.fitBounds(bounds);
      map.panToBounds(bounds);
      ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('5532 show_listings --------------------------------------------------------');
      show_listings({ type: 'partner', str: partner_id, orderby: order_listings, offset: 0, clear: true });
    } else {
      ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('5535 show_listings --------------------------------------------------------');
      show_listings({ str: listing_ids, orderby: order_listings, offset: 0, clear: true });
      gettingLocationFromValue = false;
    }
  } else {
    gettingLocationFromValue = false;
  }

  $("#listingsCount").val(full_markers_count + " Listings");
}


if ($('[name=partner_id]').length > 0) {
  partner_id = $('[name=partner_id]').val();
  show_listings({ type: 'partner', str: partner_id, orderby: order_listings, offset: 0, clear: true });
}

/**
 * clearClusters function.
 *
 * @access public
 * @param mixed e
 * @return void
 */
function clearClusters(e) {
  e.preventDefault();
  e.stopPropagation();
  markerClusterer.clearMarkers();
}

/**
 * draw_circle function.
 *
 * @access public
 * @return void
 */
function draw_circle() {
  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5615 - draw_circle');
  // Construct the circle for each value in radiusCenter and radius_meters
  // Note: We scale the area of the circle based on the radius.

  if (typeof cityCircle == 'object') {
    cityCircle.setMap(null);
  }

  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5623 - ');

  var radiusOptions =
  {
    strokeColor: '#ff0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#ff0000',
    fillOpacity: 0.05,
    map: map,
    center: radiusCenter,
    radius: radius_meters
  };

  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5637 - ');

  // Add the circle for this city to the map.
  cityCircle = new google.maps.Circle(radiusOptions);

  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('5642 - ');
}


/**
 * removeMarkers function.
 *
 * @access public
 * @return void
 */
function removeMarkers() {
  for (i = 0; i < listingMarkers.length; i++) {
    listingMarkers[i].setMap(null);
  }
}


/**
 * gotoStreetView function.
 *
 * @access public
 * @param mixed lat
 * @param mixed long
 * @return void
 */
function gotoStreetView(lat, long) {
  var fenway = new google.maps.LatLng(lat, long);
  var panoramaOptions = {
    position: fenway,
    pov: {
      heading: 34,
      pitch: 10
    }
  };
  var panorama = new google.maps.StreetViewPanorama(document.getElementById("pano-canvas"), panoramaOptions);
  map.setStreetView(panorama);
}


/**
 * getLocationFromValue function.
 *
 * @access public
 * @param mixed codethis
 * @return void
 */
function getLocationFromValue(codethis) {
  //2023-07-18 : if (user_ip == '108.180.234.14') console.log('getLocationFromValue', codethis);

  if (typeof codethis == "undefined") {
    return;
  }
  gettingLocationFromValue = true;
  openAlert({});
  polygon_is_active = false;


  if (isNumeric(codethis)) {
    window.location = '/__inc/includes/get_listing_by_id.php?lid=' + codethis
    // get_panel({id: codethis, url: 'listing-full', type: 'overlay', position: 'right'});

  } else {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      'address': codethis
    }, function (result, status) {
      places = result[0];

      $('body').find('#mapTitle h1').text('Rentals in ' + codethis);

      history.pushState({}, 'Search Results for ' + codethis, '?search=' + codethis);
      if (status == google.maps.GeocoderStatus.OK) {

        var lct = places.geometry.location_type;
        var bounds = places.geometry.bounds;

        //2023-07-18 : if (user_ip == '108.180.234.14') console.log("5737 - ", bounds, codethis);

        if (bounds) {
          map.fitBounds(bounds);
        }

        // load in listing panel
        if ($('body').find('#listings').length === 0) {
          console.log('5637           --------------------------------------------');
          get_panel({ id: 'listings', url: 'listings', type: 'static', position: 'left' });
        }

        var lat = places.geometry.location.lat(),
          long = places.geometry.location.lng();

          mapCenter = new google.maps.LatLng(lat, long);

        //2023-07-18 : if (user_ip == '108.180.234.14') console.log("5740 -----> ", lat, long);

        add_drag_marker(lat, long);
        //remove home_panel
        if ($('#map-canvas').length > 0) {
          $('#map-canvas').siblings('div').slideUp(250, function () {
            $(this).remove();
            $('body').find('#listings').siblings('[data-position="left"]').remove();

          });
          map.setCenter(mapCenter);
          redraw_map({ radius: radius_meters, json: jSon });

        } else {
          map.setCenter(mapCenter);
          redraw_map({ radius: radius_meters, json: jSon });
        }
      }
    });
  }
}


/**
 * bounce_pin function.
 *
 * @access public
 * @param mixed id
 * @return void
 */
function bounce_pin(id) {
  for (var index = 0; index < listingMarkers.length; index++) {
    if (listingMarkers[index].get("id") == id) {
      var marker = listingMarkers[index];
      marker.setAnimation(google.maps.Animation.BOUNCE);
    }
  }
}


/**
 * un_bounce_pin function.
 *
 * @access public
 * @param mixed id
 * @return void
 */
function un_bounce_pin(id) {
  for (var index = 0; index < listingMarkers.length; index++) {
    if (listingMarkers[index].get("id") == id) {
      var marker = listingMarkers[index];
      marker.setAnimation(null);
    }
  }
}


/**
 * createHistoryString function.
 *
 * @access public
 * @param mixed obj
 * @return void
 */
function createHistoryString(obj) {
  //2023-07-18 : if (user_ip == '108.180.234.14') console.log(obj);

  var query = window.location.search.substring(1);
  var qs = parse_query_string(query);
  ////2023-07-18 : if (user_ip == '108.180.234.14') console.log(qs);
  var historyUrlString = '';
  if (typeof qs.search != 'undefined') {
    historyUrlString = '?search=' + qs.search + '&refine='
  } else {
    historyUrlString = '?refine='
  }

  var comma = '';
  for (var prop in obj) {
    historyUrlString += comma + obj[prop];
    comma = ',';
  }
  history.pushState({}, historyUrlString, historyUrlString);
}


/**
 * parse_query_string function.
 *
 * @access public
 * @param mixed query
 * @return void
 */
function parse_query_string(query) {
  var vars = query.split("&"),
    query_string = {};
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("="),
      key = decodeURIComponent(pair[0]),
      value = decodeURIComponent(pair[1]);
    // If first entry with this name
    if (typeof query_string[key] === "undefined") {
      query_string[key] = decodeURIComponent(value);
      // If second entry with this name
    } else if (typeof query_string[key] === "string") {
      var arr = [query_string[key], decodeURIComponent(value)];
      query_string[key] = arr;
      // If third or later entry with this name
    } else {
      query_string[key].push(decodeURIComponent(value));
    }
  }
  return query_string;
}

/////////////////////////////////////////////////////////
//
//  Refinements
//
/////////////////////////////////////////////////////////

$(document).ready(function () {
  $body = $('body'),
    $refinements = $("#refinements"),
    $mapCanvas = $('#mapCanvas');


  var width = $(window).width(),
    height = $(window).height(),
    Min = 7,
    Max = 13,
    historyObj = {};

  if (width > height) {
    $mapCanvas.height(height);
    $mapCanvas.width(height);
  } else {
    $mapCanvas.height(width);
    $mapCanvas.width(width);
  }


  radius_meters = (Math.pow(2, (Max - 5) - 16) * 1000) * multiplier;


  $("#selectMinBedrooms").change(function () {

    redraw_map({ radius: radius_meters, json: jSon });


    historyObj['beds'] = 'beds' + $(this).val();
    createHistoryString(historyObj);
  });

  $body.on('click', ".furnished_option", function () {

    $this = $(this);
    if ($this.hasClass('ns_furnished')) {
      $this.addClass('furnished');
      $this.removeClass('ns_furnished');
      historyObj['furnished'] = 'furnished';
    } else if ($this.hasClass('furnished')) {
      $this.addClass('no-furnished');
      $this.removeClass('furnished');
      historyObj['furnished'] = 'no-furnished';
    } else if ($(this).hasClass('no-furnished')) {
      $this.addClass('ns_furnished');
      $this.removeClass('no-furnished');
      historyObj['furnished'] = 'ns_furnished';
    }
    redraw_map({ radius: radius_meters, json: jSon });

    createHistoryString(historyObj);
  });

  $body.on('click', ".short_term_option", function () {
    $this = $(this);
    if ($this.hasClass('ns_short_term')) {
      $this.addClass('short_term');
      $this.removeClass('ns_short_term');
      historyObj['term'] = 'short_term';
    } else if ($this.hasClass('short_term')) {
      $this.addClass('no-short_term');
      $this.removeClass('short_term');
      historyObj['term'] = 'no-short_term';
    } else if ($this.hasClass('no-short_term')) {
      $this.addClass('ns_short_term');
      $this.removeClass('no-short_term');
      historyObj['term'] = 'ns_short_term';
    }
    redraw_map({ radius: radius_meters, json: jSon });

    createHistoryString(historyObj);
  });


  $body.on('click', ".pets_option", function () {
    $this = $(this);
    if ($('.pets_option').hasClass('ns_pets')) {
      $('.pets_option').addClass('pets').removeClass('ns_pets');

      $('.pets_option').find('i').addClass('icon-pets').removeClass('icon-no-pets');

      historyObj['pets'] = 'pets';
    } else if ($('.pets_option').hasClass('pets')) {
      $('.pets_option').addClass('no-pets').removeClass('pets');

      $('.pets_option').find('i').addClass('icon-no-pets').removeClass('icon-pets');
      historyObj['pets'] = 'no-pets';
    } else if ($('.pets_option').hasClass('no-pets')) {
      $('.pets_option').addClass('ns_pets').removeClass('no-pets');

      $('.pets_option').find('i').addClass('icon-pets').removeClass('icon-no-pets');

      historyObj['pets'] = 'ns_pets';
    }
    redraw_map({ radius: radius_meters, json: jSon });

    createHistoryString(historyObj);
  });


  $body.on('click', ".disability_option", function () {
    $this = $(this);
    if ($('.disability_option').hasClass('disability')) {
      $('.disability_option').addClass('ns_disability');
      $('.disability_option').removeClass('disability');
      historyObj['disability'] = 'ns_disability';
    } else if ($('.disability_option').hasClass('ns_disability')) {
      $('.disability_option').addClass('disability');
      $('.disability_option').removeClass('ns_disability');
      historyObj['disability'] = 'disability';
    }
    redraw_map({ radius: radius_meters, json: jSon });

    createHistoryString(historyObj);
  });

  /////////////////////////
  //
  //	ON smoking SELECT
  //
  /////////////////////////
  $body.on('click', ".smoking_option", function () {
    $this = $(this);
    if ($(".smoking_option").hasClass('ns_smoking')) {
      $(".smoking_option").addClass('smoking').removeClass('ns_smoking');

      $(".smoking_option").find('i').addClass('icon-smoking').removeClass('icon-no-smoking');

      historyObj['smoking'] = 'smoking';
    } else if ($(".smoking_option").hasClass('smoking')) {
      $(".smoking_option").addClass('no-smoking').removeClass('smoking');

      $(".smoking_option").find('i').addClass('icon-no-smoking').removeClass('icon-smoking');

      historyObj['smoking'] = 'no-smoking';
    } else if ($(".smoking_option").hasClass('no-smoking'))			// ns > yes > no
    {
      $(".smoking_option").addClass('ns_smoking').removeClass('no-smoking');

      $(".smoking_option").find('i').addClass('icon-smoking').removeClass('icon-no-smoking');

      historyObj['smoking'] = 'ns_smoking';
    }
    redraw_map({ radius: radius_meters, json: jSon });

    createHistoryString(historyObj);
  });

  /////////////////////////
  //
  //	ON property_type SELECT
  //
  /////////////////////////
  $refinements.on('change', "#prop_type [type=checkbox]", function () {
    $this = $(this);
    if ($('#prop_type [type=checkbox]:checked').length == 0) {
      $('#prop_type [type=checkbox]').prop('checked', true);
    }


    var l = $('#prop_type [type=checkbox]').length;
    for (var i = 0; i < l; i++) {
      $this = $('#prop_type [type=checkbox]').eq(i);
      var propIndex = propTypesSelected.indexOf(Number($this.val()));
      if ($this.is(':checked')) {
        if (propIndex < 0)
          propTypesSelected.push(Number($this.val()));
      } else {
        if (propIndex >= 0)
          propTypesSelected.splice(propIndex, 1);
      }
    }

    redraw_map({ radius: radius_meters, json: jSon });
  });


  $body.on('change', 'select[title=Sort]', function () {
    if (this.value !== '') {
      order_listings = this.value;
      ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('5977 show_listings --------------------------------------------------------');
      show_listings({ str: listing_ids, orderby: order_listings, offset: '', clear: true });
    }
  });

  // PRICE Slider
  $("#priceSlider").slider(
    {
      range: true,
      min: 0,
      max: 2000,
      values: [0, 200000],
      slide: function (event, ui) {
        $("#priceSliderValue").val("$" + ui.values[0] + " - $" + ui.values[1]);
      },
      stop: function (event, ui) {

        redraw_map({ radius: radius_meters, json: jSon });
        $('#priceSlider').data('min', ui.values[0])
        historyObj['price'] = "minPrice" + ui.values[0] + ",maxPrice" + ui.values[1];
        createHistoryString(historyObj);
      }
    });
  $("#priceSliderValue").val("$" + $("#priceSlider").slider("values", 0) + " - $" + $("#priceSlider").slider("values", 1));

  /////////////////////////
  //
  //	Check All
  //
  /////////////////////////
  $('.checkall').click(function () {

    var item = $(this).data('check');

    $('#' + item + ' .refineoption').each(function () {
      $this = $(this).children('input');
      if ($this.not(':checked')) {
        $this.prop('checked', true);
      }
    });

    var l = $('#' + item + ' [type=checkbox]').length;
    if (item == 'prop_type') {
      for (var i = 0; i < l; i++) {
        $this = $('#' + item + ' [type=checkbox]').eq(i);
        var propIndex = propTypesSelected.indexOf(Number($this.val()));
        if ($this.is(':checked')) {
          if (propIndex < 0)
            propTypesSelected.push(Number($this.val()));
        } else {
          if (propIndex >= 0)
            propTypesSelected.splice(propIndex, 1);
        }
      }
    }

    redraw_map({ radius: radius_meters, json: jSon });
  });

  /////////////////////////
  //
  //	Uncheck All
  //
  /////////////////////////
  $('.uncheckall').click(function () {
    var item = $(this).data('check');

    $('#' + item + ' .refineoption').each(function () {
      $this = $(this).children('input');
      if ($this.is(':checked')) {
        $this.prop('checked', false);
      }
    });

    var l = $('#' + item + ' [type=checkbox]').length;
    if (item == 'prop_type') {
      for (var i = 0; i < l; i++) {
        $this = $('#' + item + ' [type=checkbox]').eq(i);
        var propIndex = propTypesSelected.indexOf(Number($this.val()));
        if ($this.is(':checked')) {
          if (propIndex < 0)
            propTypesSelected.push(Number($this.val()));
        } else {
          if (propIndex >= 0)
            propTypesSelected.splice(propIndex, 1);
        }
      }
    }

    redraw_map({ radius: radius_meters, json: jSon });
  });
});




var geocoder,
  map,
  $leftPane,
  map_canvas,
  admin_map_canvas,
  $rightPane,
  term,
  favorites = [],
  favoriteList = null,
  roommateFavoriteList = null,
  favcount,
  jSon,
  roommate_ids = '',
  zindex = 1030,
  breakpoint0 = 1600,
  breakpoint1 = 1200,
  breakpoint2 = 1024,
  breakpoint3 = 768,
  breakpoint4 = 640,
  breakpoint5 = 320,
  cntrlIsPressed = false,
  loadListings = true;

/////////////////////////////////////////////////////////
//
//  Initialize Map
/////////////////////////////////////////////////////////


var $body = $('body'),
  $search_bar = $body.find('#search_bar'),
  $document = $(document);

$document.ready(function () {
  "use strict";

  // if(debug) console.log('doc ready');
  // Start the Map is map exists
  map_canvas = document.getElementById('map-canvas');
  admin_map_canvas = document.getElementById('map_wrapper');

  // Load Google Maps if canvas exists
  if (map_canvas != null) {
    var script = document.createElement('script');
    script.src = 'https://maps.googleapis.com/maps/api/js?libraries=places,geometry&key=' + kM + '&callback=initialize';
    script.asnyc = 'true';
    script.defer = 'true';
    var domel = document.getElementById('script-main-min-js');
    domel.parentNode.insertBefore(script, domel);

  } else if (admin_map_canvas != null) {
    var script = document.createElement('script');
    script.src = 'https://maps.googleapis.com/maps/api/js?libraries=places,geometry&key=' + kM + '&callback=initialize';
    script.asnyc = 'true';
    script.defer = 'true';
    var domel = document.getElementById('script-main-min-js');
    domel.parentNode.insertBefore(script, domel);
  }

  $leftPane = $('[role=PaneView][data-type=static][data-position=left]');
  $rightPane = $('[role=PaneView][data-type=static][data-position=right]');

  $('[data-toggle=popover]').popover({
    trigger: 'focus'
  })

  /////////////////////////////////////////////////////////
  //
  // IF POPUP IS ALREADY SET ON PAGE
  //
  ////////////////////////////////////////////////////////
  if ($('aside[role="PopupView"]').length > 0) {
    var popID = $('aside[role="PopupView"]').attr('id');
    openPopup({ url: popID });
  }

  if ($('aside[role="PopupView"]').length > 0) {
    var popID = $('aside[role="PopupView"]').attr('id');
    openPopup({ url: popID });
  }

  if ($('#listing-gallery-panel, #roommate-gallery-panel').length > 0) {
    if ($(window).width() < 768) {
      $('#listing-gallery-panel, #roommate-gallery-panel').carousel();
    }
  }

  $(window).on('resize', function () {
    if ($('#listing-gallery-panel, #roommate-gallery-panel').length > 0) {
      if ($(window).width() < 769) {
        $('#listing-gallery-panel, #roommate-gallery-panel').carousel();
      } else {
        ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('dispose', $('#listing-gallery-panel').carousel('dispose'));
        $('#listing-gallery-panel').carousel('dispose');
        $('#roommate-gallery-panel').carousel('dispose');
      }
    }
  })

  /////////////////////////////
  //
  //	Add to Favorites
  //
  /////////////////////////////
  $('body').on('click', '.add-to-favorites', function () {
    if (typeof $(this).data('listing') != 'undefined') {
      addToFavorites($(this).data('listing'), 'listing');
    } else if (typeof $(this).data('roommate') != 'undefined') {
      addToFavorites($(this).data('roommate'), 'roommate');
    }
  });
  $('body').on('click', '.remove-from-favorites', function () {
    if (typeof $(this).data('listing') != 'undefined') {
      removeFromFavorites($(this).data('listing'), 'listing');
    } else if (typeof $(this).data('roommate') != 'undefined') {
      removeFromFavorites($(this).data('roommate'), 'roommate');
    }
  });

  /////////////////////////////////////////////////////////
  //
  // FIX TAPPING AUTOCOMPLETE ITEM ON MOBILE
  //
  /////////////////////////////////////////////////////////
  $body.on('touchstart', '.ui-autocomplete li.ui-menu-item', function () {

    var $item = $(this),
      $container = $item.closest('.ui-autocomplete');


    //if we haven't closed the result box like we should have, simulate a click on the element they tapped on.
    function fixitifitneedsit() {
      if ($container.is(':visible') && $item.hasClass('ui-state-focus')) {

        $item.trigger('click');
        return true; // it needed it
      }
      return false; // it didn't
    }

    setTimeout(function () {
      if (!fixitifitneedsit()) {
        setTimeout(fixitifitneedsit, 600);
      }
    }, 600);
  });


  // if Roommate Loader exists
  if ($('#roommate-load').length > 0) {
    console.log('Roommate -load 1')
    openAlert({});

    var urlParams = new URLSearchParams(window.location.search);

    ////2023-07-18 : if (user_ip == '108.180.234.14') console.log(urlParams);
    if (typeof urlParams != 'undefined') {

    }
    var sex = parseInt(urlParams.get('sex')),
      program = parseInt(urlParams.get('program')),
      age = parseInt(urlParams.get('age')),
      occupation = parseInt(urlParams.get('occupation')),
      htype = parseInt(urlParams.get('htype')),
      smoking = parseInt(urlParams.get('smoking')),
      rent = parseInt(urlParams.get('rent')),
      distance = parseInt(urlParams.get('distance')),
      pets = parseInt(urlParams.get('pets')),
      sharing = parseInt(urlParams.get('sharing')),
      activity = parseInt(urlParams.get('activity')),
      hours = parseInt(urlParams.get('hours')),
      socially = parseInt(urlParams.get('socially')),
      diet = parseInt(urlParams.get('diet'));
    var data = {
      sex: sex,
      program: program,
      age: age,
      occupation: occupation,
      htype: htype,
      smoking: smoking,
      rent: rent,
      distance: distance,
      pets: pets,
      sharing: sharing,
      activity: activity,
      hours: hours,
      socially: socially,
      diet: diet
    };
    console.log(data);
    $.post("/__inc/includes/get_roommates.php", data)
      .done(function (str) {
        var jSon = jQuery.parseJSON(str),
          roommate_ids = '',
          comma = '';

        for (var a = 0; a < jSon.length; a++) {
          roommate_ids += comma + jSon[a].id; comma = ',';
        }
        show_roommates({ str: roommate_ids, container: '#roommate-load', orderby: '', offset: 0 });
      })
      .fail(
        function () {
          openAlert({ remove: true });
        }
      );
  }

  /////////////////////////////////////////////////////////
  //
  // Switch between left and right view on mobile
  //
  /////////////////////////////////////////////////////////

  $body.on('click touchend', '#listings-map-view [role=PanelView][data-type=static][data-position=left]', function (event) {
    $leftPane = $('#listings-map-view [role=PanelView][data-type=static][data-position=left]', 'body');
    $rightPane = $('#listings-map-view [role=PanelView][data-type=static][data-position=right]', 'body');
    if (window.innerWidth <= 769) {
      slidePanel({
        pane: $leftPane,
        open: true,
        property: 'marginLeft'
      });
      slidePanel({
        pane: $rightPane,
        open: false,
        property: 'marginRight'
      });
    }
  });

  $body.on('click touchend', '#listings-map-view [role=PanelView][data-type=static][data-position=right]', function (event) {
    $leftPane = $('#listings-map-view [role=PanelView][data-type=static][data-position=left]', 'body');
    $rightPane = $('#listings-map-view [role=PanelView][data-type=static][data-position=right]', 'body');

    if (window.innerWidth <= 769) {
      slidePanel({
        pane: $leftPane,
        open: false,
        property: 'marginLeft'
      });
      slidePanel({
        pane: $rightPane,
        open: true,
        property: 'marginRight'
      });
    }
  });


  ///////////////////////////
  //
  //	FORM SUBMISSION
  //
  //////////////////////////

  $body.on('click', '[data-rel=action]', function (e) {
    e.preventDefault();

    var formURL = $(this).attr("href");

    formURL = '/__inc/actions/' + formURL;

    if (formURL.indexOf('.php') !== false) {
      formURL += '.php';
    }

    $.ajax(
      {
        url: formURL,
        type: 'GET',
        success: function (data, textStatus, jqXHR) {
          var actiondata = JSON.parse(data),
            duration = actiondata.alert.duration || false;

          if (actiondata.alert) {
            openAlert({ message: actiondata.alert.message, icon: actiondata.alert.icon, duration: duration });
          }
          if (actiondata.panel) {
            get_panel({ id: actiondata.panel.id, url: actiondata.panel.id, type: actiondata.panel.type, position: actiondata.panel.position });
          }
          if (actiondata.action) {
            executeFunctionByName(actiondata.action, window);
          }
        },
        error: function (jqXHR, textStatus, errorThrown) {
          openAlert({ message: 'There was an error with your request', icon: 'exclamation' });
        }
      });
  });

  ///////////////////////////
  //
  //	search_area
  //
  //////////////////////////

  $body.on('click', '.expand_main_search_box', function (e) {
    e.preventDefault();

    $(".main_search_box").removeClass("d-none");
    $(".expand_main_search_box").hide();
    $(".expand_main_search_box").parent().find('form#search_bar #loc_search').focus();
  });

  /////////////////////////////////////////////////////////
  //
  // FAVORITES
  //
  /////////////////////////////////////////////////////////

  //Add class to favorites
  var delayFavoritesLoad = setTimeout(function () {
    if (localStorage.getItem('favorites') !== null) {
      favoriteList = localStorage.getItem('favorites');
      $('[data-count]').html(favcount);
      updateFavorites(favoriteList, 'listing');
    }
    if (localStorage.getItem('roommate-favorites') !== null) {
      roommateFavoriteList = localStorage.getItem('roommate-favorites');
      $('[data-count]').html(favcount);
      updateFavorites(roommateFavoriteList, 'roommate');
    }

    clearTimeout(delayFavoritesLoad);
  }, 3000);

  var refreshButton = document.querySelector(".refresh-captcha");
  if (refreshButton !== null) {
    refreshButton.onclick = function () {
      document.querySelector(".captcha-image").src = '/__inc/includes/captcha.php?' + Date.now();
    }
  }
});

function callPhone(contact) {
  contact = contact.replace('(', '');
  contact = contact.replace(')', '');
  contact = contact.replace('-', '');
  contact = contact.replace(' ', '');
  if (navigator.platform == 'MacIntel') {
    window.location.href = 'facetime:' + contact;
  } else {
    window.location.href = 'tel:+1' + contact;
  }

  //return false;
}
/////////////////////////////////////////////////////////
//
//  Initiate Geolocation
//
/////////////////////////////////////////////////////////
function handle_errors(error) {
  console.log(error);
  switch (error.code) {
    case error.PERMISSION_DENIED: console.log("user did not share geolocation data");
      break;

    case error.POSITION_UNAVAILABLE: console.log("could not detect current position");
      break;

    case error.TIMEOUT: console.log("retrieving position timed out!");
      break;

    default: console.log("unknown error");
      break;
  }
}

/**
 * handle_geolocation_query function.
 *
 * @access public
 * @param mixed position
 * @return void
 */
function handle_geolocation_query(position) {
  console.log('handle_geolocation_query')
  console.log(position)
  if (map) {

    mygeolat = position.coords.latitude;
    mygeolong = position.coords.longitude;
    bounds = position.hasOwnProperty('bounds') ? position.bounds : false;
    localStorage.setItem('mygeolat', mygeolat);
    localStorage.setItem('mygeolong', mygeolong);

    //codeLatLng(mygeolat, mygeolong);
    $map_canvas = $('#map-canvas');

    //////////////////////
    // FROM RADIUS MAP
    //////////////////////
    if ($('#listings').length === 0) {
      get_panel({ id: 'listings', url: 'listings', type: 'static', position: 'left' });
    }

    mapCenter = new google.maps.LatLng(mygeolat, mygeolong);

    //remove home_panel
    get_panel({ id: 'gmap', type: 'static', position: 'right' });
    map.setCenter(mapCenter);

    if (bounds) map.fitBounds(bounds);

    add_drag_marker(mygeolat, mygeolong);

  } else {
    setTimeout(function () {
      handle_geolocation_query(position);
    }, 2000);
  }
}

/**
 * handle_geolocation_query function.
 *
 * @access public
 * @param mixed position
 * @return void
 */
function handle_geolocation_queryAddress(position) {
  console.log('handle_geolocation_queryAddress')
  console.log(position)
  if (map) {
    decodeLatLong(position.coords.latitude, position.coords.longitude)
  } else {
    setTimeout(function () {
      handle_geolocation_query(position);
    }, 2000);
  }
}


/**
 * accept object { position.coords.latitude, position.coords.longitude }
 * */
function decodeLatLong(lat, lng) {
  var geocoder = new google.maps.Geocoder()

  geocoder.geocode({ location: { lat: lat, lng: lng } }, function (results, status) {
    if (status === 'OK') {
      var url = '?search=' + results[0].formatted_address;
      // console.log(results[0].formatted_address)
      history.pushState({}, url, url);
      window.location.reload()
    }
  })
}

/**
 * initiate_geolocation function.
 *
 * @access public
 * @return void
 */
function initiate_geolocation() {
  openAlert({});
  //geocoder = new google.maps.Geocoder();
  navigator.geolocation.getCurrentPosition(handle_geolocation_query, handle_errors);
  //return false;
}

/**
 * initiate_geolocation function.
 *
 * @access public
 * @return void
 */
function initiate_geolocationChangeAddress() {
  openAlert({});
  //geocoder = new google.maps.Geocoder();
  navigator.geolocation.getCurrentPosition(handle_geolocation_queryAddress, handle_errors);
  //return false;
}

//////////////////////////////////////////////////////////////
//
//	Code Lat and Long
//
//////////////////////////////////////////////////////////////
function codeLatLng(lat, lng) {
  var latlng = new google.maps.LatLng(lat, lng);
  geocoder.geocode({
    'latLng': latlng
  }, function (results, status) {
    var req_data = '';
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[0]) {
        var city, state;

        for (var i = 0; i < results[0].address_components.length; i++) {
          if (results[0].address_components[i].types[0] == 'locality') {
            var city = results[0].address_components[i].long_name;
            req_data = city;
          } else if (results[0].address_components[i].types[0] == 'administrative_area_level_1') {
            var state = results[0].address_components[i].long_name;
          }
        }
        localStorage.setItem('mycity', city);

        var opts = {
          str: req_data,
          type: 'city'
        };
      } else {
        openAlert({ message: 'No results found', icon: 'frown-o' });
      }
    } else {
      openAlert({ message: 'Geocoder failed due to: ' + status, icon: 'exclamation-circle' });
    }
  });
}

/**
 * codeAddress function.
 *
 * @access public
 * @param mixed args
 * @return void
 */
function codeAddress(args) {
  if (map) {
    ////2023-07-18 : if (user_ip == '108.180.234.14') console.log('codeAddress', args);
    var address = args.address || null;

    loadListings = args.loadListings || false;

    if (typeof geocoder == 'undefined')
      geocoder = new google.maps.Geocoder();

    geocoder.geocode({ 'address': address }, function (results, status) {
      ////2023-07-18 : if (user_ip == '108.180.234.14') console.log(results, status);
      if (status == google.maps.GeocoderStatus.OK) {
        openAlert({ remove: true });

        places = results[0];
        var lct = places.geometry.location_type;
        var bounds = places.geometry.bounds;

        var lat = results[0].geometry.location.lat();
        var long = results[0].geometry.location.lng();
        var position = { coords: { latitude: lat, longitude: long }, bounds: bounds, location_type: lct };
        window.position = position;
        if (loadListings) {
          handle_geolocation_query(position);
        } else {
          /////////////////////
          ////2023-07-18 : if (user_ip == '108.180.234.14') console.log(position);

          mygeolat = position.coords.latitude;
          mygeolong = position.coords.longitude;
          bounds = position.bounds;
          //////////////////////
          // FROM RADIUS MAP
          //////////////////////
          mapCenter = new google.maps.LatLng(mygeolat, mygeolong);
          if (typeof bounds != 'undefined') map.fitBounds(bounds);
          map.setCenter(mapCenter);

          if (bounds) map.fitBounds(bounds);

          add_drag_marker(mygeolat, mygeolong);
        }

      }
    });
  } else {
    setTimeout(function () {
      codeAddress(args);
    }, 500);
  }
}

/////////////////////////////
//
//	Hide Search Bar on Scroll
//
/////////////////////////////
if ($('#start_search').length == 0) {
  $('#Home').scroll(function () {
    var scrollpos = $('#Home').scrollTop();

    if (scrollpos > 300) {
      $('#search_bar').css('display', 'none');
    }
    else {
      $('#search_bar').css('display', 'block');
    }
  });
}

/////////////////////////////
//
//	Home Page Popup - Template sites
//
/////////////////////////////
$(document).ready(function () {
  if (typeof is_template !== 'undefined' && is_template == true && box_6 == true) {
    var popup = false
    var allcookies = document.cookie;
    var cookiearray = allcookies.split(';');
    var total = 0;

    for (var i = 0; i < cookiearray.length; i++) {
      var name = cookiearray[i].split('=')[0];
      var value = cookiearray[i].split('=')[1];
      if (name.trim() == 'popup' && value == 'true') {
        popup = true;
      }
    }

    if (popup == false) {
      var modal = document.getElementById("box_6_overlay");
      modal.style.visibility = "visible";
    }
  }

  $(window).on('popstate', function (e) {

    var state = e.originalEvent.state;
    if (state !== null) {
      //load content with ajax
      location.reload();
    }
  });

  // Enable Tooltips
  $('[data-toggle="tooltip"]').tooltip();
  $('.selectpicker').selectpicker();
});

function set_cookie() {
  var now = new Date();
  now.setHours(now.getHours() + 12);
  document.cookie = "popup=true;expires=" + now.toUTCString() + ";path=/;secure";

  var modal = document.getElementById("box_6_overlay");
  modal.style.visibility = "hidden";
}
