class Wishlist { constructor() { this.iWishUrl = "https://internalapis.myshopapps.com/iwish/V2"; //'https://api.myshopapps.com/iwish/V2'; this.logs = typeof window.iWishData.logs !== 'undefined' && window.iWishData.logs === "true" ? true : false; this.varSelector = window.iWishData.variant_selector!='' ? window.iWishData.variant_selector : '[name=id]'; this.optSelector = window.iWishData.option_selector!='' ? window.iWishData.option_selector : ''; this.qtySelector = window.iWishData.quantity_selector!='' ? window.iWishData.quantity_selector : '[name=quantity]'; this.custId = window.iWishData.cust !== "" ? parseInt(window.iWishData.cust) : 0; this.locale = window.iWishData.locale !='' ? window.iWishData.locale:''; if(this.custId == 0 && localStorage.iwish_sync == "true") { // if logout localStorage.removeItem('iwish_list'); localStorage.removeItem('iwish_sync'); localStorage.removeItem('iwish_category'); localStorage.removeItem('categories'); } let iwish_local = localStorage.getItem("iwish_list"); this.iWishlist = iwish_local !== null ? new Map(JSON.parse(localStorage.iwish_list)) : new Map(); this.iWishsync = localStorage?.iwish_sync && localStorage.iwish_sync=== "true" ? true : false; this.customDelay = typeof window.iWishData.custom_delay !== 'undefined' && window.iWishData.custom_delay!='' ? window.iWishData.custom_delay : 100; this.catData = {0: window.iWishData.main_cat}; if(!localStorage.iwish_category) { localStorage.iwish_category = JSON.stringify(this.catData); } let localCategory = this.getCurrentCategory(); if(Object.keys(localCategory)[0] ==0 && Object.values(localCategory)[0] !== window.iWishData.main_cat){ localStorage.iwish_category = JSON.stringify(this.catData); } } findAncestor(el, cls) { while (el.parentElement) { el = el.parentElement; if(el.querySelectorAll(cls).length > 0) { return el.querySelector(cls); } } return false; } getWishlist() { return JSON.stringify(Array.from(iWish.iWishlist)); } setWishlist() { localStorage.iwish_list = JSON.stringify(Array.from(iWish.iWishlist)); } setCategories(){ localStorage.categories = JSON.stringify(iWish.categories); //localStorage.categories = JSON.stringify(Array.from(iWish.categories)); } getCategories(){ return JSON.parse(localStorage.categories); } getCounter() { return iWish.iWishlist.size; } setCounter() { const selectorElm = document.querySelectorAll(".iwish-counter"); if(selectorElm.length) { selectorElm.forEach( el => { el.innerHTML = this.getCounter(); }); } } isInWishlist(vId) { return iWish.iWishlist.has(vId) ? true : false; } setIwishAdded(iwishAdd) { iwishAdd.classList.add("iwishAdded"); iwishAdd.innerHTML = iwishAdd.classList.contains('iWishAddColl') ? window.iWishData.iwish_added_txt_col : window.iWishData.iwish_added_txt; } setIwishRemoved(iwishAdd) { iwishAdd.classList.remove("iwishAdded"); iwishAdd.innerHTML = iwishAdd.classList.contains('iWishAddColl') ? window.iWishData.iwish_add_txt_col : window.iWishData.iwish_add_txt; } checkIwish(varSelector,customSel="") { let vId = varSelector.value; let iwishAdd = this.findAncestor(varSelector, ".iWishAdd"); if(this.logs) { console.log('checkIwish Product::', vId); } if(iwishAdd) { iwishAdd.setAttribute("data-variant", vId); if(this.isInWishlist(vId)) { // add to wishlist this.setIwishAdded(iwishAdd); } else { // remove if added this.setIwishRemoved(iwishAdd); } } else { // set data-variant attribute from custom theme code; let custVid = customSel.getAttributeNode("data-variant").value; if(this.logs) { console.log("customSel add to wish::",custVid,customSel); } if(this.isInWishlist(custVid)) { // add to wishlist this.setIwishAdded(customSel); } else { // remove if added this.setIwishRemoved(customSel); } } } // wishlist product listing - check if products added checkIwishColl() { //setTimeout(()=> { let iwishAdd = document.querySelectorAll(".iwishcheck"); if(iwishAdd.length) { if(this.logs) { console.log("iwishcheck::",iwishAdd.length) } for (var i = 0; i < iwishAdd.length; i++) { if(iwishAdd[i].innerHTML=='') { iwishAdd[i].innerHTML = window.iWishData.iwish_add_txt_col; } // add click event this.iwishAddClick(iwishAdd[i]); let vId = iwishAdd[i].getAttributeNode("data-variant").value; if(this.isInWishlist(vId)){ this.setIwishAdded(iwishAdd[i]); } else { // remove if added this.setIwishRemoved(iwishAdd[i]); } iwishAdd[i].classList.remove("iwishcheck"); } } //},this.customDelay) } customFiltersClick(el) { let checkiwishElm = document.querySelectorAll(el); //if(this.logs) { console.log("checkiwishElm ::",checkiwishElm.length); } if(checkiwishElm.length > 0) { checkiwishElm.forEach(e => e.addEventListener('click', event => { let e = event.target; if(e.tagName == 'INPUT' || e.tagName == 'SELECT' || e.tagName == 'OPTION') { e.removeEventListener("change", ev => { }); e.addEventListener('change', ev => { setTimeout(() => { let iwishcheck = document.querySelectorAll(".iwishcheck"); if(this.logs) { console.log('checkIwishColl custom filter change: iwishcheck.length ::' + iwishcheck.length); } // attach iwish.qv_button click if(typeof window.iWishData.qv_button !== 'undefined' && window.iWishData.qv_button != '') { if(iwishcheck.length && typeof iWishQV !== 'undefined') { if(this.logs) { console.log('iWishQV.init...'); } iWishQV.init(); } } this.checkIwishColl(); }, this.customDelay); }); } else { setTimeout(() => { let iwishcheck = document.querySelectorAll(".iwishcheck"); if(this.logs) { console.log('checkIwishColl custom filter click: iwishcheck.length ::' + iwishcheck.length); } // attach iwish.qv_button click if(typeof window.iWishData.qv_button!=='undefined' && window.iWishData.qv_button!='') { if(iwishcheck.length && typeof iWishQV !== 'undefined') { if(this.logs) { console.log('iWishQV.init...'); } iWishQV.init(); } } this.checkIwishColl(); }, this.customDelay); } }, false)); } //filter click callback if (typeof customFiltersClickFn !== 'undefined' && typeof customFiltersClickFn === 'function') { customFiltersClickFn(); } } iwishAddClick(el) { window.changeDetect.status = ''; if(!el.hasAttribute("data-iwClick")) { el.setAttribute('data-iwClick', 'true'); el.addEventListener('click', event => { event.preventDefault(); window.iwishAddProxy.click = "true"; let qtySelect = this.findAncestor(el, this.qtySelector); let qty = qtySelect ? parseInt(qtySelect.value) : 1; let pId = el.getAttributeNode("data-product").value; let vId = el.getAttributeNode("data-variant").value; if(pId=='' || vId=='') { return; } if(this.isInWishlist(vId)) { // remove if added this.iwishRemove(vId, pId); this.setIwishRemoved(el); if(this.logs) { console.log("iwishRemove::",pId,vId); } window.changeDetect.status = 'removed'; } else { // add to wishlist this.iwishAdd(vId,pId,qty); this.setIwishAdded(el); if(this.logs) { console.log("iwishAdd::",pId,vId); } window.changeDetect.status = 'added'; } }); } } iwishOnBodyClick() { var _this = this; document.body.addEventListener('click', function(event) { if (event.target.tagName === 'SPAN' || event.target.tagName === 'svg' || event.target.tagName === 'A') { let el = event.target.closest('.iWishAdd'); if(el) { event.preventDefault(); let qtySelect = _this.findAncestor(el, _this.qtySelector); let qty = qtySelect ? parseInt(qtySelect.value) : 1; let pId = el.getAttributeNode("data-product").value; let vId = el.getAttributeNode("data-variant").value; if(pId=='' || vId=='') { return; } if(this.logs) { console.log("iWish bodyOnclick::",pId,vId); } if(_this.isInWishlist(vId)) { // remove if added _this.iwishRemove(vId, pId); _this.setIwishRemoved(el); window.changeDetect.status = 'removed'; }else { // add to wishlist _this.iwishAdd(vId,pId,qty); _this.setIwishAdded(el); window.changeDetect.status = 'added'; } } } }); } iwishAdd(vId, pId, qty, catId) { let defaltCat = {"0":"Main Wishlist"}; const localCat = this.getCurrentCategory() || defaltCat; catId = localCat && Object.keys(localCat).length !==0 ? Object.keys(localCat)[0] : 0; iWish.iWishlist.set(vId, qty); this.setWishlist(); // update storage this.setCounter(); if(this.custId>0) { let data = "customer_id="+this.custId+"&product_id="+pId+"&variant_id="+vId+"&product_qty="+qty+"&category_id="+catId; this.requestToSever("addToWishlist", data); } //add callback if (typeof iWishAddFn !== 'undefined' && typeof iWishAddFn === 'function'){ iWishAddFn(vId); } } iwishRemove(vId, pId, catId=null) { iWish.iWishlist.delete(vId); this.setWishlist(); // update storage this.setCounter(); //remove callback if (typeof iWishRemoveFn !== 'undefined' && typeof iWishRemoveFn === 'function'){ iWishRemoveFn(vId); } if(this.custId>0) { let data = "customer_id="+this.custId+"&product_id="+pId+"&variant_id="+vId; if(catId!==null) { data += "&category_id="+catId; } return this.requestToSever("removeWishlist", data); } else { return({"result":"OK","errors":""}) } } async updateWishlist(pId, vId, qty=null, catId=null) { if(this.custId>0) { let data = ''; if(qty!=null) { this.iWishlist.set(vId, qty); this.setWishlist(); // update storage data = "customer_id="+this.custId+"&product_id="+pId+"&variant_id="+vId+"&product_qty="+qty; } else if(catId!=null) { data += "customer_id="+this.custId+"&product_id="+pId+"&variant_id="+vId+"&category_id="+catId; } return data!='' ? await this.requestToSever("updateWishlist", data, 'PUT') : false; } else { if(qty!=null) { this.iWishlist.set(vId, qty); this.setWishlist(); } } } async requestToSever(page, body, method='POST', cFunction=null) { const url = this.iWishUrl+"/"+page; const options = { method: method, headers: {'Content-Type': 'application/x-www-form-urlencoded', domain: window.iWishData.shop, Authorization:''}, body: new URLSearchParams(body) }; try { const response = await fetch(url, options); const data = await response.json(); if(cFunction!=null) { cFunction(data); } return data; } catch (error) { //if(this.logs) { console.log(error); } return error; } } // category calls getCurrentCategory(){ return JSON.parse(localStorage.iwish_category); } setCurrentCategory(catId,catName) { let catData = {}; catData[catId] = catName; localStorage.iwish_category = JSON.stringify(catData); } async fetchCategory() { let data = ""; const response = await this.requestToSever("fetchCategory/"+this.custId, data, 'POST'); let catData = response.result; //const mapData = new Map(); const arr = []; catData?.reduce((acc, curr,index) => { if (acc.indexOf(Object.values(curr)[0]) === -1) { acc.push(Object.values(curr)[0]); arr.push(curr); //mapData.set(Object.keys(curr)[0],Object.values(curr)[0]); } return acc; }, []); iWish.categories = arr; iWish.setCategories(); //localStorage.setItem('categories', JSON.stringify(arr)); } // sync iwish when login syncWishlist() { let data = "customer_id="+this.custId+"&wishlist="+this.getWishlist(); //if(this.logs) { console.log('syncWishlist', data); } this.requestToSever("syncWishlist", data, 'POST', this.syncWishlistFn); } //callbackFn syncWishlistFn(response) { //if(iWish.logs) { console.log('syncWishlistFn...', response.result, response.errors); } if(response.result!='') { iWish.iWishlist = new Map(Object.entries(response.result)); iWish.setWishlist(); // update storage iWish.setCounter(); } iWish.iWishsync = true; if(iWish.logs) { console.log('syncWishlist :: '+iWish.iWishsync); } localStorage.setItem('iwish_sync', iWish.iWishsync); } iWishPost(e,t) { let method="post"; let n=document.createElement("form"); n.setAttribute("method",method); n.setAttribute("action",e); for(let r in t){ if(t.hasOwnProperty(r)){ let i=document.createElement("input"); i.setAttribute("type","hidden"); i.setAttribute("name",r); i.setAttribute("value",t[r]); n.appendChild(i)} } document.head.appendChild(n); n.submit(); } init() { if(this.logs) { console.log('iWish.init..'); } const iwishAddProxy = (obj) => { return new Proxy(obj, { set(target, key, value) { if(value!=="true") { this.iwishOnBodyClick(); } return true; } }); }; window.iwishAddProxy = iwishAddProxy({click:"false"}); this.setCounter(); if(this.custId > 0 && !this.iWishsync) { //if(this.logs) { console.log("syncWishlist .."); } this.syncWishlist(); this.fetchCategory(); } if(document.querySelectorAll(".iWishAdd").length && typeof window.iWishData.iwish_add_txt !== 'undefined') { // iWishAdd click let iWishAddElm = document.querySelectorAll('.iWishAdd'); iWishAddElm.forEach( elm => { if(elm.innerHTML=='') { elm.innerHTML = window.iWishData.iwish_add_txt; } // add click event this.iwishAddClick(elm); //if(this.logs) { console.log("iwishProxy.iwishAddClick : ", window.iwishAddProxy.click); } }); // checkiwish on load - product page let selectorElm = document.querySelectorAll(this.varSelector); if(this.logs) { console.log("iWishAdd selector length :: ", selectorElm.length); } selectorElm.forEach( el => { this.checkIwish(el); }); // checkiwish on variant change //setTimeout(() => { if(this.optSelector == '') { selectorElm.forEach(el => el.addEventListener('change', event => { //if(this.logs) { console.log('variant change..'); } this.checkIwish(el); })); } else { let selectorElm2 = document.querySelectorAll(this.optSelector); selectorElm2.forEach(el => el.addEventListener('change', event => { //if(this.logs) { console.log('option change..'); } setTimeout(() => { let el2 = this.findAncestor(el, this.varSelector); this.checkIwish(el2) }, 300); })); selectorElm2.forEach(el => el.addEventListener('click', event => { let target = el.target ? el.target : el; if(target.tagName!="INPUT" && target.tagName!="SELECT" && target.tagName!="OPTION") { //if(this.logs) { console.log('option click..',target); } setTimeout(() => { let el2 = this.findAncestor(el, this.varSelector); this.checkIwish(el2) }, 300); } })); } //}, this.customDelay); } if(typeof window.iWishData.iwish_add_txt_col !== 'undefined') { // checkiwish on product grid this.checkIwishColl(); // dynamically added elements : on page load setTimeout(() => { this.checkIwishColl(); }, this.customDelay); // dynamically added elements : on Custom filters if(typeof window.iWishData.custom_filters !== 'undefined' && window.iWishData.custom_filters!='') { let custCheck = window.iWishData.custom_filters; let custCheckLst = custCheck.split(", "); custCheckLst.forEach( el => { this.customFiltersClick(el); }); } } //init callback if (typeof iWishinitFn !== 'undefined' && typeof iWishinitFn === 'function') { iWishinitFn(); } } } var iWish = new Wishlist(); (function() { try { document.addEventListener("DOMContentLoaded", (event) => { let iwishInitDelay = typeof window.iWishData.init_delay !== 'undefined' && window.iWishData.init_delay!='' ? window.iWishData.init_delay : 0; setTimeout(() => { iWish.init(); }, iwishInitDelay); }); } catch(err) { //if(this.logs) { console.log("iWish init Error :: ",err); } } /*function asyncLoad() { try { let iwishInitDelay = typeof window.iWishData.init_delay !== 'undefined' && window.iWishData.init_delay!='' ? window.iWishData.init_delay : 100; setTimeout(() => { iWish.init(); }, iwishInitDelay); } catch(err) { console.log("iWish init Error :: ",err) } }; if(window.attachEvent) { window.attachEvent('onload', asyncLoad); } else { window.addEventListener('load', asyncLoad, false); }*/ })();