(function(factory){
if(typeof module==='object'&&module.exports){
module.exports=factory();
}else{
window.intlTelInput=factory();
}}(()=> {
var factoryOutput=(()=> {
var __defProp=Object.defineProperty;
var __getOwnPropDesc=Object.getOwnPropertyDescriptor;
var __getOwnPropNames=Object.getOwnPropertyNames;
var __hasOwnProp=Object.prototype.hasOwnProperty;
var __export=(target, all)=> {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps=(to, from, except, desc)=> {
if(from&&typeof from==="object"||typeof from==="function"){
for (let key of __getOwnPropNames(from))
if(!__hasOwnProp.call(to, key)&&key!==except)
__defProp(to, key, { get: ()=> from[key], enumerable: !(desc=__getOwnPropDesc(from, key))||desc.enumerable });
}
return to;
};
var __toCommonJS=(mod)=> __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var intl_tel_input_exports={};
__export(intl_tel_input_exports, {
Iti: ()=> Iti,
default: ()=> intl_tel_input_default
});
var rawCountryData=[
[
"af",
"93"
],
[
"ax",
"358",
1
],
[
"al",
"355"
],
[
"dz",
"213"
],
[
"as",
"1",
5,
["684"]
],
[
"ad",
"376"
],
[
"ao",
"244"
],
[
"ai",
"1",
6,
["264"]
],
[
"ag",
"1",
7,
["268"]
],
[
"ar",
"54"
],
[
"am",
"374"
],
[
"aw",
"297"
],
[
"ac",
"247"
],
[
"au",
"61",
0,
null,
"0"
],
[
"at",
"43"
],
[
"az",
"994"
],
[
"bs",
"1",
8,
["242"]
],
[
"bh",
"973"
],
[
"bd",
"880"
],
[
"bb",
"1",
9,
["246"]
],
[
"by",
"375"
],
[
"be",
"32"
],
[
"bz",
"501"
],
[
"bj",
"229"
],
[
"bm",
"1",
10,
["441"]
],
[
"bt",
"975"
],
[
"bo",
"591"
],
[
"ba",
"387"
],
[
"bw",
"267"
],
[
"br",
"55"
],
[
"io",
"246"
],
[
"vg",
"1",
11,
["284"]
],
[
"bn",
"673"
],
[
"bg",
"359"
],
[
"bf",
"226"
],
[
"bi",
"257"
],
[
"kh",
"855"
],
[
"cm",
"237"
],
[
"ca",
"1",
1,
["204", "226", "236", "249", "250", "263", "289", "306", "343", "354", "365", "367", "368", "382", "387", "403", "416", "418", "428", "431", "437", "438", "450", "584", "468", "474", "506", "514", "519", "548", "579", "581", "584", "587", "604", "613", "639", "647", "672", "683", "705", "709", "742", "753", "778", "780", "782", "807", "819", "825", "867", "873", "879", "902", "905"]
],
[
"cv",
"238"
],
[
"bq",
"599",
1,
["3", "4", "7"]
],
[
"ky",
"1",
12,
["345"]
],
[
"cf",
"236"
],
[
"td",
"235"
],
[
"cl",
"56"
],
[
"cn",
"86"
],
[
"cx",
"61",
2,
["89164"],
"0"
],
[
"cc",
"61",
1,
["89162"],
"0"
],
[
"co",
"57"
],
[
"km",
"269"
],
[
"cg",
"242"
],
[
"cd",
"243"
],
[
"ck",
"682"
],
[
"cr",
"506"
],
[
"ci",
"225"
],
[
"hr",
"385"
],
[
"cu",
"53"
],
[
"cw",
"599",
0
],
[
"cy",
"357"
],
[
"cz",
"420"
],
[
"dk",
"45"
],
[
"dj",
"253"
],
[
"dm",
"1",
13,
["767"]
],
[
"do",
"1",
2,
["809", "829", "849"]
],
[
"ec",
"593"
],
[
"eg",
"20"
],
[
"sv",
"503"
],
[
"gq",
"240"
],
[
"er",
"291"
],
[
"ee",
"372"
],
[
"sz",
"268"
],
[
"et",
"251"
],
[
"fk",
"500"
],
[
"fo",
"298"
],
[
"fj",
"679"
],
[
"fi",
"358",
0
],
[
"fr",
"33"
],
[
"gf",
"594"
],
[
"pf",
"689"
],
[
"ga",
"241"
],
[
"gm",
"220"
],
[
"ge",
"995"
],
[
"de",
"49"
],
[
"gh",
"233"
],
[
"gi",
"350"
],
[
"gr",
"30"
],
[
"gl",
"299"
],
[
"gd",
"1",
14,
["473"]
],
[
"gp",
"590",
0
],
[
"gu",
"1",
15,
["671"]
],
[
"gt",
"502"
],
[
"gg",
"44",
1,
["1481", "7781", "7839", "7911"],
"0"
],
[
"gn",
"224"
],
[
"gw",
"245"
],
[
"gy",
"592"
],
[
"ht",
"509"
],
[
"hn",
"504"
],
[
"hk",
"852"
],
[
"hu",
"36"
],
[
"is",
"354"
],
[
"in",
"91"
],
[
"id",
"62"
],
[
"ir",
"98"
],
[
"iq",
"964"
],
[
"ie",
"353"
],
[
"im",
"44",
2,
["1624", "74576", "7524", "7924", "7624"],
"0"
],
[
"il",
"972"
],
[
"it",
"39",
0
],
[
"jm",
"1",
4,
["876", "658"]
],
[
"jp",
"81"
],
[
"je",
"44",
3,
["1534", "7509", "7700", "7797", "7829", "7937"],
"0"
],
[
"jo",
"962"
],
[
"kz",
"7",
1,
["33", "7"],
"8"
],
[
"ke",
"254"
],
[
"ki",
"686"
],
[
"xk",
"383"
],
[
"kw",
"965"
],
[
"kg",
"996"
],
[
"la",
"856"
],
[
"lv",
"371"
],
[
"lb",
"961"
],
[
"ls",
"266"
],
[
"lr",
"231"
],
[
"ly",
"218"
],
[
"li",
"423"
],
[
"lt",
"370"
],
[
"lu",
"352"
],
[
"mo",
"853"
],
[
"mg",
"261"
],
[
"mw",
"265"
],
[
"my",
"60"
],
[
"mv",
"960"
],
[
"ml",
"223"
],
[
"mt",
"356"
],
[
"mh",
"692"
],
[
"mq",
"596"
],
[
"mr",
"222"
],
[
"mu",
"230"
],
[
"yt",
"262",
1,
["269", "639"],
"0"
],
[
"mx",
"52"
],
[
"fm",
"691"
],
[
"md",
"373"
],
[
"mc",
"377"
],
[
"mn",
"976"
],
[
"me",
"382"
],
[
"ms",
"1",
16,
["664"]
],
[
"ma",
"212",
0,
null,
"0"
],
[
"mz",
"258"
],
[
"mm",
"95"
],
[
"na",
"264"
],
[
"nr",
"674"
],
[
"np",
"977"
],
[
"nl",
"31"
],
[
"nc",
"687"
],
[
"nz",
"64"
],
[
"ni",
"505"
],
[
"ne",
"227"
],
[
"ng",
"234"
],
[
"nu",
"683"
],
[
"nf",
"672"
],
[
"kp",
"850"
],
[
"mk",
"389"
],
[
"mp",
"1",
17,
["670"]
],
[
"no",
"47",
0
],
[
"om",
"968"
],
[
"pk",
"92"
],
[
"pw",
"680"
],
[
"ps",
"970"
],
[
"pa",
"507"
],
[
"pg",
"675"
],
[
"py",
"595"
],
[
"pe",
"51"
],
[
"ph",
"63"
],
[
"pl",
"48"
],
[
"pt",
"351"
],
[
"pr",
"1",
3,
["787", "939"]
],
[
"qa",
"974"
],
[
"re",
"262",
0,
null,
"0"
],
[
"ro",
"40"
],
[
"ru",
"7",
0,
null,
"8"
],
[
"rw",
"250"
],
[
"ws",
"685"
],
[
"sm",
"378"
],
[
"st",
"239"
],
[
"sa",
"966"
],
[
"sn",
"221"
],
[
"rs",
"381"
],
[
"sc",
"248"
],
[
"sl",
"232"
],
[
"sg",
"65"
],
[
"sx",
"1",
21,
["721"]
],
[
"sk",
"421"
],
[
"si",
"386"
],
[
"sb",
"677"
],
[
"so",
"252"
],
[
"za",
"27"
],
[
"kr",
"82"
],
[
"ss",
"211"
],
[
"es",
"34"
],
[
"lk",
"94"
],
[
"bl",
"590",
1
],
[
"sh",
"290"
],
[
"kn",
"1",
18,
["869"]
],
[
"lc",
"1",
19,
["758"]
],
[
"mf",
"590",
2
],
[
"pm",
"508"
],
[
"vc",
"1",
20,
["784"]
],
[
"sd",
"249"
],
[
"sr",
"597"
],
[
"sj",
"47",
1,
["79"]
],
[
"se",
"46"
],
[
"ch",
"41"
],
[
"sy",
"963"
],
[
"tw",
"886"
],
[
"tj",
"992"
],
[
"tz",
"255"
],
[
"th",
"66"
],
[
"tl",
"670"
],
[
"tg",
"228"
],
[
"tk",
"690"
],
[
"to",
"676"
],
[
"tt",
"1",
22,
["868"]
],
[
"tn",
"216"
],
[
"tr",
"90"
],
[
"tm",
"993"
],
[
"tc",
"1",
23,
["649"]
],
[
"tv",
"688"
],
[
"ug",
"256"
],
[
"ua",
"380"
],
[
"ae",
"971"
],
[
"gb",
"44",
0,
null,
"0"
],
[
"us",
"1",
0
],
[
"uy",
"598"
],
[
"vi",
"1",
24,
["340"]
],
[
"uz",
"998"
],
[
"vu",
"678"
],
[
"va",
"39",
1,
["06698"]
],
[
"ve",
"58"
],
[
"vn",
"84"
],
[
"wf",
"681"
],
[
"eh",
"212",
1,
["5288", "5289"],
"0"
],
[
"ye",
"967"
],
[
"zm",
"260"
],
[
"zw",
"263"
]
];
var allCountries=[];
for (let i=0; i < rawCountryData.length; i++){
const c=rawCountryData[i];
allCountries[i]={
name: "",
iso2: c[0],
dialCode: c[1],
priority: c[2]||0,
areaCodes: c[3]||null,
nodeById: {},
nationalPrefix: c[4]||null
};}
var data_default=allCountries;
var countryTranslations={
ad: "Andorra",
ae: "United Arab Emirates",
af: "Afghanistan",
ag: "Antigua & Barbuda",
ai: "Anguilla",
al: "Albania",
am: "Armenia",
ao: "Angola",
ar: "Argentina",
as: "American Samoa",
at: "Austria",
au: "Australia",
aw: "Aruba",
ax: "\xC5land Islands",
az: "Azerbaijan",
ba: "Bosnia & Herzegovina",
bb: "Barbados",
bd: "Bangladesh",
be: "Belgium",
bf: "Burkina Faso",
bg: "Bulgaria",
bh: "Bahrain",
bi: "Burundi",
bj: "Benin",
bl: "St. Barth\xE9lemy",
bm: "Bermuda",
bn: "Brunei",
bo: "Bolivia",
bq: "Caribbean Netherlands",
br: "Brazil",
bs: "Bahamas",
bt: "Bhutan",
bw: "Botswana",
by: "Belarus",
bz: "Belize",
ca: "Canada",
cc: "Cocos (Keeling) Islands",
cd: "Congo - Kinshasa",
cf: "Central African Republic",
cg: "Congo - Brazzaville",
ch: "Switzerland",
ci: "C\xF4te d\u2019Ivoire",
ck: "Cook Islands",
cl: "Chile",
cm: "Cameroon",
cn: "China",
co: "Colombia",
cr: "Costa Rica",
cu: "Cuba",
cv: "Cape Verde",
cw: "Cura\xE7ao",
cx: "Christmas Island",
cy: "Cyprus",
cz: "Czechia",
de: "Germany",
dj: "Djibouti",
dk: "Denmark",
dm: "Dominica",
do: "Dominican Republic",
dz: "Algeria",
ec: "Ecuador",
ee: "Estonia",
eg: "Egypt",
eh: "Western Sahara",
er: "Eritrea",
es: "Spain",
et: "Ethiopia",
fi: "Finland",
fj: "Fiji",
fk: "Falkland Islands",
fm: "Micronesia",
fo: "Faroe Islands",
fr: "France",
ga: "Gabon",
gb: "United Kingdom",
gd: "Grenada",
ge: "Georgia",
gf: "French Guiana",
gg: "Guernsey",
gh: "Ghana",
gi: "Gibraltar",
gl: "Greenland",
gm: "Gambia",
gn: "Guinea",
gp: "Guadeloupe",
gq: "Equatorial Guinea",
gr: "Greece",
gt: "Guatemala",
gu: "Guam",
gw: "Guinea-Bissau",
gy: "Guyana",
hk: "Hong Kong SAR China",
hn: "Honduras",
hr: "Croatia",
ht: "Haiti",
hu: "Hungary",
id: "Indonesia",
ie: "Ireland",
il: "Israel",
im: "Isle of Man",
in: "India",
io: "British Indian Ocean Territory",
iq: "Iraq",
ir: "Iran",
is: "Iceland",
it: "Italy",
je: "Jersey",
jm: "Jamaica",
jo: "Jordan",
jp: "Japan",
ke: "Kenya",
kg: "Kyrgyzstan",
kh: "Cambodia",
ki: "Kiribati",
km: "Comoros",
kn: "St. Kitts & Nevis",
kp: "North Korea",
kr: "South Korea",
kw: "Kuwait",
ky: "Cayman Islands",
kz: "Kazakhstan",
la: "Laos",
lb: "Lebanon",
lc: "St. Lucia",
li: "Liechtenstein",
lk: "Sri Lanka",
lr: "Liberia",
ls: "Lesotho",
lt: "Lithuania",
lu: "Luxembourg",
lv: "Latvia",
ly: "Libya",
ma: "Morocco",
mc: "Monaco",
md: "Moldova",
me: "Montenegro",
mf: "St. Martin",
mg: "Madagascar",
mh: "Marshall Islands",
mk: "North Macedonia",
ml: "Mali",
mm: "Myanmar (Burma)",
mn: "Mongolia",
mo: "Macao SAR China",
mp: "Northern Mariana Islands",
mq: "Martinique",
mr: "Mauritania",
ms: "Montserrat",
mt: "Malta",
mu: "Mauritius",
mv: "Maldives",
mw: "Malawi",
mx: "Mexico",
my: "Malaysia",
mz: "Mozambique",
na: "Namibia",
nc: "New Caledonia",
ne: "Niger",
nf: "Norfolk Island",
ng: "Nigeria",
ni: "Nicaragua",
nl: "Netherlands",
no: "Norway",
np: "Nepal",
nr: "Nauru",
nu: "Niue",
nz: "New Zealand",
om: "Oman",
pa: "Panama",
pe: "Peru",
pf: "French Polynesia",
pg: "Papua New Guinea",
ph: "Philippines",
pk: "Pakistan",
pl: "Poland",
pm: "St. Pierre & Miquelon",
pr: "Puerto Rico",
ps: "Palestinian Territories",
pt: "Portugal",
pw: "Palau",
py: "Paraguay",
qa: "Qatar",
re: "R\xE9union",
ro: "Romania",
rs: "Serbia",
ru: "Russia",
rw: "Rwanda",
sa: "Saudi Arabia",
sb: "Solomon Islands",
sc: "Seychelles",
sd: "Sudan",
se: "Sweden",
sg: "Singapore",
sh: "St. Helena",
si: "Slovenia",
sj: "Svalbard & Jan Mayen",
sk: "Slovakia",
sl: "Sierra Leone",
sm: "San Marino",
sn: "Senegal",
so: "Somalia",
sr: "Suriname",
ss: "South Sudan",
st: "S\xE3o Tom\xE9 & Pr\xEDncipe",
sv: "El Salvador",
sx: "Sint Maarten",
sy: "Syria",
sz: "Eswatini",
tc: "Turks & Caicos Islands",
td: "Chad",
tg: "Togo",
th: "Thailand",
tj: "Tajikistan",
tk: "Tokelau",
tl: "Timor-Leste",
tm: "Turkmenistan",
tn: "Tunisia",
to: "Tonga",
tr: "Turkey",
tt: "Trinidad & Tobago",
tv: "Tuvalu",
tw: "Taiwan",
tz: "Tanzania",
ua: "Ukraine",
ug: "Uganda",
us: "United States",
uy: "Uruguay",
uz: "Uzbekistan",
va: "Vatican City",
vc: "St. Vincent & Grenadines",
ve: "Venezuela",
vg: "British Virgin Islands",
vi: "U.S. Virgin Islands",
vn: "Vietnam",
vu: "Vanuatu",
wf: "Wallis & Futuna",
ws: "Samoa",
ye: "Yemen",
yt: "Mayotte",
za: "South Africa",
zm: "Zambia",
zw: "Zimbabwe"
};
var countries_default=countryTranslations;
var interfaceTranslations={
selectedCountryAriaLabel: "Selected country",
noCountrySelected: "No country selected",
countryListAriaLabel: "List of countries",
searchPlaceholder: "Search",
zeroSearchResults: "No results found",
oneSearchResult: "1 result found",
multipleSearchResults: "${count} results found",
ac: "Ascension Island",
xk: "Kosovo"
};
var interface_default=interfaceTranslations;
var allTranslations={ ...countries_default, ...interface_default };
var en_default=allTranslations;
for (let i=0; i < data_default.length; i++){
data_default[i].name=en_default[data_default[i].iso2];
}
var id=0;
var defaults={
allowDropdown: true,
autoPlaceholder: "polite",
containerClass: "",
countryOrder: null,
countrySearch: true,
customPlaceholder: null,
dropdownContainer: null,
excludeCountries: [],
fixDropdownWidth: true,
formatAsYouType: true,
formatOnDisplay: true,
geoIpLookup: null,
hiddenInput: null,
i18n: {},
initialCountry: "",
loadUtils: null,
nationalMode: true,
onlyCountries: [],
placeholderNumberType: "MOBILE",
showFlags: true,
separateDialCode: false,
strictMode: false,
useFullscreenPopup: typeof navigator!=="undefined"&&typeof window!=="undefined" ? (
/Android.+Mobile|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent
)||window.innerWidth <=500
):false,
validationNumberTypes: ["MOBILE"]
};
var regionlessNanpNumbers=[
"800",
"822",
"833",
"844",
"855",
"866",
"877",
"880",
"881",
"882",
"883",
"884",
"885",
"886",
"887",
"888",
"889"
];
var getNumeric=(s)=> s.replace(/\D/g, "");
var normaliseString=(s="")=> s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
var isRegionlessNanp=(number)=> {
const numeric=getNumeric(number);
if(numeric.charAt(0)==="1"){
const areaCode=numeric.substr(1, 3);
return regionlessNanpNumbers.includes(areaCode);
}
return false;
};
var translateCursorPosition=(relevantChars, formattedValue, prevCaretPos, isDeleteForwards)=> {
if(prevCaretPos===0&&!isDeleteForwards){
return 0;
}
let count=0;
for (let i=0; i < formattedValue.length; i++){
if(/[+0-9]/.test(formattedValue[i])){
count++;
}
if(count===relevantChars&&!isDeleteForwards){
return i + 1;
}
if(isDeleteForwards&&count===relevantChars + 1){
return i;
}}
return formattedValue.length;
};
var createEl=(name, attrs, container)=> {
const el=document.createElement(name);
if(attrs){
Object.entries(attrs).forEach(([key, value])=> el.setAttribute(key, value));
}
if(container){
container.appendChild(el);
}
return el;
};
var forEachInstance=(method, ...args)=> {
const { instances }=intlTelInput;
Object.values(instances).forEach((instance)=> instance[method](...args));
};
var Iti=class {
constructor(input, customOptions={}){
this.id=id++;
this.telInput=input;
this.highlightedItem=null;
this.options=Object.assign({}, defaults, customOptions);
this.hadInitialPlaceholder=Boolean(input.getAttribute("placeholder"));
}
_init(){
if(this.options.useFullscreenPopup){
this.options.fixDropdownWidth=false;
}
if(this.options.onlyCountries.length===1){
this.options.initialCountry=this.options.onlyCountries[0];
}
if(this.options.separateDialCode){
this.options.nationalMode=false;
}
if(this.options.allowDropdown&&!this.options.showFlags&&!this.options.separateDialCode){
this.options.nationalMode=false;
}
if(this.options.useFullscreenPopup&&!this.options.dropdownContainer){
this.options.dropdownContainer=document.body;
}
this.isAndroid=typeof navigator!=="undefined" ? /Android/i.test(navigator.userAgent):false;
this.isRTL = !!this.telInput.closest("[dir=rtl]");
const showOnDefaultSide=this.options.allowDropdown||this.options.separateDialCode;
this.showSelectedCountryOnLeft=this.isRTL ? !showOnDefaultSide:showOnDefaultSide;
if(this.options.separateDialCode){
if(this.isRTL){
this.originalPaddingRight=this.telInput.style.paddingRight;
}else{
this.originalPaddingLeft=this.telInput.style.paddingLeft;
}}
this.options.i18n={ ...en_default, ...this.options.i18n };
const autoCountryPromise=new Promise((resolve, reject)=> {
this.resolveAutoCountryPromise=resolve;
this.rejectAutoCountryPromise=reject;
});
const utilsScriptPromise=new Promise((resolve, reject)=> {
this.resolveUtilsScriptPromise=resolve;
this.rejectUtilsScriptPromise=reject;
});
this.promise=Promise.all([autoCountryPromise, utilsScriptPromise]);
this.selectedCountryData={};
this._processCountryData();
this._generateMarkup();
this._setInitialState();
this._initListeners();
this._initRequests();
}
_processCountryData(){
this._processAllCountries();
this._processDialCodes();
this._translateCountryNames();
this._sortCountries();
}
_sortCountries(){
if(this.options.countryOrder){
this.options.countryOrder=this.options.countryOrder.map((country)=> country.toLowerCase());
}
this.countries.sort((a, b)=> {
const { countryOrder }=this.options;
if(countryOrder){
const aIndex=countryOrder.indexOf(a.iso2);
const bIndex=countryOrder.indexOf(b.iso2);
const aIndexExists=aIndex > -1;
const bIndexExists=bIndex > -1;
if(aIndexExists||bIndexExists){
if(aIndexExists&&bIndexExists){
return aIndex - bIndex;
}
return aIndexExists ? -1:1;
}}
return a.name.localeCompare(b.name);
});
}
_addToDialCodeMap(iso2, dialCode, priority){
if(dialCode.length > this.dialCodeMaxLen){
this.dialCodeMaxLen=dialCode.length;
}
if(!this.dialCodeToIso2Map.hasOwnProperty(dialCode)){
this.dialCodeToIso2Map[dialCode]=[];
}
for (let i=0; i < this.dialCodeToIso2Map[dialCode].length; i++){
if(this.dialCodeToIso2Map[dialCode][i]===iso2){
return;
}}
const index=priority!==void 0 ? priority:this.dialCodeToIso2Map[dialCode].length;
this.dialCodeToIso2Map[dialCode][index]=iso2;
}
_processAllCountries(){
const { onlyCountries, excludeCountries }=this.options;
if(onlyCountries.length){
const lowerCaseOnlyCountries=onlyCountries.map((country)=> country.toLowerCase()
);
this.countries=data_default.filter((country)=> lowerCaseOnlyCountries.includes(country.iso2)
);
}else if(excludeCountries.length){
const lowerCaseExcludeCountries=excludeCountries.map((country)=> country.toLowerCase()
);
this.countries=data_default.filter((country)=> !lowerCaseExcludeCountries.includes(country.iso2)
);
}else{
this.countries=data_default;
}}
_translateCountryNames(){
for (let i=0; i < this.countries.length; i++){
const iso2=this.countries[i].iso2.toLowerCase();
if(this.options.i18n.hasOwnProperty(iso2)){
this.countries[i].name=this.options.i18n[iso2];
}}
}
_processDialCodes(){
this.dialCodes={};
this.dialCodeMaxLen=0;
this.dialCodeToIso2Map={};
for (let i=0; i < this.countries.length; i++){
const c=this.countries[i];
if(!this.dialCodes[c.dialCode]){
this.dialCodes[c.dialCode]=true;
}
this._addToDialCodeMap(c.iso2, c.dialCode, c.priority);
}
for (let i=0; i < this.countries.length; i++){
const c=this.countries[i];
if(c.areaCodes){
const rootIso2Code=this.dialCodeToIso2Map[c.dialCode][0];
for (let j=0; j < c.areaCodes.length; j++){
const areaCode=c.areaCodes[j];
for (let k=1; k < areaCode.length; k++){
const partialAreaCode=areaCode.substr(0, k);
const partialDialCode=c.dialCode + partialAreaCode;
this._addToDialCodeMap(rootIso2Code, partialDialCode);
this._addToDialCodeMap(c.iso2, partialDialCode);
}
this._addToDialCodeMap(c.iso2, c.dialCode + areaCode);
}}
}}
_generateMarkup(){
this.telInput.classList.add("iti__tel-input");
if(!this.telInput.hasAttribute("autocomplete")&&!(this.telInput.form&&this.telInput.form.hasAttribute("autocomplete"))){
this.telInput.setAttribute("autocomplete", "off");
}
const {
allowDropdown,
separateDialCode,
showFlags,
containerClass,
hiddenInput,
dropdownContainer,
fixDropdownWidth,
useFullscreenPopup,
countrySearch,
i18n
}=this.options;
let parentClass="iti";
if(allowDropdown){
parentClass +=" iti--allow-dropdown";
}
if(showFlags){
parentClass +=" iti--show-flags";
}
if(containerClass){
parentClass +=` ${containerClass}`;
}
if(!useFullscreenPopup){
parentClass +=" iti--inline-dropdown";
}
const wrapper=createEl("div", { class: parentClass });
this.telInput.parentNode?.insertBefore(wrapper, this.telInput);
if(allowDropdown||showFlags||separateDialCode){
this.countryContainer=createEl(
"div",
{ class: "iti__country-container" },
wrapper
);
if(this.showSelectedCountryOnLeft){
this.countryContainer.style.left="0px";
}else{
this.countryContainer.style.right="0px";
}
if(allowDropdown){
this.selectedCountry=createEl(
"button",
{
type: "button",
class: "iti__selected-country",
"aria-expanded": "false",
"aria-label": this.options.i18n.selectedCountryAriaLabel,
"aria-haspopup": "true",
"aria-controls": `iti-${this.id}__dropdown-content`,
"role": "combobox"
},
this.countryContainer
);
if(this.telInput.disabled){
this.selectedCountry.setAttribute("disabled", "true");
}}else{
this.selectedCountry=createEl(
"div",
{ class: "iti__selected-country" },
this.countryContainer
);
}
const selectedCountryPrimary=createEl("div", { class: "iti__selected-country-primary" }, this.selectedCountry);
this.selectedCountryInner=createEl("div", { class: "iti__flag" }, selectedCountryPrimary);
this.selectedCountryA11yText=createEl(
"span",
{ class: "iti__a11y-text" },
this.selectedCountryInner
);
if(allowDropdown){
this.dropdownArrow=createEl(
"div",
{ class: "iti__arrow", "aria-hidden": "true" },
selectedCountryPrimary
);
}
if(separateDialCode){
this.selectedDialCode=createEl(
"div",
{ class: "iti__selected-dial-code" },
this.selectedCountry
);
}
if(allowDropdown){
const extraClasses=fixDropdownWidth ? "":"iti--flexible-dropdown-width";
this.dropdownContent=createEl("div", {
id: `iti-${this.id}__dropdown-content`,
class: `iti__dropdown-content iti__hide ${extraClasses}`
});
if(countrySearch){
this.searchInput=createEl(
"input",
{
type: "text",
class: "iti__search-input",
placeholder: i18n.searchPlaceholder,
role: "combobox",
"aria-expanded": "true",
"aria-label": i18n.searchPlaceholder,
"aria-controls": `iti-${this.id}__country-listbox`,
"aria-autocomplete": "list",
"autocomplete": "off"
},
this.dropdownContent
);
this.searchResultsA11yText=createEl(
"span",
{ class: "iti__a11y-text" },
this.dropdownContent
);
}
this.countryList=createEl(
"ul",
{
class: "iti__country-list",
id: `iti-${this.id}__country-listbox`,
role: "listbox",
"aria-label": i18n.countryListAriaLabel
},
this.dropdownContent
);
this._appendListItems();
if(countrySearch){
this._updateSearchResultsText();
}
if(dropdownContainer){
let dropdownClasses="iti iti--container";
if(useFullscreenPopup){
dropdownClasses +=" iti--fullscreen-popup";
}else{
dropdownClasses +=" iti--inline-dropdown";
}
this.dropdown=createEl("div", { class: dropdownClasses });
this.dropdown.appendChild(this.dropdownContent);
}else{
this.countryContainer.appendChild(this.dropdownContent);
}}
}
wrapper.appendChild(this.telInput);
this._updateInputPadding();
if(hiddenInput){
const telInputName=this.telInput.getAttribute("name")||"";
const names=hiddenInput(telInputName);
if(names.phone){
const existingInput=this.telInput.form?.querySelector(`input[name="${names.phone}"]`);
if(existingInput){
this.hiddenInput=existingInput;
}else{
this.hiddenInput=createEl("input", {
type: "hidden",
name: names.phone
});
wrapper.appendChild(this.hiddenInput);
}}
if(names.country){
const existingInput=this.telInput.form?.querySelector(`input[name="${names.country}"]`);
if(existingInput){
this.hiddenInputCountry=existingInput;
}else{
this.hiddenInputCountry=createEl("input", {
type: "hidden",
name: names.country
});
wrapper.appendChild(this.hiddenInputCountry);
}}
}}
_appendListItems(){
for (let i=0; i < this.countries.length; i++){
const c=this.countries[i];
const extraClass=i===0 ? "iti__highlight":"";
const listItem=createEl(
"li",
{
id: `iti-${this.id}__item-${c.iso2}`,
class: `iti__country ${extraClass}`,
tabindex: "-1",
role: "option",
"data-dial-code": c.dialCode,
"data-country-code": c.iso2,
"aria-selected": "false"
},
this.countryList
);
c.nodeById[this.id]=listItem;
let content="";
if(this.options.showFlags){
content +=`<div class='iti__flag iti__${c.iso2}'></div>`;
}
content +=`<span class='iti__country-name'>${c.name}</span>`;
content +=`<span class='iti__dial-code'>+${c.dialCode}</span>`;
listItem.insertAdjacentHTML("beforeend", content);
}}
_setInitialState(overrideAutoCountry=false){
const attributeValue=this.telInput.getAttribute("value");
const inputValue=this.telInput.value;
const useAttribute=attributeValue&&attributeValue.charAt(0)==="+"&&(!inputValue||inputValue.charAt(0)!=="+");
const val=useAttribute ? attributeValue:inputValue;
const dialCode=this._getDialCode(val);
const isRegionlessNanpNumber=isRegionlessNanp(val);
const { initialCountry, geoIpLookup }=this.options;
const isAutoCountry=initialCountry==="auto"&&geoIpLookup;
if(dialCode&&!isRegionlessNanpNumber){
this._updateCountryFromNumber(val);
}else if(!isAutoCountry||overrideAutoCountry){
const lowerInitialCountry=initialCountry ? initialCountry.toLowerCase():"";
const isValidInitialCountry=lowerInitialCountry&&this._getCountryData(lowerInitialCountry, true);
if(isValidInitialCountry){
this._setCountry(lowerInitialCountry);
}else{
if(dialCode&&isRegionlessNanpNumber){
this._setCountry("us");
}else{
this._setCountry();
}}
}
if(val){
this._updateValFromNumber(val);
}}
_initListeners(){
this._initTelInputListeners();
if(this.options.allowDropdown){
this._initDropdownListeners();
}
if((this.hiddenInput||this.hiddenInputCountry)&&this.telInput.form){
this._initHiddenInputListener();
}}
_initHiddenInputListener(){
this._handleHiddenInputSubmit=()=> {
if(this.hiddenInput){
this.hiddenInput.value=this.getNumber();
}
if(this.hiddenInputCountry){
this.hiddenInputCountry.value=this.getSelectedCountryData().iso2||"";
}};
this.telInput.form?.addEventListener("submit",
this._handleHiddenInputSubmit
);
}
_initDropdownListeners(){
this._handleLabelClick=(e)=> {
if(this.dropdownContent.classList.contains("iti__hide")){
this.telInput.focus();
}else{
e.preventDefault();
}};
const label=this.telInput.closest("label");
if(label){
label.addEventListener("click", this._handleLabelClick);
}
this._handleClickSelectedCountry=()=> {
if(this.dropdownContent.classList.contains("iti__hide")&&!this.telInput.disabled&&!this.telInput.readOnly){
this._openDropdown();
}};
this.selectedCountry.addEventListener("click", this._handleClickSelectedCountry);
this._handleCountryContainerKeydown=(e)=> {
const isDropdownHidden=this.dropdownContent.classList.contains("iti__hide");
if(isDropdownHidden&&["ArrowUp", "ArrowDown", " ", "Enter"].includes(e.key)){
e.preventDefault();
e.stopPropagation();
this._openDropdown();
}
if(e.key==="Tab"){
this._closeDropdown();
}};
this.countryContainer.addEventListener("keydown",
this._handleCountryContainerKeydown
);
}
_initRequests(){
let { loadUtils, initialCountry, geoIpLookup }=this.options;
if(loadUtils&&!intlTelInput.utils){
this._handlePageLoad=()=> {
window.removeEventListener("load", this._handlePageLoad);
intlTelInput.attachUtils(loadUtils)?.catch(()=> {
});
};
if(intlTelInput.documentReady()){
this._handlePageLoad();
}else{
window.addEventListener("load", this._handlePageLoad);
}}else{
this.resolveUtilsScriptPromise();
}
const isAutoCountry=initialCountry==="auto"&&geoIpLookup;
if(isAutoCountry&&!this.selectedCountryData.iso2){
this._loadAutoCountry();
}else{
this.resolveAutoCountryPromise();
}}
_loadAutoCountry(){
if(intlTelInput.autoCountry){
this.handleAutoCountry();
}else if(!intlTelInput.startedLoadingAutoCountry){
intlTelInput.startedLoadingAutoCountry=true;
if(typeof this.options.geoIpLookup==="function"){
this.options.geoIpLookup((iso2="")=> {
const iso2Lower=iso2.toLowerCase();
const isValidIso2=iso2Lower&&this._getCountryData(iso2Lower, true);
if(isValidIso2){
intlTelInput.autoCountry=iso2Lower;
setTimeout(()=> forEachInstance("handleAutoCountry"));
}else{
this._setInitialState(true);
forEachInstance("rejectAutoCountryPromise");
}},
()=> {
this._setInitialState(true);
forEachInstance("rejectAutoCountryPromise");
}
);
}}
}
_openDropdownWithPlus(){
this._openDropdown();
this.searchInput.value="+";
this._filterCountries("", true);
}
_initTelInputListeners(){
const { strictMode, formatAsYouType, separateDialCode, formatOnDisplay, allowDropdown, countrySearch }=this.options;
let userOverrideFormatting=false;
if(/\p{L}/u.test(this.telInput.value)){
userOverrideFormatting=true;
}
this._handleInputEvent=(e)=> {
if(this.isAndroid&&e?.data==="+"&&separateDialCode&&allowDropdown&&countrySearch){
const currentCaretPos=this.telInput.selectionStart||0;
const valueBeforeCaret=this.telInput.value.substring(0, currentCaretPos - 1);
const valueAfterCaret=this.telInput.value.substring(currentCaretPos);
this.telInput.value=valueBeforeCaret + valueAfterCaret;
this._openDropdownWithPlus();
return;
}
if(this._updateCountryFromNumber(this.telInput.value)){
this._triggerCountryChange();
}
const isFormattingChar=e?.data&&/[^+0-9]/.test(e.data);
const isPaste=e?.inputType==="insertFromPaste"&&this.telInput.value;
if(isFormattingChar||isPaste&&!strictMode){
userOverrideFormatting=true;
}else if(!/[^+0-9]/.test(this.telInput.value)){
userOverrideFormatting=false;
}
const disableFormatOnSetNumber=e?.detail&&e.detail["isSetNumber"]&&!formatOnDisplay;
if(formatAsYouType&&!userOverrideFormatting&&!disableFormatOnSetNumber){
const currentCaretPos=this.telInput.selectionStart||0;
const valueBeforeCaret=this.telInput.value.substring(0, currentCaretPos);
const relevantCharsBeforeCaret=valueBeforeCaret.replace(/[^+0-9]/g, "").length;
const isDeleteForwards=e?.inputType==="deleteContentForward";
const formattedValue=this._formatNumberAsYouType();
const newCaretPos=translateCursorPosition(relevantCharsBeforeCaret, formattedValue, currentCaretPos, isDeleteForwards);
this.telInput.value=formattedValue;
this.telInput.setSelectionRange(newCaretPos, newCaretPos);
}};
this.telInput.addEventListener("input", this._handleInputEvent);
if(strictMode||separateDialCode){
this._handleKeydownEvent=(e)=> {
if(e.key&&e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey){
if(separateDialCode&&allowDropdown&&countrySearch&&e.key==="+"){
e.preventDefault();
this._openDropdownWithPlus();
return;
}
if(strictMode){
const value=this.telInput.value;
const alreadyHasPlus=value.charAt(0)==="+";
const isInitialPlus = !alreadyHasPlus&&this.telInput.selectionStart===0&&e.key==="+";
const isNumeric=/^[0-9]$/.test(e.key);
const isAllowedChar=separateDialCode ? isNumeric:isInitialPlus||isNumeric;
const newValue=value.slice(0, this.telInput.selectionStart) + e.key + value.slice(this.telInput.selectionEnd);
const newFullNumber=this._getFullNumber(newValue);
const coreNumber=intlTelInput.utils.getCoreNumber(newFullNumber, this.selectedCountryData.iso2);
const hasExceededMaxLength=this.maxCoreNumberLength&&coreNumber.length > this.maxCoreNumberLength;
let isChangingDialCode=false;
if(alreadyHasPlus){
const currentCountry=this.selectedCountryData.iso2;
const newCountry=this._getCountryFromNumber(newFullNumber);
isChangingDialCode=newCountry!==currentCountry;
}
if(!isAllowedChar||hasExceededMaxLength&&!isChangingDialCode&&!isInitialPlus){
e.preventDefault();
}}
}};
this.telInput.addEventListener("keydown", this._handleKeydownEvent);
}}
_cap(number){
const max=parseInt(this.telInput.getAttribute("maxlength")||"", 10);
return max&&number.length > max ? number.substr(0, max):number;
}
_trigger(name, detailProps={}){
const e=new CustomEvent(name, {
bubbles: true,
cancelable: true,
detail: detailProps
});
this.telInput.dispatchEvent(e);
}
_openDropdown(){
const { fixDropdownWidth, countrySearch }=this.options;
if(fixDropdownWidth){
this.dropdownContent.style.width=`${this.telInput.offsetWidth}px`;
}
this.dropdownContent.classList.remove("iti__hide");
this.selectedCountry.setAttribute("aria-expanded", "true");
this._setDropdownPosition();
if(countrySearch){
const firstCountryItem=this.countryList.firstElementChild;
if(firstCountryItem){
this._highlightListItem(firstCountryItem, false);
this.countryList.scrollTop=0;
}
this.searchInput.focus();
}
this._bindDropdownListeners();
this.dropdownArrow.classList.add("iti__arrow--up");
this._trigger("open:countrydropdown");
}
_setDropdownPosition(){
if(this.options.dropdownContainer){
this.options.dropdownContainer.appendChild(this.dropdown);
}
if(!this.options.useFullscreenPopup){
const inputPosRelativeToVP=this.telInput.getBoundingClientRect();
const inputHeight=this.telInput.offsetHeight;
if(this.options.dropdownContainer){
this.dropdown.style.top=`${inputPosRelativeToVP.top + inputHeight}px`;
this.dropdown.style.left=`${inputPosRelativeToVP.left}px`;
this._handleWindowScroll=()=> this._closeDropdown();
window.addEventListener("scroll", this._handleWindowScroll);
}}
}
_bindDropdownListeners(){
this._handleMouseoverCountryList=(e)=> {
const listItem=e.target?.closest(".iti__country");
if(listItem){
this._highlightListItem(listItem, false);
}};
this.countryList.addEventListener("mouseover",
this._handleMouseoverCountryList
);
this._handleClickCountryList=(e)=> {
const listItem=e.target?.closest(".iti__country");
if(listItem){
this._selectListItem(listItem);
}};
this.countryList.addEventListener("click", this._handleClickCountryList);
let isOpening=true;
this._handleClickOffToClose=()=> {
if(!isOpening){
this._closeDropdown();
}
isOpening=false;
};
document.documentElement.addEventListener("click",
this._handleClickOffToClose
);
let query="";
let queryTimer=null;
this._handleKeydownOnDropdown=(e)=> {
if(["ArrowUp", "ArrowDown", "Enter", "Escape"].includes(e.key)){
e.preventDefault();
e.stopPropagation();
if(e.key==="ArrowUp"||e.key==="ArrowDown"){
this._handleUpDownKey(e.key);
}else if(e.key==="Enter"){
this._handleEnterKey();
}else if(e.key==="Escape"){
this._closeDropdown();
}}
if(!this.options.countrySearch&&/^[a-zA-ZÀ-ÿа-яА-Я ]$/.test(e.key)){
e.stopPropagation();
if(queryTimer){
clearTimeout(queryTimer);
}
query +=e.key.toLowerCase();
this._searchForCountry(query);
queryTimer=setTimeout(()=> {
query="";
}, 1e3);
}};
document.addEventListener("keydown", this._handleKeydownOnDropdown);
if(this.options.countrySearch){
const doFilter=()=> {
const inputQuery=this.searchInput.value.trim();
if(inputQuery){
this._filterCountries(inputQuery);
}else{
this._filterCountries("", true);
}};
let keyupTimer=null;
this._handleSearchChange=()=> {
if(keyupTimer){
clearTimeout(keyupTimer);
}
keyupTimer=setTimeout(()=> {
doFilter();
keyupTimer=null;
}, 100);
};
this.searchInput.addEventListener("input", this._handleSearchChange);
this.searchInput.addEventListener("click", (e)=> e.stopPropagation());
}}
_searchForCountry(query){
for (let i=0; i < this.countries.length; i++){
const c=this.countries[i];
const startsWith=c.name.substr(0, query.length).toLowerCase()===query;
if(startsWith){
const listItem=c.nodeById[this.id];
this._highlightListItem(listItem, false);
this._scrollTo(listItem);
break;
}}
}
_filterCountries(query, isReset=false){
let noCountriesAddedYet=true;
this.countryList.innerHTML="";
const normalisedQuery=normaliseString(query);
for (let i=0; i < this.countries.length; i++){
const c=this.countries[i];
const normalisedCountryName=normaliseString(c.name);
const countryInitials=c.name.split(/[^a-zA-ZÀ-ÿа-яА-Я]/).map((word)=> word[0]).join("").toLowerCase();
const fullDialCode=`+${c.dialCode}`;
if(isReset||normalisedCountryName.includes(normalisedQuery)||fullDialCode.includes(normalisedQuery)||c.iso2.includes(normalisedQuery)||countryInitials.includes(normalisedQuery)){
const listItem=c.nodeById[this.id];
if(listItem){
this.countryList.appendChild(listItem);
}
if(noCountriesAddedYet){
this._highlightListItem(listItem, false);
noCountriesAddedYet=false;
}}
}
if(noCountriesAddedYet){
this._highlightListItem(null, false);
}
this.countryList.scrollTop=0;
this._updateSearchResultsText();
}
_updateSearchResultsText(){
const { i18n }=this.options;
const count=this.countryList.childElementCount;
let searchText;
if(count===0){
searchText=i18n.zeroSearchResults;
}else if(count===1){
searchText=i18n.oneSearchResult;
}else{
searchText=i18n.multipleSearchResults.replace("${count}", count.toString());
}
this.searchResultsA11yText.textContent=searchText;
}
_handleUpDownKey(key){
let next=key==="ArrowUp" ? this.highlightedItem?.previousElementSibling:this.highlightedItem?.nextElementSibling;
if(!next&&this.countryList.childElementCount > 1){
next=key==="ArrowUp" ? this.countryList.lastElementChild:this.countryList.firstElementChild;
}
if(next){
this._scrollTo(next);
this._highlightListItem(next, false);
}}
_handleEnterKey(){
if(this.highlightedItem){
this._selectListItem(this.highlightedItem);
}}
_updateValFromNumber(fullNumber){
let number=fullNumber;
if(this.options.formatOnDisplay&&intlTelInput.utils&&this.selectedCountryData){
const useNational=this.options.nationalMode||number.charAt(0)!=="+"&&!this.options.separateDialCode;
const { NATIONAL, INTERNATIONAL }=intlTelInput.utils.numberFormat;
const format=useNational ? NATIONAL:INTERNATIONAL;
number=intlTelInput.utils.formatNumber(number,
this.selectedCountryData.iso2,
format
);
}
number=this._beforeSetNumber(number);
this.telInput.value=number;
}
_updateCountryFromNumber(fullNumber){
const iso2=this._getCountryFromNumber(fullNumber);
if(iso2!==null){
return this._setCountry(iso2);
}
return false;
}
_ensureHasDialCode(number){
const { dialCode, nationalPrefix }=this.selectedCountryData;
const alreadyHasPlus=number.charAt(0)==="+";
if(alreadyHasPlus||!dialCode){
return number;
}
const hasPrefix=nationalPrefix&&number.charAt(0)===nationalPrefix&&!this.options.separateDialCode;
const cleanNumber=hasPrefix ? number.substring(1):number;
return `+${dialCode}${cleanNumber}`;
}
_getCountryFromNumber(fullNumber){
const plusIndex=fullNumber.indexOf("+");
let number=plusIndex ? fullNumber.substring(plusIndex):fullNumber;
const selectedIso2=this.selectedCountryData.iso2;
const selectedDialCode=this.selectedCountryData.dialCode;
number=this._ensureHasDialCode(number);
const dialCodeMatch=this._getDialCode(number, true);
const numeric=getNumeric(number);
if(dialCodeMatch){
const dialCodeMatchNumeric=getNumeric(dialCodeMatch);
const iso2Codes=this.dialCodeToIso2Map[dialCodeMatchNumeric];
if(!selectedIso2&&this.defaultCountry&&iso2Codes.includes(this.defaultCountry)){
return this.defaultCountry;
}
const alreadySelected=selectedIso2&&iso2Codes.includes(selectedIso2)&&(numeric.length===dialCodeMatchNumeric.length||!this.selectedCountryData.areaCodes);
const isRegionlessNanpNumber=selectedDialCode==="1"&&isRegionlessNanp(numeric);
if(!isRegionlessNanpNumber&&!alreadySelected){
for (let j=0; j < iso2Codes.length; j++){
if(iso2Codes[j]){
return iso2Codes[j];
}}
}}else if(number.charAt(0)==="+"&&numeric.length){
return "";
}else if((!number||number==="+")&&!this.selectedCountryData.iso2){
return this.defaultCountry;
}
return null;
}
_highlightListItem(listItem, shouldFocus){
const prevItem=this.highlightedItem;
if(prevItem){
prevItem.classList.remove("iti__highlight");
prevItem.setAttribute("aria-selected", "false");
}
this.highlightedItem=listItem;
if(this.highlightedItem){
this.highlightedItem.classList.add("iti__highlight");
this.highlightedItem.setAttribute("aria-selected", "true");
const activeDescendant=this.highlightedItem.getAttribute("id")||"";
this.selectedCountry.setAttribute("aria-activedescendant", activeDescendant);
if(this.options.countrySearch){
this.searchInput.setAttribute("aria-activedescendant", activeDescendant);
}}
if(shouldFocus){
this.highlightedItem.focus();
}}
_getCountryData(iso2, allowFail){
for (let i=0; i < this.countries.length; i++){
if(this.countries[i].iso2===iso2){
return this.countries[i];
}}
if(allowFail){
return null;
}
throw new Error(`No country data for '${iso2}'`);
}
_setCountry(iso2){
const { separateDialCode, showFlags, i18n }=this.options;
const prevCountry=this.selectedCountryData.iso2 ? this.selectedCountryData:{};
this.selectedCountryData=iso2 ? this._getCountryData(iso2, false)||{}:{};
if(this.selectedCountryData.iso2){
this.defaultCountry=this.selectedCountryData.iso2;
}
if(this.selectedCountryInner){
let flagClass="";
let a11yText="";
if(iso2&&showFlags){
flagClass=`iti__flag iti__${iso2}`;
a11yText=`${this.selectedCountryData.name} +${this.selectedCountryData.dialCode}`;
}else{
flagClass="iti__flag iti__globe";
a11yText=i18n.noCountrySelected;
}
this.selectedCountryInner.className=flagClass;
this.selectedCountryA11yText.textContent=a11yText;
}
this._setSelectedCountryTitleAttribute(iso2, separateDialCode);
if(separateDialCode){
const dialCode=this.selectedCountryData.dialCode ? `+${this.selectedCountryData.dialCode}`:"";
this.selectedDialCode.innerHTML=dialCode;
this._updateInputPadding();
}
this._updatePlaceholder();
this._updateMaxLength();
return prevCountry.iso2!==iso2;
}
_updateInputPadding(){
if(this.selectedCountry){
const selectedCountryWidth=this.selectedCountry.offsetWidth||this._getHiddenSelectedCountryWidth();
const inputPadding=selectedCountryWidth + 6;
if(this.showSelectedCountryOnLeft){
this.telInput.style.paddingLeft=`${inputPadding}px`;
}else{
this.telInput.style.paddingRight=`${inputPadding}px`;
}}
}
_updateMaxLength(){
const { strictMode, placeholderNumberType, validationNumberTypes }=this.options;
const { iso2 }=this.selectedCountryData;
if(strictMode&&intlTelInput.utils){
if(iso2){
const numberType=intlTelInput.utils.numberType[placeholderNumberType];
let exampleNumber=intlTelInput.utils.getExampleNumber(iso2,
false,
numberType,
true
);
let validNumber=exampleNumber;
while (intlTelInput.utils.isPossibleNumber(exampleNumber, iso2, validationNumberTypes)){
validNumber=exampleNumber;
exampleNumber +="0";
}
const coreNumber=intlTelInput.utils.getCoreNumber(validNumber, iso2);
this.maxCoreNumberLength=coreNumber.length;
if(iso2==="by"){
this.maxCoreNumberLength=coreNumber.length + 1;
}}else{
this.maxCoreNumberLength=null;
}}
}
_setSelectedCountryTitleAttribute(iso2=null, separateDialCode){
if(!this.selectedCountry){
return;
}
let title;
if(iso2&&!separateDialCode){
title=`${this.selectedCountryData.name}: +${this.selectedCountryData.dialCode}`;
}else if(iso2){
title=this.selectedCountryData.name;
}else{
title="Unknown";
}
this.selectedCountry.setAttribute("title", title);
}
_getHiddenSelectedCountryWidth(){
if(this.telInput.parentNode){
const containerClone=this.telInput.parentNode.cloneNode(false);
containerClone.style.visibility="hidden";
document.body.appendChild(containerClone);
const countryContainerClone=this.countryContainer.cloneNode();
containerClone.appendChild(countryContainerClone);
const selectedCountryClone=this.selectedCountry.cloneNode(true);
countryContainerClone.appendChild(selectedCountryClone);
const width=selectedCountryClone.offsetWidth;
document.body.removeChild(containerClone);
return width;
}
return 0;
}
_updatePlaceholder(){
const {
autoPlaceholder,
placeholderNumberType,
nationalMode,
customPlaceholder
}=this.options;
const shouldSetPlaceholder=autoPlaceholder==="aggressive"||!this.hadInitialPlaceholder&&autoPlaceholder==="polite";
if(intlTelInput.utils&&shouldSetPlaceholder){
const numberType=intlTelInput.utils.numberType[placeholderNumberType];
let placeholder=this.selectedCountryData.iso2 ? intlTelInput.utils.getExampleNumber(this.selectedCountryData.iso2,
nationalMode,
numberType
):"";
placeholder=this._beforeSetNumber(placeholder);
if(typeof customPlaceholder==="function"){
placeholder=customPlaceholder(placeholder, this.selectedCountryData);
}
this.telInput.setAttribute("placeholder", placeholder);
}}
_selectListItem(listItem){
const countryChanged=this._setCountry(listItem.getAttribute("data-country-code")
);
this._closeDropdown();
this._updateDialCode(listItem.getAttribute("data-dial-code"));
this.telInput.focus();
if(countryChanged){
this._triggerCountryChange();
}}
_closeDropdown(){
this.dropdownContent.classList.add("iti__hide");
this.selectedCountry.setAttribute("aria-expanded", "false");
this.selectedCountry.removeAttribute("aria-activedescendant");
if(this.highlightedItem){
this.highlightedItem.setAttribute("aria-selected", "false");
}
if(this.options.countrySearch){
this.searchInput.removeAttribute("aria-activedescendant");
}
this.dropdownArrow.classList.remove("iti__arrow--up");
document.removeEventListener("keydown", this._handleKeydownOnDropdown);
if(this.options.countrySearch){
this.searchInput.removeEventListener("input", this._handleSearchChange);
}
document.documentElement.removeEventListener("click",
this._handleClickOffToClose
);
this.countryList.removeEventListener("mouseover",
this._handleMouseoverCountryList
);
this.countryList.removeEventListener("click", this._handleClickCountryList);
if(this.options.dropdownContainer){
if(!this.options.useFullscreenPopup){
window.removeEventListener("scroll", this._handleWindowScroll);
}
if(this.dropdown.parentNode){
this.dropdown.parentNode.removeChild(this.dropdown);
}}
if(this._handlePageLoad){
window.removeEventListener("load", this._handlePageLoad);
}
this._trigger("close:countrydropdown");
}
_scrollTo(element){
const container=this.countryList;
const scrollTop=document.documentElement.scrollTop;
const containerHeight=container.offsetHeight;
const containerTop=container.getBoundingClientRect().top + scrollTop;
const containerBottom=containerTop + containerHeight;
const elementHeight=element.offsetHeight;
const elementTop=element.getBoundingClientRect().top + scrollTop;
const elementBottom=elementTop + elementHeight;
const newScrollTop=elementTop - containerTop + container.scrollTop;
if(elementTop < containerTop){
container.scrollTop=newScrollTop;
}else if(elementBottom > containerBottom){
const heightDifference=containerHeight - elementHeight;
container.scrollTop=newScrollTop - heightDifference;
}}
_updateDialCode(newDialCodeBare){
const inputVal=this.telInput.value;
const newDialCode=`+${newDialCodeBare}`;
let newNumber;
if(inputVal.charAt(0)==="+"){
const prevDialCode=this._getDialCode(inputVal);
if(prevDialCode){
newNumber=inputVal.replace(prevDialCode, newDialCode);
}else{
newNumber=newDialCode;
}
this.telInput.value=newNumber;
}}
_getDialCode(number, includeAreaCode){
let dialCode="";
if(number.charAt(0)==="+"){
let numericChars="";
for (let i=0; i < number.length; i++){
const c=number.charAt(i);
if(!isNaN(parseInt(c, 10))){
numericChars +=c;
if(includeAreaCode){
if(this.dialCodeToIso2Map[numericChars]){
dialCode=number.substr(0, i + 1);
}}else{
if(this.dialCodes[numericChars]){
dialCode=number.substr(0, i + 1);
break;
}}
if(numericChars.length===this.dialCodeMaxLen){
break;
}}
}}
return dialCode;
}
_getFullNumber(overrideVal){
const val=overrideVal||this.telInput.value.trim();
const { dialCode }=this.selectedCountryData;
let prefix;
const numericVal=getNumeric(val);
if(this.options.separateDialCode&&val.charAt(0)!=="+"&&dialCode&&numericVal){
prefix=`+${dialCode}`;
}else{
prefix="";
}
return prefix + val;
}
_beforeSetNumber(fullNumber){
let number=fullNumber;
if(this.options.separateDialCode){
let dialCode=this._getDialCode(number);
if(dialCode){
dialCode=`+${this.selectedCountryData.dialCode}`;
const start=number[dialCode.length]===" "||number[dialCode.length]==="-" ? dialCode.length + 1:dialCode.length;
number=number.substr(start);
}}
return this._cap(number);
}
_triggerCountryChange(){
this._trigger("countrychange");
}
_formatNumberAsYouType(){
const val=this._getFullNumber();
const result=intlTelInput.utils ? intlTelInput.utils.formatNumberAsYouType(val, this.selectedCountryData.iso2):val;
const { dialCode }=this.selectedCountryData;
if(this.options.separateDialCode&&this.telInput.value.charAt(0)!=="+"&&result.includes(`+${dialCode}`)){
const afterDialCode=result.split(`+${dialCode}`)[1]||"";
return afterDialCode.trim();
}
return result;
}
handleAutoCountry(){
if(this.options.initialCountry==="auto"&&intlTelInput.autoCountry){
this.defaultCountry=intlTelInput.autoCountry;
const hasSelectedCountryOrGlobe=this.selectedCountryData.iso2||this.selectedCountryInner.classList.contains("iti__globe");
if(!hasSelectedCountryOrGlobe){
this.setCountry(this.defaultCountry);
}
this.resolveAutoCountryPromise();
}}
handleUtils(){
if(intlTelInput.utils){
if(this.telInput.value){
this._updateValFromNumber(this.telInput.value);
}
if(this.selectedCountryData.iso2){
this._updatePlaceholder();
this._updateMaxLength();
}}
this.resolveUtilsScriptPromise();
}
destroy(){
const { allowDropdown, separateDialCode }=this.options;
if(allowDropdown){
this._closeDropdown();
this.selectedCountry.removeEventListener("click",
this._handleClickSelectedCountry
);
this.countryContainer.removeEventListener("keydown",
this._handleCountryContainerKeydown
);
const label=this.telInput.closest("label");
if(label){
label.removeEventListener("click", this._handleLabelClick);
}}
const { form }=this.telInput;
if(this._handleHiddenInputSubmit&&form){
form.removeEventListener("submit", this._handleHiddenInputSubmit);
}
this.telInput.removeEventListener("input", this._handleInputEvent);
if(this._handleKeydownEvent){
this.telInput.removeEventListener("keydown", this._handleKeydownEvent);
}
this.telInput.removeAttribute("data-intl-tel-input-id");
if(separateDialCode){
if(this.isRTL){
this.telInput.style.paddingRight=this.originalPaddingRight;
}else{
this.telInput.style.paddingLeft=this.originalPaddingLeft;
}}
const wrapper=this.telInput.parentNode;
wrapper?.parentNode?.insertBefore(this.telInput, wrapper);
wrapper?.parentNode?.removeChild(wrapper);
delete intlTelInput.instances[this.id];
}
getExtension(){
if(intlTelInput.utils){
return intlTelInput.utils.getExtension(this._getFullNumber(),
this.selectedCountryData.iso2
);
}
return "";
}
getNumber(format){
if(intlTelInput.utils){
const { iso2 }=this.selectedCountryData;
return intlTelInput.utils.formatNumber(this._getFullNumber(),
iso2,
format
);
}
return "";
}
getNumberType(){
if(intlTelInput.utils){
return intlTelInput.utils.getNumberType(this._getFullNumber(),
this.selectedCountryData.iso2
);
}
return -99;
}
getSelectedCountryData(){
return this.selectedCountryData;
}
getValidationError(){
if(intlTelInput.utils){
const { iso2 }=this.selectedCountryData;
return intlTelInput.utils.getValidationError(this._getFullNumber(), iso2);
}
return -99;
}
isValidNumber(){
if(!this.selectedCountryData.iso2){
return false;
}
const val=this._getFullNumber();
const alphaCharPosition=val.search(/\p{L}/u);
if(alphaCharPosition > -1){
const beforeAlphaChar=val.substring(0, alphaCharPosition);
const beforeAlphaIsValid=this._utilsIsPossibleNumber(beforeAlphaChar);
const isValid=this._utilsIsPossibleNumber(val);
return beforeAlphaIsValid&&isValid;
}
return this._utilsIsPossibleNumber(val);
}
_utilsIsPossibleNumber(val){
return intlTelInput.utils ? intlTelInput.utils.isPossibleNumber(val, this.selectedCountryData.iso2, this.options.validationNumberTypes):null;
}
isValidNumberPrecise(){
if(!this.selectedCountryData.iso2){
return false;
}
const val=this._getFullNumber();
const alphaCharPosition=val.search(/\p{L}/u);
if(alphaCharPosition > -1){
const beforeAlphaChar=val.substring(0, alphaCharPosition);
const beforeAlphaIsValid=this._utilsIsValidNumber(beforeAlphaChar);
const isValid=this._utilsIsValidNumber(val);
return beforeAlphaIsValid&&isValid;
}
return this._utilsIsValidNumber(val);
}
_utilsIsValidNumber(val){
return intlTelInput.utils ? intlTelInput.utils.isValidNumber(val, this.selectedCountryData.iso2, this.options.validationNumberTypes):null;
}
setCountry(iso2){
const iso2Lower=iso2?.toLowerCase();
const currentCountry=this.selectedCountryData.iso2;
const isCountryChange=iso2&&iso2Lower!==currentCountry||!iso2&&currentCountry;
if(isCountryChange){
this._setCountry(iso2Lower);
this._updateDialCode(this.selectedCountryData.dialCode);
this._triggerCountryChange();
}}
setNumber(number){
const countryChanged=this._updateCountryFromNumber(number);
this._updateValFromNumber(number);
if(countryChanged){
this._triggerCountryChange();
}
this._trigger("input", { isSetNumber: true });
}
setPlaceholderNumberType(type){
this.options.placeholderNumberType=type;
this._updatePlaceholder();
}
setDisabled(disabled){
this.telInput.disabled=disabled;
if(disabled){
this.selectedCountry.setAttribute("disabled", "true");
}else{
this.selectedCountry.removeAttribute("disabled");
}}
};
var attachUtils=(source)=> {
if(!intlTelInput.utils&&!intlTelInput.startedLoadingUtilsScript){
let loadCall;
if(typeof source==="function"){
try {
loadCall=Promise.resolve(source());
} catch (error){
return Promise.reject(error);
}}else{
return Promise.reject(new TypeError(`The argument passed to attachUtils must be a function that returns a promise for the utilities module, not ${typeof source}`));
}
intlTelInput.startedLoadingUtilsScript=true;
return loadCall.then((module)=> {
const utils=module?.default;
if(!utils||typeof utils!=="object"){
throw new TypeError("The loader function passed to attachUtils did not resolve to a module object with utils as its default export.");
}
intlTelInput.utils=utils;
forEachInstance("handleUtils");
return true;
}).catch((error)=> {
forEachInstance("rejectUtilsScriptPromise", error);
throw error;
});
}
return null;
};
var intlTelInput=Object.assign((input, options)=> {
const iti=new Iti(input, options);
iti._init();
input.setAttribute("data-intl-tel-input-id", iti.id.toString());
intlTelInput.instances[iti.id]=iti;
return iti;
},
{
defaults,
documentReady: ()=> document.readyState==="complete",
getCountryData: ()=> data_default,
getInstance: (input)=> {
const id2=input.getAttribute("data-intl-tel-input-id");
return id2 ? intlTelInput.instances[id2]:null;
},
instances: {},
attachUtils,
startedLoadingUtilsScript: false,
startedLoadingAutoCountry: false,
version: "25.3.0"
}
);
var intl_tel_input_default=intlTelInput;
return __toCommonJS(intl_tel_input_exports);
})();
return factoryOutput.default;
}));
var MSE_STORAGE_EXPIRY_1_DAY=1,MSE_STORAGE_EXPIRY_2_DAYS=2,MSE_STORAGE_EXPIRY_7_DAYS=7,MSE_STORAGE_EXPIRY_365_DAYS=365;function launch_mystickyelements(e){var t="desktop",s=1;e=void 0!==e?e:1,/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)&&(t="mobile"),jQuery(".mystickyelements-fixed .mystickyelements-lists").each((function(){if(!(s>1)){var i=1;jQuery(this).find("li").each((function(){if(jQuery(this).hasClass("mystickyelements-minimize"))jQuery(this).hasClass("element-minimize")&&jQuery(this).trigger("click");else if(jQuery(this).hasClass("element-"+t+"-on"))return e==i?(jQuery(this).addClass("elements-active"),jQuery(this).parent().parent().parent().hasClass("mystickyelements-on-click")||jQuery(this).parent().parent().parent().addClass("mystickyelements-on-click"),!1):void i++})),s++}}))}function close_mystickyelements(){/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),jQuery(".mystickyelements-fixed .mystickyelements-lists").each((function(){jQuery(this).find("li").each((function(){jQuery(this).hasClass("elements-active")&&jQuery(this).removeClass("elements-active")}))}))}function hide_mystickyelements(){jQuery(".mystickyelements-fixed").each((function(){jQuery(this).hide(),MSESetStorageWithExpiry("hide_mystickyelements","closed",MSE_STORAGE_EXPIRY_365_DAYS)}))}function show_mystickyelements(){jQuery(".mystickyelements-fixed").each((function(){jQuery(this).show(),MSESetStorageWithExpiry("hide_mystickyelements","opened",MSE_STORAGE_EXPIRY_1_DAY)}))}function MSESetStorageWithExpiry(e,t,s){if(s){const i=Date.now()+24*s*60*60*1e3;localStorage.setItem(e,JSON.stringify({value:t,expiry:i}))}else localStorage.setItem(e,t)}function MSEGetStorageWithExpiry(e){const t=localStorage.getItem(e);if(!t)return null;try{const s=JSON.parse(t);return s&&"object"==typeof s&&"expiry"in s?Date.now()>s.expiry?(localStorage.removeItem(e),null):s.value:s}catch(e){return t}}function checkForMSEStorageString(e,t){var s=MSEGetStorageWithExpiry("mystickyelementWidget_"+e),i=[];if(null!=s&&""!=s&&(i=JSON.parse(s)),i.length>0)for(var n=0;n<i.length;n++)if(i[n].k==t)return i[n].v;return null}function saveMSEStorageString(e,t){var s=MSEGetStorageWithExpiry("mystickyelementWidget_"+e),i=[];null!=s&&""!=s&&(i=JSON.parse(s));var n=!1;if(i.length>0)for(var m=0;m<i.length;m++)i[m].k==t&&(n=!0,i[m].v=new Date);n||i.push({k:t,v:new Date}),MSESetStorageWithExpiry("mystickyelementWidget_"+e,s=JSON.stringify(i),MSE_STORAGE_EXPIRY_7_DAYS)}function checkMSEStorageExpired(e,t){var s=checkForMSEStorageString(e,t);if(null!=s&&""!=s){s=new Date(s);var i=Math.abs(new Date-s);return Math.floor(i/864e5)>=MSE_STORAGE_EXPIRY_2_DAYS}return!0}function MSECheckStorageWithExpiry(e){const t=localStorage.getItem(e);if(!t)return!1;try{const e=JSON.parse(t);return!e||"object"!=typeof e||!("expiry"in e)||Date.now()>e.expiry}catch(e){return!0}}function MSELocalStorageGetSimple(e){return localStorage.getItem(e)}function MSELocalStorageSetSimple(e,t){localStorage.setItem(e,t)}!function(e){"use strict";var t="",s="",i=0,n=!1,m=0,o=-1;function l(){return/Android|webOS|iPhone|iPad|Mac|Macintosh|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)?"mobile":"desktop"}function a(){if(e(window).width()<=1024){if(e(".mystickyelements-fixed").hasClass("mystickyelements-position-mobile-top")){var t=e(".mystickyelements-fixed").height();e("html").attr("style","margin-top: "+t+"px !important")}}else e("html").css("margin-top","")}function c(){if(0!==e(".element-contact-form").length){var m=e(window).height(),o=e(".mystickyelements-fixed").position().top,l=(e(".element-contact-form").offset().top,e("#mystickyelements-contact-form #stickyelements-form").innerHeight()+e(".element-contact-form .contact-form-heading").innerHeight());if(m<l){var a=m-70;e("#mystickyelements-contact-form .element-contact-form").css("max-height",a+"px"),e("#mystickyelements-contact-form .element-contact-form").css("overflowY","auto");var c=o-10;e(window).width()>1025&&!e(".mystickyelements-fixed").hasClass("mystickyelements-position-bottom")&&e("#mystickyelements-contact-form .element-contact-form").css("top","-"+c+"px"),e(window).width()<1024&&!e(".mystickyelements-fixed").hasClass("mystickyelements-position-mobile-bottom")&&e("#mystickyelements-contact-form .element-contact-form").css("top","-"+c+"px")}else{var r=e("ul.mystickyelements-lists .mystickyelements-minimize").height();null===r&&(r=0);c=o-(m-l)+r+10;e(window).width()>1025&&!e(".mystickyelements-fixed").hasClass("mystickyelements-position-bottom")&&e("#mystickyelements-contact-form .element-contact-form").css("top","-"+c+"px"),e(window).width()<1024&&!e(".mystickyelements-fixed").hasClass("mystickyelements-position-mobile-bottom")&&e("#mystickyelements-contact-form .element-contact-form").css("top","-"+c+"px"),e("#mystickyelements-contact-form .element-contact-form").css("overflowY",""),e("#mystickyelements-contact-form .element-contact-form").css("max-height","")}}var y="";/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)&&(y="mobile-");var h=0;e(".mystickyelements-fixed ul li").each((function(){if(e(this).hasClass("elements-active")&&!e(this).parents(".mystickyelements-fixed").hasClass("mystickyelements-on-click")&&e(this).parents(".mystickyelements-fixed").addClass("mystickyelements-on-click"),"1"===mystickyelements.google_analytics&&!0!==e(this).hasClass("mystickyelements-minimize")&&"mystickyelements-contact-form"!==e(this).attr("id"))if(0!==e(this).find("a").length){var m=e(this).attr("id").split("mystickyelements-social-");e(this).find("a").addClass("update-analytics"),e(this).find("a").attr("data-social-slug",m[1])}else e(this).addClass("analytics-update");e(".mystickyelements-position-"+y+"left #"+e(this).attr("id")+" .mystickyelements-social-icon").css("border-radius",""),e(".mystickyelements-position-"+y+"right #"+e(this).attr("id")+" .mystickyelements-social-icon").css("border-radius",""),0==i&&(e(window).width()>1024&&!e(this).hasClass("element-desktop-on")&&(n=!0),e(window).width()<1025&&!e(this).hasClass("element-mobile-on")&&(n=!0)),1==i&&!0===n&&(e(window).width()>1024&&(s=e(this).attr("id")),e(window).width()<1025&&(s=e(this).attr("id"))),e(window).width()>1024&&e(this).hasClass("element-desktop-on")&&(t=e(this).attr("id")),e(window).width()<1025&&e(this).hasClass("element-mobile-on")&&(t=e(this).attr("id"),h++),i++})),e(".mystickyelements-fixed.mystickyelements-position-mobile-bottom").addClass("mystickyelements-bottom-social-channel-"+h),e(".mystickyelements-fixed.mystickyelements-position-mobile-top").addClass("mystickyelements-top-social-channel-"+h),""!=t?"mystickyelements-contact-form"===t?(e(".mystickyelements-position-"+y+"left #"+t+" .mystickyelements-social-icon").css("border-bottom-left-radius","10px"),e(".mystickyelements-position-"+y+"right #"+t+" .mystickyelements-social-icon").css("border-top-left-radius","10px"),e(".mystickyelements-position-"+y+"bottom #"+t+" .mystickyelements-social-icon").css("border-top-right-radius","10px"),1!==e("li.mystickyelements-minimize").length&&(e(".mystickyelements-position-"+y+"left #"+t+" .mystickyelements-social-icon").css("border-bottom-right-radius","10px"),e(".mystickyelements-position-"+y+"right #"+t+" .mystickyelements-social-icon").css("border-top-right-radius","10px"))):"mystickyelements-contact-form"!==t&&(1===i?(e(".mystickyelements-position-"+y+"left #"+t+" .mystickyelements-social-icon").css("border-radius","0px 10px 10px 0"),e(".mystickyelements-position"+y+"-right #"+t+" .mystickyelements-social-icon").css("border-radius","10px 0 0 10px")):(e(".mystickyelements-position-"+y+"left #"+t+" .mystickyelements-social-icon").css("border-bottom-right-radius","10px"),e(".mystickyelements-position-"+y+"right #"+t+" .mystickyelements-social-icon").css("border-bottom-left-radius","10px"),e(".mystickyelements-position-"+y+"bottom #"+t+" .mystickyelements-social-icon").css("border-top-right-radius","10px"))):(e(".mystickyelement-credit").hide(),e(".mystickyelements-fixed").hide()),""!=s&&"mystickyelements-contact-form"!==s&&1!==e("li.mystickyelements-minimize").length&&(e(".mystickyelements-position-"+y+"left #"+s+" .mystickyelements-social-icon").css("border-top-right-radius","10px"),e(".mystickyelements-position-"+y+"right #"+s+" .mystickyelements-social-icon").css("border-top-left-radius","10px"),e(".mystickyelements-position-"+y+"bottom #"+s+" .mystickyelements-social-icon").css("border-top-left-radius","10px"))}function r(e){e.parent().parent().removeClass("elements-active")}e(document).ready((function(){function t(e){e.find("a").attr("href","#"),m++,o=0}function s(e,t){o=1,m++,e.find("a").attr("href",t)}function i(i,n){var l=i.data("tab-setting"),a=(i.data("click"),i.find("a").data("url"));"mobile"==n?function(i,n,l,a){if("hover"==n&&"enable"==i.data("mobile-behavior")){if(i.data("click","1"),0!=m)return void s(i,a);t(i)}else if("click"==n&&"enable"==i.data("flyout")){if(i.data("click","1"),0!=m)return void s(i,a);t(i)}else{if("click"==n&&"disable"==i.data("flyout"))return i.children("a").length?e(".mystickyelements-on-click .elements-active").removeClass("elements-active"):i.parent("li").addClass("elements-active"),void(o=1);o=1}}(i,l,0,a):function(i,n,l,a){if("enable"==i.data("flyout")){if(i.data("click","1"),0!=m)return void s(i,a);t(i)}else if("disable"==i.data("flyout"))i.children("a").length?e(".mystickyelements-on-click .elements-active").removeClass("elements-active"):i.parent("li").addClass("elements-active"),o=1,i.find("a").attr("href",a)}(i,0,0,a)}(e(".mystickyelements-fixed .mystickyelements-lists").each((function(){var t=e(this),s=(t.data("mystickyelement-widget"),MSEGetStorageWithExpiry("minimize_desktop")),i=MSEGetStorageWithExpiry("minimize_mobile");"minimize"!=s&&"minimize"!=i||(t.addClass("mystickyelement-minimize"),t.find(".mystickyelements-minimize").addClass("element-minimize"),t.find(".mystickyelements-minimize span").hasClass("minimize-position-left")?t.find(".mystickyelements-minimize span").html("&rarr;"):t.find(".mystickyelements-minimize span").html("&larr;")),"closed"==MSEGetStorageWithExpiry("closed_contactform")&&t.find(".mystickyelements-contact-form").removeClass("elements-open-form-active")})),"true"==localStorage.getItem("elements-default-active")?e(".mystickyelements-social-icon-li,.mystickyelements-contact-form").removeClass("elements-active"):(1==e(".mystickyelements-social-icon-li").hasClass("elements-default-active")&&e(".mystickyelements-social-icon-li.elements-default-active").addClass("elements-active elements-hover-active"),1==e(".mystickyelements-contact-form").hasClass("elements-default-active")&&e(".mystickyelements-contact-form.elements-default-active").addClass("elements-active elements-hover-active")),"closed"==MSEGetStorageWithExpiry("hide_mystickyelements")&&e(".mystickyelements-fixed").each((function(){jQuery(this).hide()})),e(".elements-open-form-active").each((function(){var t=e(this),s=e(this).data("time-delay");setTimeout((function(e){e.addClass("elements-active")}),1e3*s,t)})),/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)&&e(".mystickyelements-fixed").addClass("mystickyelements-on-click").removeClass("mystickyelements-on-hover"),e("#stickyelements-form").on("submit",(function(t){t.preventDefault();var s=e(this).data("close-after");e("#stickyelements-form .mse-input-error").removeClass("mse-input-error"),e("#stickyelements-form .mse-input-message").remove();var i=0;e("#stickyelements-form .required").length&&e("#stickyelements-form .required").each((function(){""==e.trim(e(this).val())&&(e(this).addClass("mse-input-error"),e(this).after("<span class='mse-input-message'>This field is required</span>"),i++)})),e("#stickyelements-form .email.required:not(.mse-input-error)").length&&e("#stickyelements-form .email.required:not(.mse-input-error)").each((function(){var t=e.trim(e(this).val());/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(t)||(e(this).addClass("mse-input-error"),e(this).after("<span class='mse-input-message'>Email address is not valid</span>"),i++)}));var n=e(this).find(".iti__selected-dial-code").text(),m="action=mystickyelements_contact_form&"+jQuery("form#stickyelements-form").serialize()+"&security="+mystickyelements.ajax_nonce;return""!=n&&(m="action=mystickyelements_contact_form&"+jQuery("form#stickyelements-form").serialize()+"&security="+mystickyelements.ajax_nonce+"&contact_code="+n),0==i&&jQuery.ajax({url:mystickyelements.ajaxurl,type:"post",data:m,beforeSend:function(){e("#stickyelements-submit-form").prop("disabled",!0)},success:function(t){if(e("#stickyelements-submit-form").prop("disabled",!1),e("#stickyelements-form .mse-input-error").removeClass("mse-input-error"),e("#stickyelements-form .mse-input-message").remove(),"1"==(t=e.parseJSON(t)).error)for(var i=0;i<t.errors.length;i++)"mse-form-error"!=t.errors[i].key?(e("#stickyelements-form #"+t.errors[i].key).addClass("mse-input-error"),e("#stickyelements-form #"+t.errors[i].key).after("<span class='mse-input-message'>"+t.errors[i].message+"</span>")):(e("#mse-form-error").removeClass("mse-form-success-message").addClass("mse-form-error-message").show(),e("#mse-form-error").html(t.errors[i].message));else"0"==t.status?(e("#mse-form-error").removeClass("mse-form-success-message").addClass("mse-form-error-message").show(),e("#mse-form-error").html(t.message)):(e("#mse-form-error").removeClass("mse-form-error-message").addClass("mse-form-success-message").show(),e("#mse-form-error").html(t.message),e('#stickyelements-form input[type="text"], #stickyelements-form input[type="tel"], #stickyelements-form input[type="email"]').val(""),e("#stickyelements-form textarea").val(""),MSESetStorageWithExpiry("closed_contactform","closed",MSE_STORAGE_EXPIRY_1_DAY));return setTimeout((function(){e(".mse-form-success-message").slideUp("slow")}),5e3),1==t.status&&""!=t.redirect_link?window.location=t.redirect_link:void 0!==s&&""!=s&&(s*=1e3,setTimeout((function(){e(".mystickyelements-fixed .mystickyelements-contact-form ").removeClass("elements-active"),e(".mystickyelements-fixed .mystickyelements-contact-form ").removeClass("element-contact-active")}),s)),!1}}),!1})),e(".mystickyelements-on-click .mystickyelements-social-icon").on("click touch",(function(t){var s=e(this).data("click"),n=l(),a=e(this);(e(this).parent("li").hasClass("mystickyelements-contact-form")||("0"==s&&(e(".mystickyelements-social-icon").data("click","0"),m=0),i(a,n),1!=o))&&(e(this).parent("li").hasClass("elements-active")?(e(this).parent("li").removeClass("elements-active"),MSESetStorageWithExpiry("closed_contactform","closed",MSE_STORAGE_EXPIRY_1_DAY),t.preventDefault()):(e(".mystickyelements-on-click .elements-active").removeClass("elements-active"),e(this).parent("li").addClass("elements-active")))})),e(".mystickyelements-on-hover .mystickyelements-social-icon").on("click",(function(t){e(this).parent("li").hasClass("elements-active")&&0==e(this).children("a").length&&(e(this).parent("li").removeClass("elements-hover-active"),t.preventDefault(),e(this).parent().parent().parent().parent(".mystickyelements-on-hover").removeClass("mystickyelements-on-click"))})),e(".mystickyelements-on-hover .mystickyelements-social-icon-li").on("mouseenter",(function(){e(this).hasClass("elements-active"),e(this).hasClass("elements-active")||(e(".mystickyelements-on-click .elements-active").removeClass("elements-active"),e(this).addClass("elements-active"),e(this).addClass("elements-hover-active"),e(this).parent().parent().parent(".mystickyelements-on-hover").addClass("mystickyelements-on-click"))})).on("mouseleave",(function(){e(this).removeClass("elements-active"),e(this).removeClass("elements-hover-active"),e(this).parent().parent().parent(".mystickyelements-on-hover").removeClass("mystickyelements-on-click"),(e(".mystickyelements-social-icon-li").hasClass("elements-default-active")||e(".mystickyelements-contact-form").hasClass("elements-default-active"))&&localStorage.setItem("elements-default-active",!0)})),e(".mystickyelements-on-hover ul li.mystickyelements-contact-form").on("mouseenter",(function(){e(this).parents(".mystickyelement-lists-wrap").find("li.elements-active").removeClass("elements-active elements-hover-active"),e(this).addClass("element-contact-active")})).on("mouseleave",(function(){e(this).removeClass("element-contact-active"),(e(".mystickyelements-social-icon-li").hasClass("elements-default-active")||e(".mystickyelements-contact-form").hasClass("elements-default-active"))&&localStorage.setItem("elements-default-active",!0)})),e(".element-contact-close").on("click touch",(function(t){e(".mystickyelements-contact-form").removeClass("elements-active"),e(".mystickyelements-contact-form").removeClass("element-contact-active"),MSESetStorageWithExpiry("closed_contactform","closed",MSE_STORAGE_EXPIRY_1_DAY),(e(".mystickyelements-social-icon-li").hasClass("elements-default-active")||e(".mystickyelements-contact-form").hasClass("elements-default-active"))&&localStorage.setItem("elements-default-active",!0)})),e("#stickyelements-form input:not(#stickyelements-submit-form), #stickyelements-form textarea ").on("keyup",(function(t){e(this).val()&&(e(this).css("background-color","#EFF5F8"),e(this).css("border-color","#7761DF"))})),c(),e("li.mystickyelements-minimize").on("click",(function(t){var s,i,n,m;e(this).toggleClass("element-minimize"),/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)?(i="mobile",n="mobile-",m="element-mobile-on"):(i="desktop",n="",m="element-desktop-on"),!0===e(this).hasClass("element-minimize")?(MSESetStorageWithExpiry("minimize_"+i,"minimize",MSE_STORAGE_EXPIRY_1_DAY),s=!0):(MSESetStorageWithExpiry("minimize_"+i,"minimize_not",MSE_STORAGE_EXPIRY_1_DAY),s=!1),e(".mystickyelements-position-"+n+"left ul li").each((function(){1==e(this).hasClass(m)&&(1==e(".mystickyelements-fixed").hasClass("mystickyelements-size-large")?e(this).animate({width:"toggle",left:!0===s?"-=80":""}):e(this).animate({width:"toggle",left:!0===s?"-=50":""}))})),e(".mystickyelements-position-"+n+"right ul li").each((function(){1==e(this).hasClass(m)&&(1==e(".mystickyelements-fixed").hasClass("mystickyelements-size-large")?e(this).animate({width:"toggle",left:!0===s?"+=80":""},300,(function(){})):e(this).animate({width:"toggle",left:!0===s?"+=50":""},300,(function(){})))})),e(".mystickyelements-position-"+n+"bottom ul li").each((function(){1==e(this).hasClass(m)&&(e(this).css("position","relative"),1==e(".mystickyelements-fixed").hasClass("mystickyelements-size-large")?e(this).animate({height:"toggle",bottom:!0===s?"-=80":""},300,(function(){e(this).css("position",!0===s?"relative":"static")})):e(this).animate({height:"toggle",bottom:!0===s?"-=60":""},300,(function(){e(this).css("position",!0===s?"relative":"static")})))})),e(".mystickyelements-position-"+n+"top ul li").each((function(){1==e(this).hasClass(m)&&(e(this).css("position","relative"),1==e(".mystickyelements-fixed").hasClass("mystickyelements-size-large")?e(this).animate({height:"toggle",top:!0===s?"-=80":""},300,(function(){e(this).css("position",!0===s?"relative":"static")})):e(this).animate({height:"toggle",top:!0===s?"-=60":""},300,(function(){e(this).css("position",!0===s?"relative":"static")})))})),!0===e("span.mystickyelements-minimize").hasClass("minimize-position-"+n+"left")?!0===e("li.mystickyelements-minimize").hasClass("element-minimize")?e(".mystickyelements-minimize.minimize-position-"+n+"left").html("&rarr;"):e(".mystickyelements-minimize.minimize-position-"+n+"left").html("&larr;"):!0===e("span.mystickyelements-minimize").hasClass("minimize-position-"+n+"bottom")?!0===e("li.mystickyelements-minimize").hasClass("element-minimize")?e(".mystickyelements-minimize.minimize-position-"+n+"bottom").html("&uarr;"):e(".mystickyelements-minimize.minimize-position-"+n+"bottom").html("&darr;"):!0===e("span.mystickyelements-minimize").hasClass("minimize-position-"+n+"top")?!0===e("li.mystickyelements-minimize").hasClass("element-minimize")?e(".mystickyelements-minimize.minimize-position-"+n+"top").html("&darr;"):e(".mystickyelements-minimize.minimize-position-"+n+"top").html("&uarr;"):!0===e("li.mystickyelements-minimize").hasClass("element-minimize")?e(".mystickyelements-minimize.minimize-position-"+n+"right").html("&larr;"):e(".mystickyelements-minimize.minimize-position-"+n+"right").html("&rarr;")})),e(".mystickyelements-fixed ul li").each((function(){if(e(this).hasClass("mystickyelements-custom-html-main")&&e(this).hasClass("mystickyelements-custom-html-iframe"))e(this).find(".mystickyelements-custom-html").height(),e(".mystickyelements-fixed ul").height()})),setTimeout((function(){e(".mystickyelements-entry-effect-fade.entry-effect,.mystickyelements-entry-effect-slide-in.entry-effect").css("transition","all 0s ease 0s")}),1e3),e(".mystickyelements-fixed ul li").on("click",(function(){e(this).hasClass("mystickyelements-custom-html-iframe")?e(".mystickyelements-fixed").toggleClass("mystickyelements-custom-html-iframe-open"):e(".mystickyelements-fixed").removeClass("mystickyelements-custom-html-iframe-open")})),e(".mystickyelements-fixed").addClass("entry-effect"),e(window).width()>1024)&&(e(".mystickyelements-position-bottom .mystickyelements-lists").width()<300&&e(".mystickyelements-position-bottom .mystickyelements-contact-form .element-contact-form").width("300"));if(a(),1==e("#phone_formate").val()){var n=document.querySelector("#contact-form-phone");window.intlTelInput(n,{dropdownContainer:document.body,initialCountry:"auto",separateDialCode:!0,utilsScript:mystickyelements.plugin_url+"intl-tel-input-src/build/js/utils.js"});e("#contact-form-phone").addClass("tel_formate")}})),e(window).on("resize",(function(){c(),a()})),jQuery(document).on("click",".mystickyelements-social-text a",(function(){m=0,r(e(this))})),jQuery(document).on("click",".mystickyelements-social-icon a",(function(){var t=l(),s=e(this);"mobile"==t?"hover"==e(this).data("tab-setting")&&"enable"!==e(this).data("mobile-behavior")||"click"==e(this).data("tab-setting")&&"enable"!==e(this).data("flyout")?r(s):m>1&&(r(s),m=0):"enable"!==e(this).data("flyout")?r(s):m>1&&(r(s),m=0)})),jQuery("body").mouseup((function(t){0===e(t.target).closest(".mystickyelement-lists-wrap").length&&(m=0,jQuery(".mystickyelements-social-icon-li,.mystickyelements-contact-form").removeClass("elements-active"),(e(".mystickyelements-social-icon-li").hasClass("elements-default-active")||e(".mystickyelements-contact-form").hasClass("elements-default-active"))&&localStorage.setItem("elements-default-active",!0))})),jQuery(document).on("click",".iti--allow-dropdown",(function(){jQuery(this).closest(".mystickyelements-contact-form").addClass("country-code-trigger"),jQuery(this).closest(".mystickyelements-contact-form").removeClass("element-contact-active"),jQuery(this).closest(".mystickyelements-contact-form").addClass("elements-active")})),jQuery(document).on("click","ul.iti__country-list li",(function(){e(".mystickyelements-contact-form").each((function(t){"hover"==jQuery(this).data("tab-opt")&&1==e(this).data("isphone-formate")&&e(this).hasClass("elements-active")?(jQuery(this).addClass("element-contact-active"),jQuery(this).removeClass("elements-active"),jQuery(this).removeClass("country-code-trigger")):(jQuery(this).removeClass("element-contact-active"),jQuery(this).addClass("elements-active"),jQuery(this).removeClass("country-code-trigger"))}))}))}(jQuery);
(function (factory){
"use strict";
if(typeof define==='function'&&define.amd){
define(['jquery'], factory);
}else if(typeof exports==='object'&&typeof require==='function'){
factory(require('jquery'));
}else{
factory(jQuery);
}}(function ($){
'use strict';
var utils=(function (){
return {
escapeRegExChars: function (value){
return value.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
},
formatHtml: function (string){
return string.replace(/&/g, '&amp;')
.replace(/&amp;amp;/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;')
.replace(/&lt;sup/g, '<sup')
.replace(/&lt;\/sup/g, '</sup')
.replace(/sup&gt;/g, 'sup>')
.replace(/&lt;sub/g, '<sub')
.replace(/&lt;\/sub/g, '</sub')
.replace(/sub&gt;/g, 'sub>')
.replace(/&lt;br\s?\/?&gt;/g, '<br/>')
.replace(/&lt;(\/?(strong|b|br|span|i))&gt;/g, '<$1>')
.replace(/&lt;(strong|span|i)\s+class\s*=\s*&quot;([^&]+)&quot;&gt;/g, '<$1 class="$2">');
},
createNode: function (containerClass){
var div=document.createElement('div');
div.className=containerClass;
div.style.position='absolute';
div.style.display='none';
div.setAttribute('unselectable', 'on');
return div;
},
matchGreekAccents: function (phrase){
if(!/[\u0370-\u03FF\u1F00-\u1FFF]+/.test(phrase)){
return phrase;
}
phrase=phrase.normalize('NFD').replace(/[\u0300-\u036f]/g, "");
var accents={
'Α': 'Ά',
'α': 'ά',
'Ε': 'Έ',
'ε': 'έ',
'Ι': 'Ί',
'ι': 'ί',
'ϊ': 'ΐ',
'Υ': 'Ύ',
'υ': 'ύ',
'ϋ': 'ΰ',
'Η': 'Ή',
'η': 'ή',
'Ο': 'Ό',
'ο': 'ό',
'Ω': 'Ώ',
'ω': 'ώ'
};
for (let [key, value] of Object.entries(accents)){
if(phrase.indexOf(key) > -1){
phrase=phrase.replaceAll(key, '[' + key + value + ']');
}}
return phrase;
},
highlight: function (suggestionValue, phrase){
var i,
tokens=phrase.split(/ /),
highlighted=false,
last='';
if(tokens){
last=tokens[tokens.length - 1];
tokens=tokens.sort(function (a, b){
return b.length - a.length;
});
for (i=0; i < tokens.length; i++){
if(tokens[i]&&tokens[i].length >=1){
var token=tokens[i].replace(/[\^\@]/g, '');
if(token.length > 0){
if(token.trim().length===1&&tokens[i]!==last){
var pattern='((\\s|^)' + utils.escapeRegExChars(token.trim()) + '\\s)';
pattern=utils.matchGreekAccents(pattern);
}else if(token.trim().length===1&&tokens[i]===last){
var pattern='((\\s|^)' + utils.escapeRegExChars(token.trim()) + ')';
pattern=utils.matchGreekAccents(pattern);
}else{
var pattern='(' + utils.escapeRegExChars(token.trim()) + ')';
pattern=utils.matchGreekAccents(pattern);
}
suggestionValue=suggestionValue.replace(new RegExp(pattern, 'gi'), '\^\^$1\@\@');
highlighted=true;
}}
}}
if(highlighted){
suggestionValue=suggestionValue.replace(/\^\^/g, '<strong>');
suggestionValue=suggestionValue.replace(/@@/g, '<\/strong>');
}
return suggestionValue;
},
debounce: function (func, wait){
var timeout,
debounceID=new Date().getUTCMilliseconds();
if(ajaxDebounceState.id.length===0){
ajaxDebounceState.id=debounceID;
func();
return;
}
ajaxDebounceState.id=debounceID;
timeout=setTimeout(function (){
if(debounceID!==ajaxDebounceState.id){
clearTimeout(timeout);
return;
}
func();
ajaxDebounceState.id='';
}, wait);
},
mouseHoverDebounce: function (func, selector, wait){
var timeout;
timeout=setTimeout(function (){
if($(selector + ':hover').length > 0){
func();
}else{
clearTimeout(timeout);
return;
}}, wait);
},
isTextSelected: function (){
var selected=false,
selObj=document.getSelection();
if(typeof selObj=='object'){
if(selObj.toString().length > 0){
selected=true;
}}
return selected
},
getActiveInstance: function (){
var $el=$('.dgwt-wcas-search-wrapp.dgwt-wcas-active'),
instance;
if($el.length > 0){
$el.each(function (){
var $input=$(this).find('.dgwt-wcas-search-input');
if(typeof $input.data('autocomplete')=='object'){
instance=$input.data('autocomplete');
return false;
}});
}
return instance;
},
hashCode: function (s){
var h=0, i=s.length;
while (i > 0){
h=(h << 5) - h + s.charCodeAt(--i) | 0;
}
return h < 0 ? h * -1:h;
},
isBrowser: function (browser){
return navigator.userAgent.indexOf(browser)!==-1;
},
isSafari: function (){
return this.isBrowser('Safari')&&!this.isBrowser('Chrome');
},
isIOS: function (){
var platform=navigator?.userAgent||navigator?.platform||'unknown';
return /iPhone|iPod|iPad/.test(platform)
|| (navigator.userAgent.includes("Mac")&&"ontouchend" in document)
},
isIE11: function (){
return !!navigator.userAgent.match(/Trident\/7\./);
},
setLocalStorageItem: function (key, value){
try {
window.localStorage.setItem(key,
JSON.stringify(value)
);
} catch (error){
}},
getLocalStorageItem: function (key, defaultValue){
try {
const item=window.localStorage.getItem(key);
return item ? JSON.parse(item):defaultValue;
} catch (error){
return defaultValue;
}},
removeLocalStorageItem: function (key){
try {
window.localStorage.removeItem(key);
} catch (error){
}}
};}()),
ajaxDebounceState={
id: '',
callback: null,
ajaxSettings: null,
object: null,
},
keys={
ESC: 27,
TAB: 9,
RETURN: 13,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
},
noop=$.noop;
function DgwtWcasAutocompleteSearch(el, options){
var that=this;
that.element=el;
that.el=$(el);
that.suggestions=[];
that.badQueries=[];
that.selectedIndex=-1;
that.currentValue=that.element.value;
that.timeoutId=null;
that.cachedResponse={};
that.cachedDetails={};
that.cachedPrices={};
that.detailsRequestsSent=[];
that.onChangeTimeout=null;
that.onChange=null;
that.isLocal=false;
that.suggestionsContainer=null;
that.detailsContainer=null;
that.autoAligmentprocess=null;
that.noSuggestionsContainer=null;
that.latestActivateSource='';
that.actionTriggerSource='';
that.options=$.extend(true, {}, DgwtWcasAutocompleteSearch.defaults, options);
that.classes={
selected: 'dgwt-wcas-suggestion-selected',
suggestion: 'dgwt-wcas-suggestion',
suggestionsContainerOrientTop: 'dgwt-wcas-suggestions-wrapp--top',
inputFilled: 'dgwt-wcas-search-filled',
darkenOverlayMounted: 'js-dgwt-wcas-search-darkoverl-mounted',
fixed: 'dgwt-wcas-suggestions-wrapp-fixed',
initialized: 'dgwt-wcas-suggestions-wrapp-initialized'
};
that.hint=null;
that.hintValue='';
that.selection=null;
that.overlayMobileState='off';
that.overlayDarkenedState='off';
that.isMouseDownOnSearchElements=false;
that.isPreSuggestionsMode=false;
that.voiceSearchRecognition=null;
that.voiceSearchStarted=null;
that.recentlyViewedProductsKey='fibosearch_recently_viewed_products';
that.recentlySearchedPhrasesKey='fibosearch_recently_searched_phrases';
that.initialize();
that.setOptions(options);
}
DgwtWcasAutocompleteSearch.utils=utils;
$.DgwtWcasAutocompleteSearch=DgwtWcasAutocompleteSearch;
DgwtWcasAutocompleteSearch.defaults={
ajaxSettings: {},
autoSelectFirst: false,
appendTo: 'body',
serviceUrl: null,
lookup: null,
onSelect: null,
containerDetailsWidth: 'auto',
showDetailsPanel: false,
showImage: false,
showPrice: false,
showSKU: false,
showDescription: false,
showSaleBadge: false,
showFeaturedBadge: false,
dynamicPrices: false,
saleBadgeText: 'sale',
featuredBadgeText: 'featured',
minChars: 3,
maxHeight: 600,
dpusbBreakpoint: 550,
deferRequestBy: 0,
params: {},
formatResult: _formatResult,
delimiter: null,
zIndex: 999999999,
type: 'GET',
noCache: false,
isRtl: false,
onSearchStart: noop,
onSearchComplete: noop,
onSearchError: noop,
preserveInput: false,
searchFormClass: 'dgwt-wcas-search-wrapp',
containerClass: 'dgwt-wcas-suggestions-wrapp',
containerDetailsClass: 'dgwt-wcas-details-wrapp',
preSuggestionsWrappClass: 'dgwt-wcas-pre-suggestions-wrapp',
darkenedOverlayClass: 'dgwt-wcas-darkened-overlay',
searchInputClass: 'dgwt-wcas-search-input',
preloaderClass: 'dgwt-wcas-preloader',
closeTrigger: 'dgwt-wcas-close',
formClass: 'dgwt-wcas-search-form',
voiceSearchClass: 'dgwt-wcas-voice-search',
voiceSearchSupportedClass: 'dgwt-wcas-voice-search-supported',
voiceSearchActiveClass: 'dgwt-wcas-voice-search-active',
voiceSearchDisabledClass: 'dgwt-wcas-voice-search-disabled',
tabDisabled: false,
dataType: 'text',
currentRequest: null,
triggerSelectOnValidInput: true,
isPremium: false,
overlayMobile: false,
preventBadQueries: true,
lookupFilter: _lookupFilter,
paramName: 'query',
transformResult: _transformResult,
noSuggestionNotice: 'No results',
forceFixPosition: false,
positionFixed: false,
debounceWaitMs: 400,
sendGAEvents: true,
enableGASiteSearchModule: false,
showProductVendor: false,
disableHits: false,
disableSubmit: false,
voiceSearchEnabled: false,
voiceSearchLang: '',
showRecentlySearchedProducts: false,
showRecentlySearchedPhrases: false,
goToFirstVariationOnSubmit: true,
}
function _lookupFilter(suggestion, originalQuery, queryLowerCase){
return suggestion.value.toLowerCase().indexOf(queryLowerCase)!==-1;
}
function _transformResult(response){
return typeof response==='string' ? JSON.parse(response):response;
}
function _formatResult(suggestionValue, currentValue, highlight){
if(currentValue.length > 0&&highlight){
suggestionValue=utils.highlight(suggestionValue, currentValue);
}
return utils.formatHtml(suggestionValue);
}
DgwtWcasAutocompleteSearch.prototype={
initialize: function (){
var that=this;
that.element.setAttribute('autocomplete', 'off');
that.options.params=that.applyCustomParams(that.options.params);
that.createContainers();
that.registerEventsSearchBar();
that.registerEventsSuggestions();
that.registerEventsDetailsPanel();
that.registerIconHandler();
that.registerFlexibleLayout();
that.initVoiceSearch();
that.fixPosition=function (){
that.adjustContainerWidth();
if(that.visible){
that.fixPositionSuggestions();
if(that.canShowDetailsPanel()){
that.fixPositionDetailsPanel();
}}
that.positionOverlayDarkened();
};
$(window).on('resize.autocomplete', function (){
var that=utils.getActiveInstance();
clearTimeout(window.dgwt_wcas.resizeOnlyOnce);
if(typeof that!='undefined'){
window.dgwt_wcas.resizeOnlyOnce=setTimeout(function (){
that.fixPosition();
}, 100);
}});
$(window).on('scroll.autocomplete', function (){
var that=utils.getActiveInstance();
clearTimeout(window.dgwt_wcas.scrollOnlyOnce);
if(typeof that!='undefined'){
window.dgwt_wcas.scrollOnlyOnce=setTimeout(function (){
that.fixPosition();
}, 100);
}});
var windowWidth=$(window).width();
$(window).on('resize.autocomplete', function (){
var newWidth=$(window).width();
if(newWidth!=windowWidth){
that.toggleMobileOverlayMode();
windowWidth=newWidth;
}});
if(that.isBreakpointReached('mobile-overlay')){
that.activateMobileOverlayMode();
}
that.hideAfterClickOutsideListener();
that.getFormWrapper().addClass(that.classes.initialized);
that.suggestionsContainer.addClass('js-dgwt-wcas-initialized');
if(that.detailsContainer&&that.detailsContainer.length > 0){
that.detailsContainer.addClass('js-dgwt-wcas-initialized');
}},
createContainers: function (type){
var that=this,
options=that.options;
if($('.' + options.containerClass).length==0){
that.suggestionsContainer=$(DgwtWcasAutocompleteSearch.utils.createNode(options.containerClass));
that.suggestionsContainer.appendTo(options.appendTo||'body');
that.suggestionsContainer.addClass('woocommerce');
if(options.showImage===true){
that.suggestionsContainer.addClass('dgwt-wcas-has-img');
}
if(options.showPrice===true){
that.suggestionsContainer.addClass('dgwt-wcas-has-price');
}
if(options.showDescription===true){
that.suggestionsContainer.addClass('dgwt-wcas-has-desc');
}
if(options.showSKU===true){
that.suggestionsContainer.addClass('dgwt-wcas-has-sku');
}
if(options.showHeadings===true){
that.suggestionsContainer.addClass('dgwt-wcas-has-headings');
}}else{
that.suggestionsContainer=$('.' + that.options.containerClass);
}
if(that.canShowDetailsPanel()){
if($('.' + options.containerDetailsClass).length==0){
that.detailsContainer=$(DgwtWcasAutocompleteSearch.utils.createNode(options.containerDetailsClass));
that.detailsContainer.appendTo(options.appendTo||'body');
that.detailsContainer.addClass('woocommerce');
}else{
that.detailsContainer=$('.' + options.containerDetailsClass);
}}
},
registerEventsSearchBar: function (){
var that=this;
that.el.on('fibosearch/ping', function (){
that.el.addClass('fibosearch-pong');
});
that.getForm().on('submit.autocomplete', function (e){
if(that.options.disableSubmit){
e.preventDefault();
return false;
}
var $input=$(this).find('.' + that.options.searchInputClass);
if($input.length&&$input.val().length===0){
e.preventDefault();
return false;
}
if(that.options.goToFirstVariationOnSubmit){
if(that.suggestions.length > 0){
$.each(that.suggestions, function (i, suggestion){
if(typeof suggestion.type!='undefined'
&& suggestion.type=='product_variation'
){
that.select(i);
e.preventDefault();
return false;
}});
}}
if(that.options.showRecentlySearchedPhrases){
that.saveHistorySearches($input.val());
}
that.closeOverlayMobile();
});
that.positionPreloaderAndMic();
$(window).on('load', function (){
that.positionPreloaderAndMic();
});
that.el.on('keydown.autocomplete', function (e){
that.onKeyPress(e);
});
that.el.on('keyup.autocomplete', function (e){
that.onKeyUp(e);
});
that.el.on('blur.autocomplete', function (){
that.onBlur();
});
that.el.on('focus.autocomplete', function (e){
that.onFocus(e);
});
that.el.on('change.autocomplete', function (e){
that.onKeyUp(e);
});
that.el.on('input.autocomplete', function (e){
that.onKeyUp(e);
});
},
registerEventsSuggestions: function (){
var that=this,
suggestionSelector='.' + that.classes.suggestion,
suggestionsContainer=that.getSuggestionsContainer();
if(suggestionsContainer.hasClass('js-dgwt-wcas-initialized')){
return;
}
$(document).on('mouseenter.autocomplete', suggestionSelector, function (){
var that=utils.getActiveInstance();
if(typeof that=='undefined'){
return;
}
var currentIndex=$(this).data('index');
var selector='.dgwt-wcas-suggestion[data-index="' + currentIndex + '"]';
var timeOffset=that.canShowDetailsPanel() ? 100:1;
if(that.selectedIndex!=currentIndex){
if(that.suggestions[currentIndex].type=='headline'
|| that.suggestions[currentIndex].type=='headline-v2'){
return;
}
utils.mouseHoverDebounce(function (){
if(that.selectedIndex!==currentIndex){
that.latestActivateSource='mouse';
that.getDetails(that.suggestions[currentIndex]);
that.activate(currentIndex);
}}, selector, timeOffset);
}});
var alreadyClicked=false;
$(document).on('click.autocomplete', suggestionSelector, function (e){
if(!alreadyClicked){
var that=utils.getActiveInstance();
that.actionTriggerSource='click';
alreadyClicked=true;
setTimeout(function (){
alreadyClicked=false;
}, 500);
if(typeof e.ctrlKey==='undefined'||e.ctrlKey===false){
that.select($(this).data('index'));
e.preventDefault();
}}else{
e.preventDefault();
}});
$(document).on('mousedown.autocomplete', suggestionSelector, function (e){
var _this=this;
if(e.button===0){
setTimeout(function (){
if(!alreadyClicked){
var that=utils.getActiveInstance();
that.select($(_this).data('index'));
}}, 250);
}});
$('.' + that.options.containerClass).on('mousedown.autocomplete', function (e){
var that=utils.getActiveInstance();
that.isMouseDownOnSearchElements=true;
});
$(document).on('click', '.js-dgwt-wcas-sugg-hist-clear', function (){
that.resetPreSuggestions();
});
},
registerEventsDetailsPanel: function (){
var that=this,
detailsContainer=that.getDetailsContainer();
if(!that.canShowDetailsPanel()||detailsContainer.hasClass('js-dgwt-wcas-initialized')){
return;
}
$(document).on('change.autocomplete', '[name="js-dgwt-wcas-quantity"]', function (e){
var $input=$(this).closest('.js-dgwt-wcas-pd-addtc').find('[data-quantity]');
$input.attr('data-quantity', $(this).val());
});
$('.' + that.options.containerDetailsClass).on('mousedown.autocomplete', function (e){
var that=utils.getActiveInstance();
that.isMouseDownOnSearchElements=true;
});
},
registerIconHandler: function (){
var that=this,
$formWrapper=that.getFormWrapper(),
$form=that.getForm();
$formWrapper.on('click.autocomplete', '.js-dgwt-wcas-search-icon-handler', function (e){
var $input=$formWrapper.find('.' + that.options.searchInputClass);
if($formWrapper.hasClass('dgwt-wcas-layout-icon-open')){
that.hide();
$form.hide(true);
$formWrapper.removeClass('dgwt-wcas-layout-icon-open');
}else{
var $arrow=$formWrapper.find('.dgwt-wcas-search-icon-arrow');
$form.hide();
$arrow.hide();
$formWrapper.addClass('dgwt-wcas-layout-icon-open');
that.positionIconSearchMode($formWrapper);
$form.fadeIn(50, function (){
$arrow.show();
that.positionPreloaderAndMic($formWrapper);
var textEnd=that.currentValue.length;
if(textEnd > 0){
$input[0].setSelectionRange(textEnd, textEnd);
}
$input.trigger('focus');
});
setTimeout(function (){
that.fixPosition();
}, 110);
}
return false;
});
if($('.js-dgwt-wcas-initialized').length==0&&$('.js-dgwt-wcas-search-icon-handler').length > 0){
$(document).on('click.autocomplete', function (event){
if($('.dgwt-wcas-layout-icon-open').length){
var $target=$(event.target);
if(!($target.closest('.' + that.options.searchFormClass).length > 0
|| $target.closest('.' + that.options.containerClass).length > 0
|| $target.closest('.' + that.options.containerDetailsClass).length > 0
|| $target.hasClass('js-dgwt-wcas-sugg-hist-clear')
)){
that.hideIconModeSearch();
}}
});
}},
registerFlexibleLayout: function (){
var that=this;
var windowWidth=$(window).width();
$(window).on('resize.autocomplete', function (){
var newWidth=$(window).width();
if(newWidth!=windowWidth){
that.reloadFlexibleLayout();
windowWidth=newWidth;
}});
that.reloadFlexibleLayout();
$(window).on('load.autocomplete', function (){
that.reloadFlexibleLayout();
});
},
activateMobileOverlayMode: function (){
var that=this,
$formWrapper=that.getFormWrapper(),
$iconHandler=$formWrapper.find('.js-dgwt-wcas-search-icon-handler');
if($formWrapper.hasClass('js-dgwt-wcas-mobile-overlay-enabled')
&& !$formWrapper.find('.js-dgwt-wcas-enable-mobile-form').length
){
var aria=typeof dgwt_wcas.labels.mob_overlay_label==='string' ? dgwt_wcas.labels.mob_overlay_label:'';
$formWrapper.prepend('<a href="#" aria-label="' + aria + '" class="js-dgwt-wcas-enable-mobile-form dgwt-wcas-enable-mobile-form"></a>');
$formWrapper.addClass('dgwt-wcas-mobile-overlay-trigger-active');
if($iconHandler.length){
$iconHandler.attr('tabindex', '-1');
}
var $el=$formWrapper.find('.js-dgwt-wcas-enable-mobile-form');
$el.on('click.autocomplete', function (e){
if(that.options.mobileOverlayDelay > 0){
setTimeout(function (){
that.showMobileOverlay();
}, that.options.mobileOverlayDelay);
}else{
that.showMobileOverlay();
}
return false;
});
}},
deactivateMobileOverlayMode: function (){
var that=this,
$formWrapper=that.getFormWrapper(),
$iconHandler=$formWrapper.find('.js-dgwt-wcas-search-icon-handler');
var $el=$formWrapper.find('.js-dgwt-wcas-enable-mobile-form');
if($formWrapper.hasClass('js-dgwt-wcas-mobile-overlay-enabled')
&& $el.length
){
that.closeOverlayMobile();
$el.remove();
$formWrapper.removeClass('dgwt-wcas-mobile-overlay-trigger-active');
if($iconHandler.length){
$iconHandler.removeAttr('tabindex');
}}
},
toggleMobileOverlayMode: function (){
var that=this,
$formWrapper=that.getFormWrapper(),
isMobOverlayEnabled=false;
if(!$formWrapper.hasClass('js-dgwt-wcas-mobile-overlay-enabled')){
return;
}
if($formWrapper.find('.js-dgwt-wcas-enable-mobile-form').length){
isMobOverlayEnabled=true;
}
if((!isMobOverlayEnabled&&that.isBreakpointReached('mobile-overlay'))
|| (isMobOverlayEnabled&&!that.isBreakpointReached('mobile-overlay'))
){
var $suggestionsWrapper=that.getSuggestionsContainer();
that.close(false);
if($suggestionsWrapper.length){
$suggestionsWrapper.html('');
}
that.hideIconModeSearch();
}
if(!isMobOverlayEnabled&&that.isBreakpointReached('mobile-overlay')){
that.activateMobileOverlayMode();
}
if(isMobOverlayEnabled&&!that.isBreakpointReached('mobile-overlay')){
that.deactivateMobileOverlayMode();
}},
showMobileOverlay: function (){
var that=this;
if(that.overlayMobileState==='on'){
return;
}
that.overlayMobileState='on';
var zIndex=99999999999,
$wrapper=that.getFormWrapper(),
$suggestionsWrapp=that.getSuggestionsContainer(),
$overlayWrap,
html='';
$('html').addClass('dgwt-wcas-overlay-mobile-on');
$('html').addClass('dgwt-wcas-open-' + that.getSearchStyle());
html +='<div class="js-dgwt-wcas-overlay-mobile dgwt-wcas-overlay-mobile">';
html +='<div class="dgwt-wcas-om-bar js-dgwt-wcas-om-bar">';
html +='<button class="dgwt-wcas-om-return js-dgwt-wcas-om-return">'
if(typeof dgwt_wcas.back_icon=='string'){
html +=dgwt_wcas.back_icon;
}
html +='</button>';
html +='</div>';
html +='</div>';
$(that.options.mobileOverlayWrapper).append(html);
$overlayWrap=$('.js-dgwt-wcas-overlay-mobile');
$overlayWrap.css('zIndex', zIndex);
$wrapper.after('<span class="js-dgwt-wcas-om-hook"></span>');
$wrapper.appendTo('.js-dgwt-wcas-om-bar');
$suggestionsWrapp.appendTo('.js-dgwt-wcas-om-bar');
$wrapper.addClass('dgwt-wcas-search-wrapp-mobile');
if($wrapper.hasClass('dgwt-wcas-has-submit')){
$wrapper.addClass('dgwt-wcas-has-submit-off');
$wrapper.removeClass('dgwt-wcas-has-submit');
}
$wrapper.find('.' + that.options.searchInputClass).trigger('focus');
$(document).on('click.autocomplete', '.js-dgwt-wcas-om-return', function (e){
that.closeOverlayMobile($overlayWrap);
});
document.dispatchEvent(new CustomEvent('fibosearch/show-mobile-overlay', {
detail: that
}));
},
closeOverlayMobile: function ($overlayWrap){
var that=this;
if(!$('html').hasClass('dgwt-wcas-overlay-mobile-on')){
that.overlayMobileState='off';
return;
}
var $suggestionsWrapp=that.getSuggestionsContainer();
var $clonedForm=$('.js-dgwt-wcas-om-bar').find('.' + that.options.searchFormClass);
if($clonedForm.hasClass('dgwt-wcas-has-submit-off')){
$clonedForm.removeClass('dgwt-wcas-has-submit-off');
$clonedForm.addClass('dgwt-wcas-has-submit');
}
$clonedForm.removeClass('dgwt-wcas-search-wrapp-mobile');
$('html').removeClass('dgwt-wcas-overlay-mobile-on');
$('html').removeClass('dgwt-wcas-open-' + that.getSearchStyle());
$suggestionsWrapp.appendTo('body');
$suggestionsWrapp.removeAttr('body-scroll-lock-ignore');
$('.js-dgwt-wcas-om-hook').after($clonedForm);
$('.js-dgwt-wcas-overlay-mobile').remove();
$('.js-dgwt-wcas-om-hook').remove();
setTimeout(function (){
$clonedForm.find('.' + that.options.searchInputClass).val('');
var $closeBtn=$clonedForm.find('.dgwt-wcas-close');
if($clonedForm.length > 0){
$closeBtn.removeClass('dgwt-wcas-close');
$closeBtn.html('');
}
that.hide();
}, 150);
that.overlayMobileState='off';
document.dispatchEvent(new CustomEvent('fibosearch/hide-mobile-overlay', {
detail: that
}));
},
reloadFlexibleLayout: function (){
var that=this,
$searchWrapp=that.getFormWrapper(),
flexibleMode=0,
$iconPreloader=$searchWrapp.find('.dgwt-wcas-icon-preloader');
if($searchWrapp.hasClass('js-dgwt-wcas-layout-icon-flexible')){
flexibleMode=1;
}
if($searchWrapp.hasClass('js-dgwt-wcas-layout-icon-flexible-inv')){
flexibleMode=2;
}
if(flexibleMode > 0){
if((flexibleMode===1&&that.isBreakpointReached('search-layout'))
|| (flexibleMode===2&&!that.isBreakpointReached('search-layout'))
){
$searchWrapp.addClass('js-dgwt-wcas-layout-icon');
$searchWrapp.addClass('dgwt-wcas-layout-icon');
}else{
$searchWrapp.removeClass('js-dgwt-wcas-layout-icon');
$searchWrapp.removeClass('dgwt-wcas-layout-icon');
}
$searchWrapp.addClass('dgwt-wcas-layout-icon-flexible-loaded');
if($iconPreloader.length){
$iconPreloader.remove();
}}
},
onFocus: function (e){
var that=this,
$formWrapper=that.getFormWrapper(),
options=that.options;
$('.' + options.searchFormClass).removeClass('dgwt-wcas-active');
$formWrapper.addClass('dgwt-wcas-active');
$('body').addClass('dgwt-wcas-focused');
$formWrapper.addClass('dgwt-wcas-search-focused');
if($(e.target).closest('.dgwt-wcas-search-wrapp-mobile').length==0){
that.enableOverlayDarkened();
}
that.fixPosition();
if(that.el.val().length===0){
if(that.canShowPreSuggestions()){
that.showPreSuggestions();
}}else if(that.el.val().length >=that.options.minChars){
that.onValueChange();
}},
onBlur: function (){
var that=this,
options=that.options,
value=that.el.val(),
query=that.getQuery(value),
isMobileOverlayOnIPhone=false;
$('body').removeClass('dgwt-wcas-focused');
$('.' + options.searchFormClass).removeClass('dgwt-wcas-search-focused');
if(utils.isIOS()&&$('html').hasClass('dgwt-wcas-overlay-mobile-on')){
isMobileOverlayOnIPhone=true;
}
if(!(that.isMouseDownOnSearchElements||isMobileOverlayOnIPhone)){
that.hide();
if(that.selection&&that.currentValue!==query){
(options.onInvalidateSelection||$.noop).call(that.element);
}}
document.dispatchEvent(new CustomEvent('fibosearch/close', {
detail: that
}));
},
abortAjax: function (){
var that=this;
if(that.currentRequest){
that.currentRequest.abort();
that.currentRequest=null;
}},
setOptions: function (suppliedOptions){
var that=this,
$suggestionsContainer=that.getSuggestionsContainer(),
options=$.extend({}, that.options, suppliedOptions);
that.isLocal=Array.isArray(options.lookup);
if(that.isLocal){
options.lookup=that.verifySuggestionsFormat(options.lookup);
}
$suggestionsContainer.css({
'max-height': !that.canShowDetailsPanel() ? options.maxHeight + 'px':'none',
'z-index': options.zIndex
});
if(that.canShowDetailsPanel()){
var $detailsContainer=that.getDetailsContainer();
$detailsContainer.css({
'z-index': (options.zIndex - 1)
});
}
options.onSearchComplete=function (){
var $searchForm=that.getFormWrapper();
$searchForm.removeClass('dgwt-wcas-processing');
that.preloader('hide', 'form', 'dgwt-wcas-inner-preloader');
that.showCloseButton();
};
this.options=options;
},
clearCache: function (){
this.cachedResponse={};
this.cachedDetails={};
this.cachedPrices={};
this.badQueries=[];
},
clear: function (cache){
if(cache){
this.clearCache();
}
this.currentValue='';
this.suggestions=[];
},
close: function (focus){
var that=this,
$el=that.el.closest('.' + that.options.searchFormClass).find('.' + that.options.searchInputClass),
$wrapp=that.getFormWrapper();
that.hide();
that.clear(false);
that.hideCloseButton();
$el.val('');
$wrapp.removeClass(that.classes.inputFilled);
if(focus){
$el.trigger('focus');
}},
fixPositionSuggestions: function (){
var that=this,
$suggestions=that.getSuggestionsContainer(),
$formEl=that.getForm(),
$input=that.el,
formData=that.getElementInfo($formEl),
inputData=that.getElementInfo($input),
offset={
top: inputData.top + inputData.height,
left: formData.left
};
if(that.ancestorHasPositionFixed($formEl)){
offset.top=inputData.topViewPort + inputData.height;
$suggestions.addClass(that.classes.fixed);
}else{
$suggestions.removeClass(that.classes.fixed);
}
that.getSuggestionsContainer().css(offset);
},
fixPositionDetailsPanel: function (){
var that=this,
$searchBar=that.getFormWrapper(),
$suggestions=that.getSuggestionsContainer(),
$detailsPanel=that.getDetailsContainer(),
$formEl=that.getForm(),
$input=that.el,
formData=that.getElementInfo($formEl),
inputData=that.getElementInfo($input),
offset={
top: inputData.top + inputData.height,
left: formData.left + $suggestions.outerWidth(false)
};
if(that.ancestorHasPositionFixed($searchBar)){
offset.top=inputData.topViewPort + inputData.height;
$detailsPanel.addClass(that.classes.fixed);
}else{
$detailsPanel.removeClass(that.classes.fixed)
}
$detailsPanel.css(offset);
$('body').removeClass('dgwt-wcas-full-width dgwt-wcas-details-outside dgwt-wcas-details-right dgwt-wcas-details-left dgwt-wcas-details-notfit');
if($searchBar.outerWidth() >=that.options.dpusbBreakpoint){
$('body').addClass('dgwt-wcas-full-width');
if(that.options.isRtl===true){
offset.left=formData.left + $detailsPanel.outerWidth(false);
$suggestions.css('left', offset.left);
$detailsPanel.css('left', formData.left);
}
return;
}
var windowWidth=$(window).width(),
cDWidth=$detailsPanel.outerWidth(),
cOffset=$detailsPanel.offset();
$('body').addClass('dgwt-wcas-details-outside dgwt-wcas-details-right');
if(windowWidth < (cOffset.left + cDWidth)){
$('body').removeClass('dgwt-wcas-details-right');
$('body').addClass('dgwt-wcas-details-left');
offset.left=$suggestions.offset().left - $detailsPanel.outerWidth(false);
$detailsPanel.css('left', offset.left);
cOffset=$detailsPanel.offset();
}
if(cOffset.left < 1){
$('body').removeClass('dgwt-wcas-details-left dgwt-wcas-details-right');
$('body').addClass('dgwt-wcas-details-notfit');
}},
fixHeight: function (){
var that=this;
var $suggestionsWrapp=that.getSuggestionsContainer(),
$detailsWrapp=that.getDetailsContainer();
$suggestionsWrapp.css('height', 'auto');
$detailsWrapp.css('height', 'auto');
if(!that.canShowDetailsPanel()){
$suggestionsWrapp.css('height', 'auto');
return false;
}
var sH=$suggestionsWrapp.outerHeight(false),
dH=$detailsWrapp.outerHeight(false),
minHeight=340;
$suggestionsWrapp.find('.dgwt-wcas-suggestion:last-child').removeClass('dgwt-wcas-suggestion-no-border-bottom');
if(sH <=minHeight&&dH <=minHeight){
return false;
}
$suggestionsWrapp.find('.dgwt-wcas-suggestion:last-child').addClass('dgwt-wcas-suggestion-no-border-bottom');
if(dH < sH){
$detailsWrapp.css('height', (sH) + 'px');
}
if(sH < dH){
$suggestionsWrapp.css('height', dH + 'px');
}
return false;
},
automaticAlignment: function (){
var that=this,
$input=that.getFormWrapper().find('.dgwt-wcas-search-input'),
$suggestionsContainer=that.getSuggestionsContainer(),
$detailsWrapp=that.getDetailsContainer();
if(that.autoAligmentprocess!=null){
return;
}
var markers=[$input.width(), $suggestionsContainer.height()];
if(that.canShowDetailsPanel()){
markers[2]=$detailsWrapp.height();
}
that.autoAligmentprocess=setInterval(function (){
var newMarkers=[$input.width(), $suggestionsContainer.height()];
if(that.canShowDetailsPanel()){
newMarkers[2]=$detailsWrapp.height();
}
for (var i=0; i < markers.length; i++){
if(markers[i]!=newMarkers[i]){
that.fixHeight();
that.fixPosition();
markers=newMarkers;
break;
}}
if(that.canShowDetailsPanel()){
var innerDetailsHeight=$detailsWrapp.find('.dgwt-wcas-details-inner').height();
if((innerDetailsHeight - $detailsWrapp.height()) > 2){
that.fixHeight();
}}
}, 10);
},
getElementInfo: function ($el){
var data={},
viewPort,
offset;
viewPort=$el[0].getBoundingClientRect();
offset=$el.offset();
data.left=offset.left;
data.top=offset.top;
data.width=$el.outerWidth(false);
data.height=$el.outerHeight(false);
data.right=data.left + data.width;
data.bottom=data.top + data.height;
data.topViewPort=viewPort.top;
data.bottomViewPort=viewPort.top + data.height;
return data;
},
getFormWrapper: function (){
var that=this;
return that.el.closest('.' + that.options.searchFormClass);
},
getForm: function (){
var that=this;
return that.el.closest('.' + that.options.formClass);
},
getSuggestionsContainer: function (){
var that=this;
return $('.' + that.options.containerClass);
},
getDetailsContainer: function (){
var that=this;
return $('.' + that.options.containerDetailsClass);
},
scrollDownSuggestions: function (){
var that=this,
$el=that.getSuggestionsContainer();
$el[0].scrollTop=$el[0].scrollHeight;
},
isCursorAtEnd: function (){
var that=this,
valLength=that.el.val().length,
selectionStart=that.element.selectionStart,
range;
if(typeof selectionStart==='number'){
return selectionStart===valLength;
}
if(document.selection){
range=document.selection.createRange();
range.moveStart('character', -valLength);
return valLength===range.text.length;
}
return true;
},
onKeyPress: function (e){
var that=this,
$wrapp=that.getFormWrapper();
that.addActiveClassIfMissing();
if(!that.visible&&e.keyCode===keys.DOWN&&that.currentValue){
that.suggest();
return;
}
if(!that.visible){
if(e.keyCode===keys.ESC&&$wrapp.hasClass('dgwt-wcas-layout-icon-open')){
that.hideIconModeSearch();
}
if(e.keyCode===keys.ESC&&that.isMountedOverlayDarkened()){
that.disableOverlayDarkened();
that.el.blur();
}
if(e.keyCode===keys.ESC&&$('html').hasClass('dgwt-wcas-overlay-mobile-on')){
that.closeOverlayMobile();
}
return;
}
if((e.ctrlKey||e.metaKey)&&e.keyCode===keys.RETURN){
if(that.selectedIndex > -1){
that.openInNewTab(that.selectedIndex);
}
return;
}
switch (e.keyCode){
case keys.ESC:
that.close();
break;
case keys.RIGHT:
if(that.hint&&that.options.onHint&&that.isCursorAtEnd()){
that.selectHint();
break;
}
return;
case keys.TAB:
break;
case keys.RETURN:
if(that.selectedIndex===-1){
if(that.options.disableSubmit){
return false;
}
that.hide();
return;
}
that.actionTriggerSource='enter';
that.select(that.selectedIndex);
break;
case keys.UP:
that.moveUp();
break;
case keys.DOWN:
that.moveDown();
break;
default:
return;
}
e.stopImmediatePropagation();
e.preventDefault();
},
onKeyUp: function (e){
var that=this;
switch (e.keyCode){
case keys.UP:
case keys.DOWN:
return;
}
clearTimeout(that.onChangeTimeout);
if(that.currentValue!==that.el.val()){
if(that.options.deferRequestBy > 0){
that.onChangeTimeout=setTimeout(function (){
that.onValueChange();
}, that.options.deferRequestBy);
}else{
that.onValueChange();
}}
},
onValueChange: function (){
if(this.ignoreValueChange){
this.ignoreValueChange=false;
return;
}
var that=this,
options=that.options,
value=that.el.val(),
query=that.getQuery(value),
$wrapp=that.getFormWrapper();
if(that.selection&&that.currentValue!==query){
that.selection=null;
(options.onInvalidateSelection||$.noop).call(that.element);
}
clearTimeout(that.onChangeTimeout);
that.currentValue=value;
that.selectedIndex=-1;
if(options.triggerSelectOnValidInput&&that.isExactMatch(query)){
that.select(0);
return;
}
if(query.length > 0){
if(!$wrapp.hasClass(that.classes.inputFilled)){
$wrapp.addClass(that.classes.inputFilled);
}}else{
$wrapp.removeClass(that.classes.inputFilled);
}
if(query.length < options.minChars){
that.hideCloseButton();
that.hide();
if(that.canShowPreSuggestions()&&query.length===0){
that.showPreSuggestions();
}}else{
if(that.canShowPreSuggestions()){
that.hidePreSuggestions()
}
that.getSuggestions(query);
}},
isExactMatch: function (query){
var suggestions=this.suggestions;
return (suggestions.length===1&&suggestions[0].value.toLowerCase()===query.toLowerCase());
},
isNoResults: function (suggestions){
var isNoResults=false;
if(typeof suggestions!='undefined'
&& suggestions.length===1
&& typeof suggestions[0].type!=='undefined'
&& suggestions[0].type==='no-results'
){
isNoResults=true;
}
return isNoResults;
},
canShowDetailsPanel: function (){
var that=this,
show=that.options.showDetailsPanel;
if($(window).width() < 768||('ontouchend' in document)||that.isPreSuggestionsMode||that.isNoResults(that.suggestions)){
show=false;
}
return show;
},
isBreakpointReached: function (context){
var that=this,
breakpoint=0;
switch (context){
case 'search-layout':
breakpoint=that.options.layoutBreakpoint;
if(that.isSetParam('layout_breakpoint')){
breakpoint=Number.parseInt(that.getParam('layout_breakpoint'));
}
break;
case 'mobile-overlay':
breakpoint=that.options.mobileOverlayBreakpoint;
if(that.isSetParam('mobile_overlay_breakpoint')){
breakpoint=Number.parseInt(that.getParam('mobile_overlay_breakpoint'));
}
break;
}
return window.innerWidth <=breakpoint;
},
getQuery: function (value){
var delimiter=this.options.delimiter,
parts;
if(!delimiter){
return value.trim();
}
parts=value.split(delimiter);
return $.trim(parts[parts.length - 1]);
},
getSuggestionsLocal: function (query){
var that=this,
options=that.options,
queryLowerCase=query.toLowerCase(),
filter=options.lookupFilter,
limit=parseInt(options.lookupLimit, 10),
data;
data={
suggestions: $.grep(options.lookup, function (suggestion){
return filter(suggestion, query, queryLowerCase);
})
};
if(limit&&data.suggestions.length > limit){
data.suggestions=data.suggestions.slice(0, limit);
}
return data;
},
getSuggestions: function (q){
var response,
that=this,
options=that.options,
serviceUrl=options.serviceUrl,
searchForm=that.getFormWrapper(),
params,
cacheKey,
ajaxSettings,
iconSearchActive=that.isActiveIconModeSearch();
options.params[options.paramName]=q;
if(typeof dgwt_wcas.current_lang!='undefined'){
options.params['l']=dgwt_wcas.current_lang;
}
that.preloader('show', 'form', 'dgwt-wcas-inner-preloader');
searchForm.addClass('dgwt-wcas-processing');
if(options.onSearchStart.call(that.element, options.params)===false){
return;
}
params=options.ignoreParams ? null:options.params;
if(typeof options.lookup==='function'){
options.lookup(q, function (data){
that.suggestions=data.suggestions;
that.suggest();
that.selectFirstSuggestion(data.suggestions);
options.onSearchComplete.call(that.element, q, data.suggestions);
});
return;
}
if(!$('body').hasClass('dgwt-wcas-open')){
document.dispatchEvent(new CustomEvent('fibosearch/open', {
detail: that
}));
}
if(that.isLocal){
response=that.getSuggestionsLocal(q);
}else{
if(typeof serviceUrl==='function'){
serviceUrl=serviceUrl.call(that.element, q);
}
cacheKey=serviceUrl + '?' + $.param(params||{});
response=that.cachedResponse[cacheKey];
}
if(response&&Array.isArray(response.suggestions)){
that.suggestions=response.suggestions;
that.suggest();
that.selectFirstSuggestion(response.suggestions);
options.onSearchComplete.call(that.element, q, response.suggestions);
that.updatePrices();
if(that.isNoResults(response.suggestions)){
document.dispatchEvent(new CustomEvent('fibosearch/no-results', {
detail: that
}));
}else{
document.dispatchEvent(new CustomEvent('fibosearch/show-suggestions', {
detail: that
}));
}}else if(!that.isBadQuery(q)){
that.abortAjax();
ajaxSettings={
url: serviceUrl,
data: params,
type: options.type,
dataType: options.dataType
};
$.extend(ajaxSettings, options.ajaxSettings);
ajaxDebounceState.object=that;
ajaxDebounceState.ajaxSettings=ajaxSettings;
utils.debounce(function (){
var that=ajaxDebounceState.object,
ajaxSettings=ajaxDebounceState.ajaxSettings;
that.currentRequest=$.ajax(ajaxSettings).done(function (data){
if(iconSearchActive&&!that.isActiveIconModeSearch()){
return;
}
var result;
that.currentRequest=null;
result=that.options.transformResult(data, q);
if(typeof result.suggestions!=='undefined'){
that.processResponse(result, q, cacheKey);
that.selectFirstSuggestion(result.suggestions);
if(that.isNoResults(result.suggestions)){
that.gaEvent(q, 'Autocomplete Search without results');
}else{
that.gaEvent(q, 'Autocomplete Search with results');
}}
that.fixPosition();
that.options.onSearchComplete.call(that.element, q, result.suggestions);
that.updatePrices();
if(that.isNoResults(result.suggestions)){
document.dispatchEvent(new CustomEvent('fibosearch/no-results', {
detail: that
}));
}else{
document.dispatchEvent(new CustomEvent('fibosearch/show-suggestions', {
detail: that
}));
}}).fail(function (jqXHR, textStatus, errorThrown){
that.options.onSearchError.call(that.element, q, jqXHR, textStatus, errorThrown);
});
}, options.debounceWaitMs);
}else{
options.onSearchComplete.call(that.element, q, []);
}},
getDetails: function (suggestion){
var that=this;
if(!that.canShowDetailsPanel()){
return false;
}
if(suggestion==null||typeof suggestion.type=='undefined'){
return;
}
if(typeof suggestion.type=='string'&&suggestion.type==='more_products'){
return;
}
that.fixHeight();
var $containerDetails=that.getDetailsContainer(),
currentObjectID=that.prepareSuggestionObjectID(suggestion),
result;
result=that.cachedDetails[currentObjectID];
if(result!=null){
that.detailsPanelSetScene(currentObjectID);
that.fixHeight();
that.fixPosition();
}else{
var data={
action: dgwt_wcas.action_result_details,
items: []
};
$.each(that.suggestions, function (i, suggestion){
if(typeof suggestion.type!='undefined'
&& suggestion.type!='more_products'
&& suggestion.type!='headline'
){
var itemData={
objectID: that.prepareSuggestionObjectID(suggestion),
value: suggestion.value!=null ? suggestion.value:''
};
data.items.push(itemData);
}});
that.detailsPanelClearScene();
that.preloader('show', 'details', '');
if($.inArray(currentObjectID, that.detailsRequestsSent)!=-1){
return;
}else{
that.detailsRequestsSent.push(currentObjectID);
}
$.ajax({
data: data,
type: 'post',
url: dgwt_wcas.ajax_details_endpoint,
success: function (response){
var result=typeof response==='string' ? JSON.parse(response):response;
if(typeof result.items!='undefined'){
for (var i=0; i < result.items.length; i++){
var cacheKey=result.items[i]['objectID'];
that.cachedDetails[cacheKey]={html: result.items[i]['html']}
that.detailsPanelAddToScene(cacheKey);
if(typeof result.items[i]['price']!='undefined'&&result.items[i]['price'].length > 0){
that.cachedPrices[cacheKey]=result.items[i]['price'];
}}
}
that.preloader('hide', 'details', '');
var currentObjectID=that.prepareSuggestionObjectID(that.suggestions[that.selectedIndex]);
if(that.cachedDetails[currentObjectID]!=null){
that.detailsPanelSetScene(currentObjectID);
}else{
that.detailsPanelClearScene();
}
that.fixPosition();
that.fixHeight();
that.updatePrices(true);
},
error: function (jqXHR, exception){
that.preloader('hide', 'details', '');
that.detailsPanelClearScene();
that.fixPosition();
that.fixHeight();
},
});
}
$(document).trigger('dgwtWcasDetailsPanelLoaded', that);
},
updatePrices: function (noAjax){
var that=this,
i,
productsToLoad=[];
if(!(that.options.showPrice&&that.options.dynamicPrices)){
return;
}
if(that.suggestions.length==0){
return;
}
for (i=0; i < that.suggestions.length; i++){
if(typeof that.suggestions[i].type!='undefined'
&& (that.suggestions[i].type=='product'||that.suggestions[i].type=='product_variation')
){
var key='';
if(typeof that.suggestions[i].variation_id!=='undefined'){
key='product__' + that.suggestions[i].variation_id;
}else{
key='product__' + that.suggestions[i].post_id;
}
if(typeof that.cachedPrices[key]!='undefined'){
that.updatePrice(i, that.cachedPrices[key]);
}else{
that.applyPreloaderForPrice(i);
if(typeof that.suggestions[i].variation_id!=='undefined'){
productsToLoad.push(that.suggestions[i].variation_id);
}else{
productsToLoad.push(that.suggestions[i].post_id);
}}
}}
if(!noAjax&&productsToLoad.length > 0){
var data={
action: typeof dgwt_wcas.action_get_prices=='undefined' ? 'dgwt_wcas_get_prices':dgwt_wcas.action_get_prices,
items: productsToLoad
};
$.ajax({
data: data,
type: 'post',
url: dgwt_wcas.ajax_prices_endpoint,
success: function (response){
if(typeof response.success!='undefined'
&& response.success
&& Object.keys(response.data).length > 0
&& that.suggestions.length > 0
){
for (i=0; i < that.suggestions.length; i++){
if(typeof that.suggestions[i].type!=='undefined'
&& that.suggestions[i].type==='product'
&& typeof response.data[that.suggestions[i].post_id]==='string'
){
key='product__' + that.suggestions[i].post_id;
that.cachedPrices[key]=response.data[that.suggestions[i].post_id];
that.updatePrice(i, response.data[that.suggestions[i].post_id]);
}else if(typeof that.suggestions[i].type!=='undefined'
&& that.suggestions[i].type==='product_variation'
&& typeof that.suggestions[i].variation_id!=='undefined'
&& typeof response.data[that.suggestions[i].variation_id]==='string'
){
key='product__' + that.suggestions[i].variation_id;
that.cachedPrices[key]=response.data[that.suggestions[i].variation_id];
that.updatePrice(i, response.data[that.suggestions[i].variation_id]);
}}
}},
error: function (jqXHR, exception){
},
});
}},
updatePrice: function (index, price){
var that=this;
if(typeof that.suggestions[index]!='undefined'){
that.suggestions[index].price=price;
var $price=$('.dgwt-wcas-suggestions-wrapp').find('[data-index="' + index + '"] .dgwt-wcas-sp');
if($price.length){
$price.html(price);
}}
},
applyCustomParams: function (params){
var that=this;
if(typeof dgwt_wcas.custom_params=='object'){
var cp=dgwt_wcas.custom_params;
for (var property in cp){
params[property]=cp[property];
}}
var inputCustomParams=that.el.data('custom-params');
if(typeof inputCustomParams==='object'){
for (var property in inputCustomParams){
params[property]=inputCustomParams[property];
}}
return params;
},
isSetParam: function (param){
var that=this;
return typeof that.options.params[param]!='undefined';
},
getParam: function (param){
var that=this;
return that.isSetParam(param) ? that.options.params[param]:'';
},
applyPreloaderForPrice: function (index){
var that=this;
if(typeof that.suggestions[index]!='undefined'){
var $price=$('.dgwt-wcas-suggestions-wrapp').find('[data-index="' + index + '"] .dgwt-wcas-sp');
if($price.length){
$price.html('<div class="dgwt-wcas-preloader-price"><div class="dgwt-wcas-preloader-price-inner"> <div></div><div></div><div></div></div></div>');
}}
},
prepareSuggestionObjectID: function (suggestion){
var objectID='';
if(typeof suggestion!='undefined'&&typeof suggestion.type!='undefined'){
if(suggestion.post_id!=null){
objectID=suggestion.type + '__' + suggestion.post_id;
if(suggestion.type==='product_variation'){
objectID +='__' + suggestion.variation_id;
}
if(typeof suggestion.post_type!='undefined'){
objectID=suggestion.type + '__' + suggestion.post_id + '__' + suggestion.post_type;
}}
if(suggestion.term_id!=null&&suggestion.taxonomy!=null){
objectID=suggestion.type + '__' + suggestion.term_id + '__' + suggestion.taxonomy;
}}
return objectID;
},
detailsPanelSetScene: function (objectID){
var that=this,
$containerDetails=that.getDetailsContainer(),
objectHash=utils.hashCode(objectID),
$el=$containerDetails.find('.dgwt-wcas-details-inner[data-object="' + objectHash + '"]');
document.dispatchEvent(new CustomEvent('fibosearch/show-details-panel', {
detail: that
}));
if($el.length){
that.preloader('hide', 'details', '');
that.detailsPanelClearScene();
$el.addClass('dgwt-wcas-details-inner-active');
}},
detailsPanelAddToScene: function (objectID){
var that=this,
$containerDetails=that.getDetailsContainer(),
object=that.cachedDetails[objectID],
objectHash=utils.hashCode(objectID),
html='';
if(typeof object!='undefined'&&typeof object.html=='string'){
html=object.html.replace('<div ', '<div data-object="' + objectHash + '" ');
}
if($containerDetails.find('.dgwt-wcas-details-inner[data-object="' + objectHash + '"]').length==0){
$containerDetails.append(html);
}},
detailsPanelClearScene: function (){
var that=this,
$containerDetails=that.getDetailsContainer(),
$views=$containerDetails.find('.dgwt-wcas-details-inner');
if($views.length){
$views.removeClass('dgwt-wcas-details-inner-active');
}},
selectFirstSuggestion: function (suggestions){
var that=this,
index=0,
noResults=false;
if(!that.canShowDetailsPanel()){
return;
}
if(suggestions!='undefined'&&suggestions.length > 0){
$.each(that.suggestions, function (i, suggestion){
if(typeof suggestion.type!='undefined'
&& suggestion.type!='more_products'
&& suggestion.type!='headline'
&& suggestion.type!='headline-v2'
&& suggestion.type!='no-results'
){
index=i;
return false;
}
if(typeof suggestion.type==='undefined'||suggestion.type==='no-results'){
noResults=true;
}});
}
if(noResults){
return;
}
that.latestActivateSource='system';
that.getDetails(suggestions[index]);
that.activate(index);
},
isBadQuery: function (q){
if(!this.options.preventBadQueries){
return false;
}
var badQueries=this.badQueries,
i=badQueries.length;
while (i--){
if(q.indexOf(badQueries[i])===0){
return true;
}}
return false;
},
hide: function (clear){
var that=this,
$suggestions=that.getSuggestionsContainer(),
$detailsPanel=that.getDetailsContainer();
if(typeof that.options.onHide==='function'&&that.visible){
that.options.onHide.call(that.element, container);
}
that.visible=false;
that.selectedIndex=-1;
clearTimeout(that.onChangeTimeout);
$suggestions.hide();
$suggestions.removeClass(that.classes.suggestionsContainerOrientTop);
$suggestions.removeClass(that.classes.fixed);
if(that.canShowDetailsPanel()){
$detailsPanel.hide();
$detailsPanel.removeClass(that.classes.fixed);
}
that.hidePreSuggestions();
$('body').removeClass('dgwt-wcas-open');
if(!$('html').hasClass('dgwt-wcas-overlay-mobile-on')){
var searchStyle=that.getSearchStyle();
$('html').removeClass('dgwt-wcas-open-' + searchStyle);
if(searchStyle==='pirx'){
$('html').removeClass('dgwt-wcas-open-pirx-compact');
}}
$('body').removeClass('dgwt-wcas-block-scroll');
$('body').removeClass('dgwt-wcas-is-details');
$('body').removeClass('dgwt-wcas-full-width');
$('body').removeClass('dgwt-wcas-nores');
$('body').removeClass('dgwt-wcas-details-outside');
$('body').removeClass('dgwt-wcas-details-right');
$('body').removeClass('dgwt-wcas-details-left');
if(that.autoAligmentprocess!=null){
clearInterval(that.autoAligmentprocess);
that.autoAligmentprocess=null;
}
that.isMouseDownOnSearchElements=false;
if(typeof clear=='boolean'&&clear){
that.hideCloseButton();
that.currentValue='';
that.suggestions=[];
}},
positionIconSearchMode: function ($formWrapper){
var that=this,
formLeftValue=-20,
$form=that.getForm(),
formWidth=$form.width(),
windowWidth=$(window).width();
var iconLeftOffset=$formWrapper[0].getBoundingClientRect().left;
var iconLeftRatio=(iconLeftOffset + 10) / windowWidth;
formLeftValue=Math.floor(-1 * (formWidth * iconLeftRatio));
formLeftValue=Math.max(formLeftValue, -1 * iconLeftOffset);
$form.css({'left': formLeftValue + 'px'});
},
isActiveIconModeSearch: function (){
var active=false,
$openedElements=$('.dgwt-wcas-layout-icon-open');
if($openedElements.length > 0){
active=true;
}
return active;
},
hideIconModeSearch: function (){
var that=this;
if(that.isActiveIconModeSearch()&&!utils.isTextSelected()){
$('.dgwt-wcas-layout-icon-open').removeClass('dgwt-wcas-layout-icon-open');
}},
hideAfterClickOutsideListener: function (){
var that=this;
if(!('ontouchend' in document)){
$(document).on('mouseup', function (e){
if(!that.visible){
return;
}
var outsideForm = !($(e.target).closest('.' + that.options.searchFormClass).length > 0||$(e.target).hasClass(that.options.searchFormClass)),
outsideContainer = !($(e.target).closest('.' + that.options.containerClass).length > 0||$(e.target).hasClass(that.options.containerClass));
if(!that.canShowDetailsPanel()){
if(outsideForm&&outsideContainer){
that.hide();
}}else{
var outsidecontainerDetails = !($(e.target).closest('.' + that.options.containerDetailsClass).length > 0||$(e.target).hasClass(that.options.containerDetailsClass));
if(outsideForm&&outsideContainer&&outsidecontainerDetails){
that.hide();
}}
});
}},
suggest: function (){
if(!this.suggestions.length){
this.hide();
return;
}
var that=this,
options=that.options,
groupBy=options.groupBy,
formatResult=options.formatResult,
value=that.getQuery(that.currentValue),
className=that.classes.suggestion,
classSelected=that.classes.selected,
container=that.getSuggestionsContainer(),
containerDetails=that.getDetailsContainer(),
noSuggestionsContainer=$(that.noSuggestionsContainer),
beforeRender=options.beforeRender,
html='',
category,
formatGroup=function (suggestion, index){
var currentCategory=suggestion.data[groupBy];
if(category===currentCategory){
return '';
}
category=currentCategory;
return '<div class="autocomplete-group"><strong>' + category + '</strong></div>';
};
if(options.triggerSelectOnValidInput&&that.isExactMatch(value)){
that.select(0);
return;
}
$('body').removeClass('dgwt-wcas-nores');
$.each(that.suggestions, function (i, suggestion){
var url=typeof suggestion.url=='string'&&suggestion.url.length ? suggestion.url:'#';
if(groupBy){
html +=formatGroup(suggestion, value, i);
}
if(typeof suggestion.type=='undefined'||(suggestion.type!='product')&&suggestion.type!='product_variation'){
var classes=className,
innerClass='dgwt-wcas-st',
prepend='',
append='',
title='',
highlight=true,
isImg,
noResults=false;
if(suggestion.taxonomy==='product_cat'){
classes +=' dgwt-wcas-suggestion-tax dgwt-wcas-suggestion-cat';
if(!options.showHeadings){
prepend +='<span class="dgwt-wcas-st--direct-headline">' + dgwt_wcas.labels['tax_' + suggestion.taxonomy] + '</span>';
}
if(typeof suggestion.breadcrumbs!='undefined'&&suggestion.breadcrumbs){
title=suggestion.breadcrumbs + ' &gt; ' + suggestion.value;
append +='<span class="dgwt-wcas-st-breadcrumbs"><span class="dgwt-wcas-st-label-in">' + dgwt_wcas.labels.in + ' </span>' + suggestion.breadcrumbs + '</span>';
}}else if(suggestion.taxonomy==='product_tag'){
classes +=' dgwt-wcas-suggestion-tax dgwt-wcas-suggestion-tag';
if(!options.showHeadings){
prepend +='<span class="dgwt-wcas-st--direct-headline">' + dgwt_wcas.labels['tax_' + suggestion.taxonomy] + '</span>';
}}else if(options.isPremium&&suggestion.taxonomy===options.taxonomyBrands){
classes +=' dgwt-wcas-suggestion-tax dgwt-wcas-suggestion-brand';
if(!options.showHeadings){
prepend +='<span class="dgwt-wcas-st--direct-headline">' + dgwt_wcas.labels['tax_' + suggestion.taxonomy] + '</span>';
}}else if(options.isPremium&&suggestion.type==='taxonomy'){
classes +=' dgwt-wcas-suggestion-tax dgwt-wcas-suggestion-tax-' + suggestion.taxonomy;
if(!options.showHeadings){
prepend +='<span class="dgwt-wcas-st--direct-headline">' + dgwt_wcas.labels['tax_' + suggestion.taxonomy] + '</span>';
}}else if(options.isPremium&&suggestion.type==='vendor'){
classes +=' dgwt-wcas-suggestion-vendor dgwt-wcas-suggestion-vendor';
if(!options.showHeadings){
prepend +='<span class="dgwt-wcas-st--direct-headline">' + dgwt_wcas.labels.vendor + '</span>';
}}else if(options.isPremium&&suggestion.type==='post'&&typeof suggestion.post_type!=='undefined'){
classes +=' dgwt-wcas-suggestion-pt dgwt-wcas-suggestion-pt-' + suggestion.post_type;
if(!options.showHeadings){
prepend +='<span class="dgwt-wcas-st--direct-headline">' + dgwt_wcas.labels['post_type_' + suggestion.post_type] + '</span>';
}}else if(suggestion.type==='more_products'){
classes +=' js-dgwt-wcas-suggestion-more dgwt-wcas-suggestion-more';
innerClass='dgwt-wcas-st-more';
suggestion.value=dgwt_wcas.labels.show_more + '<span class="dgwt-wcas-st-more-total"> (' + suggestion.total + ')</span>';
highlight=false;
}else if(options.showHeadings&&suggestion.type==='headline'){
classes +=' js-dgwt-wcas-suggestion-headline dgwt-wcas-suggestion-headline';
if(typeof dgwt_wcas.labels[suggestion.value + '_plu']!='undefined'){
suggestion.value=dgwt_wcas.labels[suggestion.value + '_plu'];
}
highlight=false;
}
if(suggestion.type==='no-results'){
$('body').addClass('dgwt-wcas-nores');
if(containerDetails.length){
that.detailsPanelClearScene();
containerDetails.hide();
containerDetails.removeClass(that.classes.fixed);
that.fixHeight();
}
suggestion.value='';
html +=that.createNoResultsContent();
}else{
if((typeof suggestion.image_src!='undefined'&&suggestion.image_src) ||
(typeof suggestion.image!='undefined'&&suggestion.image)
){
isImg=true;
}
prepend +=that.apply3rdPartyPlaceholder('title_before', suggestion);
append +=that.apply3rdPartyPlaceholder('title_after', suggestion);
title=title.length > 0 ? ' title="' + title.replace(/>/g, '&gt;') + '"':'';
html +='<a href="' + url + '" class="' + classes + '" data-index="' + i + '">';
if(isImg){
const imgSrc=suggestion.image_src ? suggestion.image_src:suggestion.image;
html +='<span class="dgwt-wcas-si"><img src="' + imgSrc + '" /></span>';
html +='<div class="dgwt-wcas-content-wrapp">';
}
html +='<span' + title + ' class="' + innerClass + '">';
if(suggestion.type==='vendor'){
html +='<span class="dgwt-wcas-st-title">' + prepend + formatResult(suggestion.value, value, highlight, options) + append + '</span>';
if(suggestion.shop_city){
html +='<span class="dgwt-wcas-vendor-city"><span> - </span>' + formatResult(suggestion.shop_city, value, true, options) + '</span>';
}
if(typeof suggestion.desc!='undefined'&&suggestion.desc){
html +='<span class="dgwt-wcas-sd">' + formatResult(suggestion.desc, value, true, options) + '</span>';
}}else{
html +=prepend + formatResult(suggestion.value, value, highlight, options) + append;
}
html +='</span>';
html +=isImg ? '</div>':'';
html +='</a>';
}}else{
html +=that.createProductSuggestion(suggestion, i);
}});
this.adjustContainerWidth();
noSuggestionsContainer.detach();
container.html(html);
if(typeof beforeRender==='function'){
beforeRender.call(that.element, container, that.suggestions);
}
container.show();
$('body').addClass('dgwt-wcas-open');
var searchStyle=that.getSearchStyle();
$('html').addClass('dgwt-wcas-open-' + searchStyle);
if(searchStyle==='pirx'){
$('html').addClass('dgwt-wcas-open-pirx-compact');
}
that.isMouseDownOnSearchElements=false;
that.automaticAlignment();
if(that.canShowDetailsPanel()){
$('body').addClass('dgwt-wcas-is-details');
containerDetails.show();
that.fixHeight();
}
if(options.autoSelectFirst){
that.selectedIndex=0;
container.scrollTop(0);
container.children('.' + className).first().addClass(classSelected);
}
that.visible=true;
that.fixPosition();
},
createNoResultsContent: function (){
var html='<div class="dgwt-wcas-suggestion-nores">',
defaultHtml=typeof dgwt_wcas.labels.no_results_default!='undefined' ? dgwt_wcas.labels.no_results_default:'',
noResultsHtml=defaultHtml;
try {
noResultsHtml=JSON.parse(dgwt_wcas.labels.no_results);
var tmpEl=document.createElement('div');
tmpEl.innerHTML=noResultsHtml;
noResultsHtml=tmpEl.innerHTML;
} catch (e){
}
html +=noResultsHtml;
html +='</div>';
return html;
},
createProductSuggestion: function (suggestion, index, extClassName){
var that=this,
html='',
parent='',
dataAttrs='',
options=that.options,
className=that.classes.suggestion,
isImg=false,
value=that.getQuery(that.currentValue),
formatResult=options.formatResult,
url=typeof suggestion.url=='string'&&suggestion.url.length ? suggestion.url:'#';
if(typeof extClassName=='string'){
className +=' ' + extClassName;
}
if(options.showImage===true&&typeof suggestion.thumb_html!='undefined'){
isImg=true;
}
var sugVarClass=suggestion.type==='product_variation' ? ' dgwt-wcas-suggestion-product-var':'';
dataAttrs +=typeof suggestion.post_id!='undefined' ? 'data-post-id="' + suggestion.post_id + '" ':'';
dataAttrs +=typeof suggestion.taxonomy!='undefined' ? 'data-taxonomy="' + suggestion.taxonomy + '" ':'';
dataAttrs +=typeof suggestion.term_id!='undefined' ? 'data-term-id="' + suggestion.term_id + '" ':'';
html +='<a href="' + url + '" class="' + className + ' dgwt-wcas-suggestion-product' + sugVarClass + '" data-index="' + index + '" ' + dataAttrs + '>';
if(isImg){
html +='<span class="dgwt-wcas-si">' + suggestion.thumb_html + '</span>';
}
html +=isImg ? '<div class="dgwt-wcas-content-wrapp">':'';
html +='<div class="dgwt-wcas-st">';
html +=that.apply3rdPartyPlaceholder('title_before', suggestion);
html +='<span class="dgwt-wcas-st-title">' + formatResult(suggestion.value, value, true, options) + parent + '</span>';
html +=that.apply3rdPartyPlaceholder('title_after', suggestion);
if(options.showSKU===true&&typeof suggestion.sku!='undefined'&&suggestion.sku.length > 0){
html +='<span class="dgwt-wcas-sku">(' + dgwt_wcas.labels.sku_label + ' ' + formatResult(suggestion.sku, value, true, options) + ')</span>';
}
if(options.showDescription===true&&typeof suggestion.desc!='undefined'&&suggestion.desc){
html +='<span class="dgwt-wcas-sd">' + formatResult(suggestion.desc, value, true, options) + '</span>';
}
if(options.showProductVendor===true&&typeof suggestion.vendor!='undefined'&&suggestion.vendor){
var vendorBody='<span class="dgwt-wcas-product-vendor"><span class="dgwt-wcas-product-vendor-label">' + dgwt_wcas.labels.vendor_sold_by + ' </span>' + suggestion.vendor + '</span>'
if(typeof suggestion.vendor_url!='undefined'&&suggestion.vendor_url){
html +='<span class="dgwt-wcas-product-vendor-link" data-url="' + suggestion.vendor_url + '">' + vendorBody + '</span>';
}else{
html +=vendorBody;
}}
html +=that.apply3rdPartyPlaceholder('content_after', suggestion);
if(typeof suggestion.score!=='undefined'){
html +='<div class="dgwt-wcas-score">Score: ' + suggestion.score + '</div>';
}
html +='</div>';
var showPrice=options.showPrice===true&&typeof suggestion.price!='undefined',
showMetaBefore=typeof suggestion.meta_before!='undefined',
showMetaAfter=typeof suggestion.meta_after!='undefined',
showMeta=showPrice||showMetaBefore||showMetaAfter;
html +=showMeta ? '<div class="dgwt-wcas-meta">':'';
if(showMetaBefore){
html +=that.apply3rdPartyPlaceholder('meta_before', suggestion);
}
if(showPrice){
html +='<span class="dgwt-wcas-sp">' + suggestion.price + '</span>';
}
if(showMetaAfter){
html +=that.apply3rdPartyPlaceholder('meta_after', suggestion);
}
html +=showMeta ? '</div>':'';
html +=isImg ? '</div>':'';
html +='</a>';
return html;
},
apply3rdPartyPlaceholder: function (name, suggestion){
var content='';
if(typeof suggestion[name]!='undefined'&&suggestion[name]){
content=suggestion[name];
}
return content;
},
getSearchStyle: function (){
var that=this,
$searchWrapp=that.getFormWrapper(),
style='solaris';
if(!$searchWrapp||$searchWrapp.length===0){
return style;
}
$($searchWrapp?.attr('class')?.split(/\s+/)).each(function (index){
if(/dgwt-wcas-style-/i.test(this)){
style=this.replace(/dgwt-wcas-style-/i, '');
}});
if(style==='pirx-compact'){
style='pirx';
}
return style;
},
adjustContainerWidth: function (){
var that=this,
$searchBar=that.getFormWrapper(),
$suggestions=that.getSuggestionsContainer(),
$detailsPanel=that.getDetailsContainer(),
$baseElement=that.getForm(),
baseWidth=$baseElement.outerWidth();
if(!$searchBar.length){
return;
}
$suggestions.css('width', baseWidth + 'px');
if(that.canShowDetailsPanel()&&baseWidth >=that.options.dpusbBreakpoint){
var measurementError=0;
$suggestions.css('width', baseWidth / 2);
$detailsPanel.css('width', baseWidth / 2);
measurementError=baseWidth - ($suggestions.outerWidth() + $detailsPanel.outerWidth());
if(measurementError!=0){
$detailsPanel.css('width', $detailsPanel.outerWidth() + measurementError);
}}
},
positionPreloaderAndMic: function ($formWrapper){
var that=this;
var $submit=typeof $formWrapper=='object' ? $formWrapper.find('.dgwt-wcas-search-submit'):$('.dgwt-wcas-search-submit');
if($submit.length > 0){
$submit.each(function (){
var $preloader=$(this).closest('.dgwt-wcas-search-wrapp').find('.dgwt-wcas-preloader'),
isSolarisStyle=$(this).closest('.dgwt-wcas-search-wrapp').hasClass('dgwt-wcas-style-solaris'),
isVoiceSearchSupported=$(this).closest('.dgwt-wcas-search-wrapp').hasClass(that.options.voiceSearchSupportedClass),
$voiceSearch=$(this).closest('.dgwt-wcas-search-wrapp').find('.' + that.options.voiceSearchClass);
if(isVoiceSearchSupported&&isSolarisStyle){
if(dgwt_wcas.is_rtl==1){
$voiceSearch.css('transform', 'translateX(' + $(this).outerWidth() + 'px)');
}else{
$voiceSearch.css('transform', 'translateX(-' + $(this).outerWidth() + 'px)');
}}
if(dgwt_wcas.is_rtl==1){
$preloader.css('left', $(this).outerWidth() + 'px');
}else{
$preloader.css('right', $(this).outerWidth() + 'px');
}});
}},
preloader: function (action, place, cssClass){
var that=this,
html,
$container,
defaultClass='dgwt-wcas-preloader-wrapp',
cssClasses=cssClass==null ? defaultClass:defaultClass + ' ' + cssClass;
if(place==='form'){
if(dgwt_wcas.show_preloader!=1){
return;
}
$container=that.getFormWrapper().find('.dgwt-wcas-preloader');
}else if(place==='details'){
$container=that.getDetailsContainer();
}
if($container.length==0){
return;
}
if(place==='form'){
if(action==='hide'){
$container.removeClass(cssClass);
$container.html('');
}else{
$container.addClass(cssClass);
if(typeof dgwt_wcas.preloader_icon=='string'){
$container.html(dgwt_wcas.preloader_icon);
}}
return;
}
var $preloader=$container.find('.' + defaultClass);
if(action==='hide'){
if($preloader.length){
$preloader.remove();
}
return
}
if(action==='show'){
var rtlSuffix=that.options.isRtl ? '-rtl':'';
html='<div class="' + cssClasses + '"><img class="dgwt-wcas-placeholder-preloader" src="' + dgwt_wcas.img_url + 'placeholder' + rtlSuffix + '.png" /></div>';
that.detailsPanelClearScene();
if($preloader.length){
$preloader.remove();
}
$container.prepend(html);
}},
verifySuggestionsFormat: function (suggestions){
if(suggestions.length&&typeof suggestions[0]==='string'){
return $.map(suggestions, function (value){
return {value: value, data: null};});
}
return suggestions;
},
processResponse: function (result, originalQuery, cacheKey){
var that=this,
options=that.options;
result.suggestions=that.verifySuggestionsFormat(result.suggestions);
if(!options.noCache){
that.cachedResponse[cacheKey]=result;
if(options.preventBadQueries&&!result.suggestions.length){
that.badQueries.push(originalQuery);
}}
if(originalQuery!==that.getQuery(that.currentValue)){
return;
}
that.suggestions=result.suggestions;
that.suggest();
},
activate: function (index){
var that=this,
activeItem,
selected=that.classes.selected,
container=that.getSuggestionsContainer(),
children=container.find('.' + that.classes.suggestion);
container.find('.' + selected).removeClass(selected);
that.selectedIndex=index;
if(that.selectedIndex!==-1&&children.length > that.selectedIndex){
activeItem=children.get(that.selectedIndex);
$(activeItem).addClass(selected);
return activeItem;
}
return null;
},
selectHint: function (){
var that=this,
i=$.inArray(that.hint, that.suggestions);
that.select(i);
},
select: function (i){
var that=this;
if(that.options.disableHits){
return;
}
if(typeof that.suggestions[i]=='undefined'){
return;
}
if(typeof that.suggestions[i]!='undefined'
&& (that.suggestions[i].type=='headline'||that.suggestions[i].type=='headline-v2')){
return;
}
that.closeOverlayMobile();
that.hide();
that.onSelect(i);
},
moveUp: function (){
var that=this;
if(that.selectedIndex===-1){
return;
}
that.latestActivateSource='key';
if(that.selectedIndex===0){
that.getSuggestionsContainer().children('.' + that.classes.suggestion).first().removeClass(that.classes.selected);
that.selectedIndex=-1;
that.ignoreValueChange=false;
that.el.val(that.currentValue);
return;
}
that.adjustScroll(that.selectedIndex - 1, 'up');
},
moveDown: function (){
var that=this;
if(that.selectedIndex===(that.suggestions.length - 1)){
return;
}
that.latestActivateSource='key';
that.adjustScroll(that.selectedIndex + 1, 'down');
},
adjustScroll: function (index, direction){
var that=this;
if(that.suggestions[index].type==='headline'){
index=direction==='down' ? index + 1:index - 1;
}
if(typeof that.suggestions[index]=='undefined'){
return;
}
var activeItem=that.activate(index);
that.getDetails(that.suggestions[index]);
if(that.suggestions[index].type==='more_products'){
return;
}
if(!activeItem||that.canShowDetailsPanel()){
return;
}
var offsetTop,
upperBound,
lowerBound,
$suggestionContainer=that.getSuggestionsContainer(),
heightDelta=$(activeItem).outerHeight(false);
offsetTop=activeItem.offsetTop;
upperBound=$suggestionContainer.scrollTop();
lowerBound=upperBound + that.options.maxHeight - heightDelta;
if(offsetTop < upperBound){
$suggestionContainer.scrollTop(offsetTop);
}else if(offsetTop > lowerBound){
$suggestionContainer.scrollTop(offsetTop - that.options.maxHeight + heightDelta);
}
if(!that.options.preserveInput){
that.ignoreValueChange=true;
}},
onSelect: function (index){
var that=this,
onSelectCallback=that.options.onSelect,
suggestion=that.suggestions[index],
forceSubmit=false;
if(typeof suggestion.type!='undefined'){
if(suggestion.type==='more_products'
|| (that.actionTriggerSource==='enter'&&that.latestActivateSource!='key'&&suggestion.type!='product_variation')
|| (that.actionTriggerSource==='enter'&&that.latestActivateSource!='key'&&suggestion.type=='product_variation'&&!that.options.goToFirstVariationOnSubmit)
){
that.el.closest('form').trigger('submit');
forceSubmit=true;
}
if(suggestion.type==='history-search'){
that.currentValue=that.getValue(suggestion.value);
if(that.currentValue!==that.el.val()&&!that.options.preserveInput){
that.el.val(that.currentValue.replace(/(<([^>]+)>)/gi, ' ').replace(/\s\s+/g, ' '));
}
that.el.closest('form').trigger('submit');
forceSubmit=true;
}}
if(suggestion.type==='product'||suggestion.type==='product_variation'){
if(that.options.showRecentlySearchedProducts){
that.saveHistoryProducts(suggestion);
}}
if(!forceSubmit){
that.currentValue=that.getValue(suggestion.value);
if(that.currentValue!==that.el.val()&&!that.options.preserveInput){
that.el.val(that.currentValue.replace(/(<([^>]+)>)/gi, ' ').replace(/\s\s+/g, ' '));
}
if(suggestion.url.length > 0){
window.location.href=suggestion.url;
}
that.suggestions=[];
that.selection=suggestion;
}
if(typeof onSelectCallback==='function'){
onSelectCallback.call(that.element, suggestion);
}},
openInNewTab: function (index){
var that=this,
suggestion=that.suggestions[index];
if(suggestion.url.length > 0){
window.open(suggestion.url, '_blank').trigger('focus');
}},
getValue: function (value){
var that=this,
delimiter=that.options.delimiter,
currentValue,
parts;
if(!delimiter){
return value;
}
currentValue=that.currentValue;
parts=currentValue.split(delimiter);
if(parts.length===1){
return value;
}
return currentValue.substr(0, currentValue.length - parts[parts.length - 1].length) + value;
},
dispose: function (){
var that=this,
$el=that.el,
$formWrapper=that.getFormWrapper(),
$suggestionsWrapper=that.getSuggestionsContainer(),
$mobileHandler=$formWrapper.find('.js-dgwt-wcas-enable-mobile-form');
if($formWrapper.length){
var $items=$formWrapper.find('*');
$items.each(function (){
$(this).off('.autocomplete');
});
}
$el.off('fibosearch/ping');
$formWrapper.off('click.autocomplete', '.js-dgwt-wcas-search-icon-handler');
$el.removeData('autocomplete');
$(window).off('resize.autocomplete', that.fixPosition);
$formWrapper.removeClass('dgwt-wcas-active');
that.close(false);
if($mobileHandler.length){
$mobileHandler.remove();
}
if($suggestionsWrapper.length){
$suggestionsWrapper.html('');
}},
isMountedOverlayDarkened: function (){
var that=this,
$wrapp=that.getFormWrapper(),
mounted=false;
if($wrapp.hasClass(that.classes.darkenOverlayMounted)){
mounted=true;
}
return mounted;
},
enableOverlayDarkened: function (){
var that=this,
options=that.options,
$formWrapper;
if(!that.isMountedOverlayDarkened()){
return;
}
$formWrapper=that.getFormWrapper();
$formWrapper.addClass('dgwt-wcas-search-darkoverl-on');
$('body').addClass('dgwt-wcas-darkoverl-on');
if($('.' + options.darkenedOverlayClass).length==0){
var html='<div class="' + options.darkenedOverlayClass + '"><div></div><div></div><div></div><div></div></div>';
$('body').append(html);
var $darkenedOverlay=$('.' + that.options.darkenedOverlayClass);
that.positionOverlayDarkened();
$darkenedOverlay.on('click.autocomplete', function (e){
that.disableOverlayDarkened();
});
}
that.overlayDarkenedState='on';
},
disableOverlayDarkened: function (){
var that=this,
options=that.options,
$wrapps;
if(!that.isMountedOverlayDarkened()){
return;
}
$wrapps=$('.dgwt-wcas-search-darkoverl-on');
if($wrapps.length){
$wrapps.removeClass('dgwt-wcas-search-darkoverl-on');
}
$('body').removeClass('dgwt-wcas-darkoverl-on');
var $el=$('.' + options.darkenedOverlayClass);
if($el.length > 0){
$el.remove();
that.overlayDarkenedState='off';
}},
positionOverlayDarkened: function (){
var that=this,
fixed=false,
$darkenedOverlay=$('.' + that.options.darkenedOverlayClass);
if($darkenedOverlay.length > 0){
if(that.ancestorHasPositionFixed(that.getFormWrapper())){
fixed=true;
$darkenedOverlay.addClass('dgwt-wcas-suggestions-wrapp-fixed');
}else{
$darkenedOverlay.removeClass('dgwt-wcas-suggestions-wrapp-fixed');
}
$darkenedOverlay.children('div').each(function (i){
that.positionOverlayDarkenedDiv($(this), i + 1, fixed);
});
}},
positionOverlayDarkenedDiv: function ($el, orient, fixed){
var that=this,
elData,
$baseEl=that.getFormWrapper(),
css,
secureOffset=200;
if($baseEl.hasClass('js-dgwt-wcas-layout-icon')){
$baseEl=that.getForm();
}
elData=that.getElementInfo($baseEl);
switch (orient){
case 1:
css={
left: (-secureOffset) + 'px',
top: (-secureOffset) + 'px',
width: (elData.left + secureOffset) + 'px',
height: ($(document).outerHeight(false) + secureOffset - 1) + 'px'
};
break;
case 2:
var topSpan=fixed ? elData.topViewPort:elData.top;
css={
left: (-secureOffset) + 'px',
top: (-secureOffset) + 'px',
width: ($(window).outerWidth(false) + secureOffset) + 'px',
height: (topSpan + secureOffset) + 'px',
};
break;
case 3:
css={
left: (elData.left + elData.width) + 'px',
top: (-secureOffset) + 'px',
width: ($(window).outerWidth(false) - elData.right) + 'px',
height: ($(document).outerHeight(false) + secureOffset - 1) + 'px'
};
break;
case 4:
var topSpan=fixed ? elData.topViewPort:elData.top;
css={
left: (-secureOffset) + 'px',
top: (topSpan + elData.height) + 'px',
width: ($(window).outerWidth(false) + secureOffset) + 'px',
height: ($(document).outerHeight(false) - elData.bottom - 1) + 'px'
};
break;
}
if(css){
$el.css(css);
}},
showCloseButton: function (){
var that=this,
iconBody=typeof dgwt_wcas.close_icon!='undefined' ? dgwt_wcas.close_icon:'',
$actionsEl=that.getFormWrapper().find('.' + that.options.preloaderClass);
if(that.el.val().length < that.options.minChars){
return;
}
if(!$actionsEl.hasClass(that.options.closeTrigger)){
$actionsEl.on('click.autocomplete', function (){
that.close(true);
});
}
$actionsEl.addClass(that.options.closeTrigger);
$actionsEl.html(iconBody);
},
hideCloseButton: function (){
var that=this,
$btn=that.getFormWrapper().find('.' + that.options.closeTrigger);
if($btn.length){
$btn.removeClass(that.options.closeTrigger);
$btn.html('');
}
$btn.off('click.autocomplete');
},
canShowPreSuggestions: function (){
var that=this,
canShow=false;
if(that.options.showRecentlySearchedProducts||that.options.showRecentlySearchedPhrases){
canShow=true;
}
return canShow;
},
showPreSuggestions: function (){
var that=this,
suggestionsIndex=0,
i,
html='',
$suggestionsWrapper=that.getSuggestionsContainer(),
$searchBar=that.getFormWrapper(),
noHistory=true,
historyProducts=[],
historySearches=[],
origShowImageOpt=that.options.showImage;
that.isPreSuggestionsMode=true;
that.suggestions=[];
that.suggestionsContainer.addClass('dgwt-wcas-has-img');
if(!origShowImageOpt){
that.suggestionsContainer.addClass('dgwt-wcas-has-img-forced');
}
that.options.showImage=true;
if(that.options.showRecentlySearchedProducts){
historyProducts=utils.getLocalStorageItem(that.recentlyViewedProductsKey, []);
}
if(that.options.showRecentlySearchedPhrases){
historySearches=utils.getLocalStorageItem(that.recentlySearchedPhrasesKey, []);
}
if(historyProducts.length===0&&historySearches.length===0){
return;
}
that.suggestions.push({type: 'headline-v2', value: '',});
html +='<span class="dgwt-wcas-suggestion dgwt-wcas-suggestion-headline-v2" data-index="' + suggestionsIndex + '">';
if(typeof dgwt_wcas.labels['search_hist']!='undefined'){
var label=dgwt_wcas.labels['search_hist'];
label +=' <span class="js-dgwt-wcas-sugg-hist-clear dgwt-wcas-sugg-hist-clear">' + dgwt_wcas.labels['search_hist_clear'] + '</span>';
html +='<span className="dgwt-wcas-st">' + label + '</span>';
}
html +='</span>';
suggestionsIndex++;
if(historyProducts.length > 0){
for (i=0; i < historyProducts.length; i++){
html +=that.createProductSuggestion(historyProducts[i], suggestionsIndex, 'dgwt-wcas-suggestion-history-product');
that.suggestions.push(historyProducts[i]);
suggestionsIndex++;
}}
if(historySearches.length > 0){
for (i=0; i < historySearches.length; i++){
var suggestion={
type: 'history-search',
value: historySearches[i],
url: '#',
thumb_html: dgwt_wcas.magnifier_icon
};
if($searchBar.hasClass('dgwt-wcas-style-pirx')){
suggestion.thumb_html=dgwt_wcas.magnifier_icon_pirx;
}
that.suggestions.push(suggestion);
html +='<a href="' + suggestion.url + '" class="' + that.classes.suggestion + ' dgwt-wcas-suggestion-history-search" data-index="' + suggestionsIndex + '">';
html +='<span class="dgwt-wcas-si">' + suggestion.thumb_html + '</span>';
html +='<div class="dgwt-wcas-content-wrapp">';
html +='<div class="dgwt-wcas-st"><span class="dgwt-wcas-st-title">' + utils.formatHtml(suggestion.value) + '</span></div>'
html +='</div>';
html +='</a>';
suggestionsIndex++;
}}
$suggestionsWrapper.html(html);
$suggestionsWrapper.show();
$('body').addClass('dgwt-wcas-open');
$('body').addClass('dgwt-wcas-open-pre-suggestions');
var searchStyle=that.getSearchStyle();
$('html').addClass('dgwt-wcas-open-' + that.getSearchStyle());
if(searchStyle==='pirx'){
$('html').addClass('dgwt-wcas-open-pirx-compact');
}
that.isMouseDownOnSearchElements=false;
that.visible=true;
that.fixPosition();
that.options.showImage=origShowImageOpt;
document.dispatchEvent(new CustomEvent('fibosearch/open', {
detail: that
}));
document.dispatchEvent(new CustomEvent('fibosearch/show-pre-suggestions', {
detail: that
}));
},
resetPreSuggestions: function (){
var that=this,
$suggestionsWrapp=that.getSuggestionsContainer(),
activeInstance=utils.getActiveInstance();
utils.removeLocalStorageItem(that.recentlyViewedProductsKey);
utils.removeLocalStorageItem(that.recentlySearchedPhrasesKey);
that.suggestions=[];
$suggestionsWrapp.html('');
$('body').removeClass('dgwt-wcas-open-pre-suggestions');
activeInstance.el.trigger('focus');
},
hidePreSuggestions: function (){
var that=this;
if(!that.options.showImage){
that.suggestionsContainer.removeClass('dgwt-wcas-has-img');
}
that.suggestionsContainer.removeClass('dgwt-wcas-has-img-forced');
that.isPreSuggestionsMode=false;
},
saveHistoryProducts: function (suggestion){
var that=this,
viewedProducts=utils.getLocalStorageItem(that.recentlyViewedProductsKey, []);
viewedProducts=[suggestion, ...viewedProducts];
viewedProducts=[...new Map(viewedProducts.map((item)=> {
if(typeof item['price']!='undefined'){
delete item['price'];
}
if(!that.options.showImage){
item['thumb_html']=dgwt_wcas.history_icon;
}
return [item['post_id'], item];
})).values()];
utils.setLocalStorageItem(that.recentlyViewedProductsKey, viewedProducts.slice(0, 5));
},
saveHistorySearches: function (value){
var that=this,
phrases=utils.getLocalStorageItem(that.recentlySearchedPhrasesKey, []);
phrases=[value, ...phrases];
phrases=[...new Set(phrases)];
utils.setLocalStorageItem(that.recentlySearchedPhrasesKey, phrases.slice(0, 5));
},
addActiveClassIfMissing: function (){
var activeEl=document.activeElement;
if(typeof activeEl=='object'
&& $(activeEl).length
&& $(activeEl).hasClass('dgwt-wcas-search-input')
){
var $search=$(activeEl).closest('.dgwt-wcas-search-wrapp');
if($search.length&&!$search.hasClass('dgwt-wcas-active')){
$search.addClass('dgwt-wcas-active');
}}
},
ancestorHasPositionFixed: function ($element){
var $checkElements=$element.add($element.parents());
var isFixed=false;
$checkElements.each(function (){
if($(this).css("position")==="fixed"){
isFixed=true;
return false;
}});
return isFixed;
},
gaEvent: function (label, category){
var that=this;
var gaObj=window.hasOwnProperty('GoogleAnalyticsObject')&&window.hasOwnProperty(window['GoogleAnalyticsObject']) ? window[window['GoogleAnalyticsObject']]:false;
if(that.options.sendGAEvents){
try {
if(typeof gtag!=='undefined'){
gtag('event', 'autocomplete_search', {
'event_label': label,
'event_category': category
});
}else if(gaObj!==false){
var tracker=gaObj.getAll()[0];
if(tracker) tracker.send({
hitType: 'event',
eventCategory: category,
eventAction: 'autocomplete_search',
eventLabel: label
});
}} catch (error){
}}
if(that.options.enableGASiteSearchModule){
try {
if(typeof gtag!=='undefined'){
gtag('event', 'page_view', {
'page_path': '/?s=' + encodeURI(label) + '&post_type=product&dgwt_wcas=1',
});
}else if(gaObj!==false){
var tracker2=gaObj.getAll()[0];
if(tracker2){
tracker2.set('page', '/?s=' + encodeURI(label) + '&post_type=product&dgwt_wcas=1');
tracker2.send('pageview');
}}
} catch (error){
}}
$(document).trigger('dgwtWcasGAEvent', {'term': label, 'category': category});
},
initVoiceSearch: function (){
var that=this;
if(!that.options.voiceSearchEnabled){
return false;
}
var $formWrapper=that.getFormWrapper();
var $input=$formWrapper.find('.' + that.options.searchInputClass);
var $voiceSearch=$formWrapper.find('.' + that.options.voiceSearchClass);
var speechRecognition=false;
if(typeof SpeechRecognition==="function"){
speechRecognition=SpeechRecognition;
}else if(typeof webkitSpeechRecognition==="function"){
speechRecognition=webkitSpeechRecognition;
}
if(!speechRecognition){
return false;
}
if(utils.isBrowser('Chrome')&&utils.isIOS()){
return false;
}
if(utils.isSafari()){
return false;
}
that.voiceSearchSetState('inactive', $voiceSearch);
$formWrapper.addClass(that.options.voiceSearchSupportedClass);
that.voiceSearchRecognition=new speechRecognition();
that.voiceSearchRecognition.lang=that.options.voiceSearchLang;
that.voiceSearchRecognition.continuous=false;
that.voiceSearchRecognition.interimResults=true;
that.voiceSearchRecognition.maxAlternatives=1;
$voiceSearch.on('click', function (){
if($formWrapper.hasClass('dgwt-wcas-mobile-overlay-trigger-active') &&
!$('html').hasClass('dgwt-wcas-overlay-mobile-on')
){
$formWrapper.find('.js-dgwt-wcas-enable-mobile-form').trigger('click');
$formWrapper.find('.' + that.options.searchInputClass).trigger('blur');
}
if(that.voiceSearchStarted){
that.voiceSearchAbort();
return;
}
if(that.voiceSearchIsInitialized()){
that.voiceSearchAbort();
}
that.voiceSearchRecognition.start();
});
that.voiceSearchRecognition.onstart=function (event){
that.voiceSearchSetState('active', $voiceSearch);
}
that.voiceSearchRecognition.onresult=function (event){
const result=event.results[0];
const text=result[0].transcript;
$input.val(text);
if(result.isFinal){
$input.trigger('change');
if(!('ontouchend' in document)){
$input.trigger('focus');
}
that.voiceSearchSetState('inactive', $voiceSearch);
}}
that.voiceSearchRecognition.onspeechend=function (){
that.voiceSearchSetState('inactive', $voiceSearch);
that.voiceSearchRecognition.stop();
}
that.voiceSearchRecognition.onnomatch=function (event){
that.voiceSearchSetState('inactive', $voiceSearch);
}
that.voiceSearchRecognition.onerror=function (event){
switch (event.error){
case 'aborted':
case 'no-speech':
that.voiceSearchSetState('inactive', $voiceSearch);
break;
case 'network':
break;
case 'not-allowed':
case 'service-not-allowed':
that.voiceSearchSetState('off', $voiceSearch);
break;
}}
},
voiceSearchAbort: function (){
var that=this;
if(that.voiceSearchIsInitialized()){
that.voiceSearchRecognition.abort();
that.voiceSearchStarted=false;
}},
voiceSearchIsInitialized: function (){
var that=this;
return that.voiceSearchRecognition!==null;
},
voiceSearchSetState: function (state, $voiceSearch){
var that=this;
switch (state){
case 'active':
that.voiceSearchStarted=true;
if(typeof dgwt_wcas.voice_search_active_icon=='string'){
$voiceSearch.html(dgwt_wcas.voice_search_active_icon);
}
break;
case 'inactive':
that.voiceSearchStarted=false;
if(typeof dgwt_wcas.voice_search_inactive_icon=='string'){
$voiceSearch.html(dgwt_wcas.voice_search_inactive_icon);
}
break;
case 'off':
that.voiceSearchStarted=false;
if(typeof dgwt_wcas.voice_search_disabled_icon=='string'){
$voiceSearch.html(dgwt_wcas.voice_search_disabled_icon);
}
break;
}},
};
$.fn.dgwtWcasAutocomplete=function (options, args){
var dataKey='autocomplete';
if(!arguments.length){
return this.first().data(dataKey);
}
return this.each(function (){
var inputElement=$(this),
instance=inputElement.data(dataKey);
if(typeof options==='string'){
if(instance&&typeof instance[options]==='function'){
instance[options](args);
}}else{
if(instance&&instance.dispose){
instance.dispose();
}
instance=new DgwtWcasAutocompleteSearch(this, options);
inputElement.data(dataKey, instance);
}});
};
if(!$.fn.autocomplete){
$.fn.autocomplete=$.fn.dgwtWcasAutocomplete;
}
(function (){
if(utils.isIE11()){
(function (self, undefined){
function Call(t, l){
var n=arguments.length > 2 ? arguments[2]:[];
if(!1===IsCallable(t)) throw new TypeError(Object.prototype.toString.call(t) + "is not a function.");
return t.apply(l, n)
}
function CreateMethodProperty(e, r, t){
var a={value: t, writable: !0, enumerable: !1, configurable: !0};
Object.defineProperty(e, r, a)
}
function Get(n, t){
return n[t]
}
function IsCallable(n){
return "function"==typeof n
}
function RequireObjectCoercible(e){
if(null===e||e===undefined) throw TypeError(Object.prototype.toString.call(e) + " is not coercible to Object.");
return e
}
function SameValueNonNumber(e, n){
return e===n
}
function ToBoolean(o){
return Boolean(o)
}
function ToObject(e){
if(null===e||e===undefined) throw TypeError();
return Object(e)
}
function GetV(t, e){
return ToObject(t)[e]
}
function GetMethod(e, n){
var r=GetV(e, n);
if(null===r||r===undefined) return undefined;
if(!1===IsCallable(r)) throw new TypeError("Method not callable: " + n);
return r
}
function Type(e){
switch (typeof e){
case"undefined":
return "undefined";
case"boolean":
return "boolean";
case"number":
return "number";
case"string":
return "string";
case"symbol":
return "symbol";
default:
return null===e ? "null":"Symbol" in self&&(e instanceof self.Symbol||e.constructor===self.Symbol) ? "symbol":"object"
}}
function IsRegExp(e){
if("object"!==Type(e)) return !1;
var n="Symbol" in self&&"match" in self.Symbol ? Get(e, self.Symbol.match):undefined;
if(n!==undefined) return ToBoolean(n);
try {
var t=e.lastIndex;
return e.lastIndex=0, RegExp.prototype.exec.call(e), !0
} catch (l){
} finally {
e.lastIndex=t
}
return !1
}
function OrdinaryToPrimitive(r, t){
if("string"===t) var e=["toString", "valueOf"]; else e=["valueOf", "toString"];
for (var i=0; i < e.length; ++i){
var n=e[i], a=Get(r, n);
if(IsCallable(a)){
var o=Call(a, r);
if("object"!==Type(o)) return o
}}
throw new TypeError("Cannot convert to primitive.")
}
function SameValueZero(n, e){
return Type(n)===Type(e)&&("number"===Type(n) ? !(!isNaN(n)||!isNaN(e))||(1 / n===Infinity&&1 / e==-Infinity||(1 / n==-Infinity&&1 / e===Infinity||n===e)):SameValueNonNumber(n, e))
}
function ToInteger(n){
if("symbol"===Type(n)) throw new TypeError("Cannot convert a Symbol value to a number");
var t=Number(n);
return isNaN(t) ? 0:1 / t===Infinity||1 / t==-Infinity||t===Infinity||t===-Infinity ? t:(t < 0 ? -1:1) * Math.floor(Math.abs(t))
}
function ToLength(n){
var t=ToInteger(n);
return t <=0 ? 0:Math.min(t, Math.pow(2, 53) - 1)
}
function ToPrimitive(e){
var t=arguments.length > 1 ? arguments[1]:undefined;
if("object"===Type(e)){
if(arguments.length < 2) var i="default"; else t===String ? i="string":t===Number&&(i="number");
var r="function"==typeof self.Symbol&&"symbol"==typeof self.Symbol.toPrimitive ? GetMethod(e, self.Symbol.toPrimitive):undefined;
if(r!==undefined){
var n=Call(r, e, [i]);
if("object"!==Type(n)) return n;
throw new TypeError("Cannot convert exotic object to primitive.")
}
return "default"===i&&(i="number"), OrdinaryToPrimitive(e, i)
}
return e
}
function ToString(t){
switch (Type(t)){
case"symbol":
throw new TypeError("Cannot convert a Symbol value to a string");
case"object":
return ToString(ToPrimitive(t, String));
default:
return String(t)
}}
CreateMethodProperty(Array.prototype, "includes", function e(r){
"use strict";
var t=ToObject(this), o=ToLength(Get(t, "length"));
if(0===o) return !1;
var n=ToInteger(arguments[1]);
if(n >=0) var a=n; else (a=o + n) < 0&&(a=0);
for (; a < o;){
var i=Get(t, ToString(a));
if(SameValueZero(r, i)) return !0;
a +=1
}
return !1
});
CreateMethodProperty(String.prototype, "includes", function e(t){
"use strict";
var r=arguments.length > 1 ? arguments[1]:undefined, n=RequireObjectCoercible(this),
i=ToString(n);
if(IsRegExp(t)) throw new TypeError("First argument to String.prototype.includes must not be a regular expression");
var o=ToString(t), g=ToInteger(r), a=i.length, p=Math.min(Math.max(g, 0), a);
return -1!==String.prototype.indexOf.call(i, o, p)
});
})('object'===typeof window&&window||'object'===typeof self&&self||'object'===typeof global&&global||{});
}
$(document).ready(function (){
"use strict";
if(utils.isIOS()){
$('html').addClass('dgwt-wcas-is-ios');
}
window.dgwt_wcas.resizeOnlyOnce=null;
window.dgwt_wcas.scrollOnlyOnce=null;
window.dgwt_wcas.config={
minChars: dgwt_wcas.min_chars,
width: dgwt_wcas.sug_width,
autoSelectFirst: false,
triggerSelectOnValidInput: false,
serviceUrl: dgwt_wcas.ajax_search_endpoint,
paramName: 's',
showDetailsPanel: dgwt_wcas.show_details_panel==1 ? true:false,
showImage: dgwt_wcas.show_images==1 ? true:false,
showPrice: dgwt_wcas.show_price==1 ? true:false,
showDescription: dgwt_wcas.show_desc==1 ? true:false,
showSKU: dgwt_wcas.show_sku==1 ? true:false,
showSaleBadge: dgwt_wcas.show_sale_badge==1 ? true:false,
showFeaturedBadge: dgwt_wcas.show_featured_badge==1 ? true:false,
dynamicPrices: typeof dgwt_wcas.dynamic_prices!='undefined'&&dgwt_wcas.dynamic_prices ? true:false,
saleBadgeText: dgwt_wcas.labels.sale_badge,
featuredBadgeText: dgwt_wcas.labels.featured_badge,
isRtl: dgwt_wcas.is_rtl==1 ? true:false,
showHeadings: dgwt_wcas.show_headings==1 ? true:false,
isPremium: dgwt_wcas.is_premium==1 ? true:false,
taxonomyBrands: dgwt_wcas.taxonomy_brands,
layoutBreakpoint: dgwt_wcas.layout_breakpoint,
mobileOverlayBreakpoint: dgwt_wcas.mobile_overlay_breakpoint,
mobileOverlayWrapper: dgwt_wcas.mobile_overlay_wrapper,
mobileOverlayDelay: dgwt_wcas.mobile_overlay_delay,
debounceWaitMs: dgwt_wcas.debounce_wait_ms,
sendGAEvents: dgwt_wcas.send_ga_events,
enableGASiteSearchModule: dgwt_wcas.enable_ga_site_search_module,
appendTo: typeof dgwt_wcas.suggestions_wrapper!='undefined' ? dgwt_wcas.suggestions_wrapper:'body',
showProductVendor: typeof dgwt_wcas.show_product_vendor!='undefined'&&dgwt_wcas.show_product_vendor ? true:false,
disableHits: typeof dgwt_wcas.disable_hits!='undefined'&&dgwt_wcas.disable_hits ? true:false,
disableSubmit: typeof dgwt_wcas.disable_submit!='undefined'&&dgwt_wcas.disable_submit ? true:false,
voiceSearchEnabled: typeof dgwt_wcas.voice_search_enabled!='undefined'&&dgwt_wcas.voice_search_enabled ? true:false,
voiceSearchLang: typeof dgwt_wcas.voice_search_lang!='undefined' ? dgwt_wcas.voice_search_lang:'',
showRecentlySearchedProducts: typeof dgwt_wcas.show_recently_searched_products!='undefined' ? dgwt_wcas.show_recently_searched_products:false,
showRecentlySearchedPhrases: typeof dgwt_wcas.show_recently_searched_phrases!='undefined' ? dgwt_wcas.show_recently_searched_phrases:false,
goToFirstVariationOnSubmit: typeof dgwt_wcas.go_to_first_variation_on_submit!='undefined' ? dgwt_wcas.go_to_first_variation_on_submit:false,
};
$('.dgwt-wcas-search-input').dgwtWcasAutocomplete(window.dgwt_wcas.config);
var $focusedElement=$(document.activeElement);
if($focusedElement.length){
if($focusedElement.hasClass('dgwt-wcas-search-input')){
$focusedElement.trigger('focus');
}else if($focusedElement.hasClass('js-dgwt-wcas-search-icon-handler')){
$focusedElement.trigger('click');
}}
});
var UI_FIXER={
brokenSearchUi: typeof dgwt_wcas.fixer.broken_search_ui!='undefined'&&dgwt_wcas.fixer.broken_search_ui ? true:false,
brokenSearchUiAjax: typeof dgwt_wcas.fixer.broken_search_ui_ajax!='undefined'&&dgwt_wcas.fixer.broken_search_ui_ajax ? true:false,
brokenSearchUiHard: typeof dgwt_wcas.fixer.broken_search_ui_hard!='undefined'&&dgwt_wcas.fixer.broken_search_ui_hard ? true:false,
brokenSearchElementorPopups: typeof dgwt_wcas.fixer.broken_search_elementor_popups!='undefined'&&dgwt_wcas.fixer.broken_search_elementor_popups ? true:false,
brokenSearchJetMobileMenu: typeof dgwt_wcas.fixer.broken_search_jet_mobile_menu!='undefined'&&dgwt_wcas.fixer.broken_search_jet_mobile_menu ? true:false,
brokenSearchBrowserBackArrow: typeof dgwt_wcas.fixer.broken_search_browsers_back_arrow!='undefined'&&dgwt_wcas.fixer.broken_search_browsers_back_arrow ? true:false,
forceRefreshCheckout: typeof dgwt_wcas.fixer.force_refresh_checkout!='undefined'&&dgwt_wcas.fixer.force_refresh_checkout ? true:false,
searchBars: [],
init: function (){
var that=this;
if(that.brokenSearchUi){
$(document).ready(function (){
that.fixBrokenSearchUi();
});
}
if(that.brokenSearchUiAjax){
that.fixBrokenSearchUiAjax();
}
if(that.brokenSearchUiHard){
that.fixBrokenSearchUiHard();
}
if(that.brokenSearchElementorPopups){
$(document).ready(function (){
that.fixBrokenSearchOnElementorPopupsV1();
that.fixBrokenSearchOnElementorPopupsV2();
});
}
if(that.brokenSearchJetMobileMenu){
$(window).on('load', function (){
that.fixSearchInJetMobileMenu();
});
}
if(that.brokenSearchBrowserBackArrow){
that.fixbrokenSearchBrowserBackArrow();
}
if(that.forceRefreshCheckout){
that.fixforceRefreshCheckout();
}},
fixBrokenSearchUi: function (){
var that=this;
$(document).ready(function (){
setTimeout(function (){
that.pullAndReconditionSearchBars();
}, 50);
});
$(window).on('load', function (){
setTimeout(function (){
that.pullAndReconditionSearchBars();
}, 500);
});
},
fixBrokenSearchUiAjax: function (){
var that=this;
$(document).ajaxSuccess(function (event, request, settings){
if(typeof settings.url=='string'&&new RegExp('search\.php|wc-ajax').test(settings.url)){
return;
}
if(typeof request.responseText=='string'&&request.responseText.includes('dgwt-wcas-search-input')){
setTimeout(function (){
that.pullAndReconditionSearchBars();
}, 500);
}});
},
fixBrokenSearchUiHard: function (){
var that=this;
$(document).ready(function (){
if(that.searchBars.length===0){
that.pullAndReconditionSearchBars();
}
setInterval(function (){
that.pullAndReconditionSearchBars();
}, 1000);
});
},
fixBrokenSearchOnElementorPopupsV1: function (){
var that=this;
$(document).on('elementor/popup/show', ()=> {
setTimeout(function (){
that.pullAndReconditionSearchBars();
}, 500);
});
},
fixBrokenSearchOnElementorPopupsV2: function (){
var that=this;
$(document).ready(function (){
if(typeof window.elementorFrontend!='undefined'
&& typeof window.elementorFrontend.documentsManager!='undefined'
&& typeof window.elementorFrontend.documentsManager.documents!='undefined'
){
$.each(elementorFrontend.documentsManager.documents, function (id, document){
if(typeof document.getModal!='undefined'&&document.getModal){
document.getModal().on('show', function (){
setTimeout(function (){
that.pullAndReconditionSearchBars();
}, 500);
});
}});
}});
},
fixSearchInJetMobileMenu: function (){
var that=this;
if($('.jet-mobile-menu__toggle').length===0){
return;
}
$(document).ajaxSend(function (event){
if(typeof event.currentTarget!='undefined'
&& typeof event.currentTarget.activeElement=='object'
&& $(event.currentTarget.activeElement).hasClass('jet-mobile-menu__toggle')
){
setTimeout(function (){
var $search=$(".jet-mobile-menu__container .dgwt-wcas-search-input");
if($search.length > 0){
that.pullAndReconditionSearchBars();
}}, 500);
}});
},
fixforceRefreshCheckout: function (){
$(document.body).on('added_to_cart', function (){
if($(document.body).hasClass('woocommerce-checkout') &&
$('.dgwt-wcas-search-input').length > 0
){
$(document.body).trigger('update_checkout');
}});
},
fixbrokenSearchBrowserBackArrow: function (){
$(window).on('load', function (){
var i=0;
var interval=setInterval(function (){
var activeEl=document.activeElement;
if(typeof activeEl=='object'
&& $(activeEl).length
&& $(activeEl).hasClass('dgwt-wcas-search-input')
){
var $search=$(activeEl).closest('.dgwt-wcas-search-wrapp');
if($search.length&&!$search.hasClass('dgwt-wcas-active')){
$search.addClass('dgwt-wcas-active');
clearInterval(interval);
}}
if(i > 10){
clearInterval(interval);
}
i++;
}, 500);
});
},
pullAndReconditionSearchBars: function (){
var that=this,
$inputs=$('.dgwt-wcas-search-input'),
firstPull=that.searchBars.length==0;
if($inputs.length > 0){
$inputs.each(function (){
var $searchBar=$(this),
isNew=true,
i;
if(that.searchBars.length > 0){
for (i=0; i < that.searchBars.length; i++){
if($searchBar[0]===that.searchBars[i][0]){
isNew=false;
break;
}}
}
if(isNew){
var changedId=false;
if(!that.hasUniqueId($searchBar)){
that.makeUniqueID($searchBar);
changedId=true;
}
if(!firstPull||!that.isInitialized($searchBar)||changedId){
that.reinitSearchBar($searchBar)
}
that.searchBars.push($searchBar);
}
if(!that.hasEvents($searchBar)){
that.reinitSearchBar($searchBar)
}});
}},
hasEvents: function ($searchBarInput){
var hasEvents=false;
$searchBarInput.trigger('fibosearch/ping');
if($searchBarInput.hasClass('fibosearch-pong')){
hasEvents=true;
}
$('.fibosearch-pong').removeClass('fibosearch-pong');
return hasEvents;
},
isInitialized: function ($searchBarInput){
return typeof $searchBarInput.data('autocomplete')=='object';
},
hasUniqueId: function ($searchBarInput){
var that=this,
unique=true;
if(that.searchBars.length > 0){
for (var i=0; i < that.searchBars.length; i++){
if($searchBarInput.attr('id')===that.searchBars[i].attr('id')){
unique=false;
}}
}
return unique;
},
reinitSearchBar: function ($searchBarInput){
if(typeof $searchBarInput.data('autocomplete')=='object'){
$searchBarInput.data('autocomplete').dispose();
}
$searchBarInput.dgwtWcasAutocomplete(window.dgwt_wcas.config);
},
makeUniqueID: function ($searchBarInput){
var newID=Math.random().toString(36).substring(2, 6);
newID='dgwt-wcas-search-input-' + newID;
$searchBarInput.attr('id', newID);
$searchBarInput.closest('form').find('label').attr('for', newID);
},
}
if(typeof dgwt_wcas.fixer.core=='undefined'){
dgwt_wcas.fixer.core=UI_FIXER;
dgwt_wcas.fixer.core.init();
}}());
}));
jQuery(function($){
if(typeof wc_cart_fragments_params==='undefined'){
return false;
}
var $supports_html5_storage=true,
cart_hash_key=wc_cart_fragments_params.cart_hash_key;
try {
$supports_html5_storage=('sessionStorage' in window&&window.sessionStorage!==null);
window.sessionStorage.setItem('wc', 'test');
window.sessionStorage.removeItem('wc');
window.localStorage.setItem('wc', 'test');
window.localStorage.removeItem('wc');
} catch(err){
$supports_html5_storage=false;
}
function set_cart_creation_timestamp(){
if($supports_html5_storage){
sessionStorage.setItem('wc_cart_created',(new Date()).getTime());
}}
function set_cart_hash(cart_hash){
if($supports_html5_storage){
localStorage.setItem(cart_hash_key, cart_hash);
sessionStorage.setItem(cart_hash_key, cart_hash);
}}
var $fragment_refresh={
url: wc_cart_fragments_params.wc_ajax_url.toString().replace('%%endpoint%%', 'get_refreshed_fragments'),
type: 'POST',
data: {
time: new Date().getTime()
},
timeout: wc_cart_fragments_params.request_timeout,
success: function(data){
if(data&&data.fragments){
$.each(data.fragments, function(key, value){
$(key).replaceWith(value);
});
if($supports_html5_storage){
sessionStorage.setItem(wc_cart_fragments_params.fragment_name, JSON.stringify(data.fragments) );
set_cart_hash(data.cart_hash);
if(data.cart_hash){
set_cart_creation_timestamp();
}}
$(document.body).trigger('wc_fragments_refreshed');
}},
error: function(){
$(document.body).trigger('wc_fragments_ajax_error');
}};
function refresh_cart_fragment(){
$.ajax($fragment_refresh);
}
if($supports_html5_storage){
var cart_timeout=null,
day_in_ms=(24 * 60 * 60 * 1000);
$(document.body).on('wc_fragment_refresh updated_wc_div', function(){
refresh_cart_fragment();
});
$(document.body).on('added_to_cart removed_from_cart', function(event, fragments, cart_hash){
var prev_cart_hash=sessionStorage.getItem(cart_hash_key);
if(prev_cart_hash===null||prev_cart_hash===undefined||prev_cart_hash===''){
set_cart_creation_timestamp();
}
sessionStorage.setItem(wc_cart_fragments_params.fragment_name, JSON.stringify(fragments) );
set_cart_hash(cart_hash);
});
$(document.body).on('wc_fragments_refreshed', function(){
clearTimeout(cart_timeout);
cart_timeout=setTimeout(refresh_cart_fragment, day_in_ms);
});
$(window).on('storage onstorage', function(e){
if(cart_hash_key===e.originalEvent.key&&localStorage.getItem(cart_hash_key)!==sessionStorage.getItem(cart_hash_key)
){
refresh_cart_fragment();
}});
$(window).on('pageshow' , function(e){
if(e.originalEvent.persisted){
$('.widget_shopping_cart_content').empty();
$(document.body).trigger('wc_fragment_refresh');
}});
try {
var wc_fragments=JSON.parse(sessionStorage.getItem(wc_cart_fragments_params.fragment_name) ),
cart_hash=sessionStorage.getItem(cart_hash_key),
cookie_hash=Cookies.get('woocommerce_cart_hash'),
cart_created=sessionStorage.getItem('wc_cart_created');
if(cart_hash===null||cart_hash===undefined||cart_hash===''){
cart_hash='';
}
if(cookie_hash===null||cookie_hash===undefined||cookie_hash===''){
cookie_hash='';
}
if(cart_hash&&(cart_created===null||cart_created===undefined||cart_created==='') ){
throw 'No cart_created';
}
if(cart_created){
var cart_expiration=(( 1 * cart_created) + day_in_ms),
timestamp_now=(new Date()).getTime();
if(cart_expiration < timestamp_now){
throw 'Fragment expired';
}
cart_timeout=setTimeout(refresh_cart_fragment,(cart_expiration - timestamp_now) );
}
if(wc_fragments&&wc_fragments['div.widget_shopping_cart_content']&&cart_hash===cookie_hash){
$.each(wc_fragments, function(key, value){
$(key).replaceWith(value);
});
$(document.body).trigger('wc_fragments_loaded');
}else{
throw 'No fragment';
}} catch(err){
refresh_cart_fragment();
}}else{
refresh_cart_fragment();
}
if(Cookies.get('woocommerce_items_in_cart') > 0){
$('.hide_cart_widget_if_empty').closest('.widget_shopping_cart').show();
}else{
$('.hide_cart_widget_if_empty').closest('.widget_shopping_cart').hide();
}
$(document.body).on('adding_to_cart', function(){
$('.hide_cart_widget_if_empty').closest('.widget_shopping_cart').show();
});
var hasSelectiveRefresh=(
'undefined'!==typeof wp &&
wp.customize &&
wp.customize.selectiveRefresh &&
wp.customize.widgetsPreview &&
wp.customize.widgetsPreview.WidgetPartial
);
if(hasSelectiveRefresh){
wp.customize.selectiveRefresh.bind('partial-content-rendered', function(){
refresh_cart_fragment();
});
}});