//506//
const $body = document.querySelector('body');
var version = "506";
var new_version = '';
var currentScript = document.currentScript.src;
var priceData = "";
var attrStatus = "close";
let menuStr = "";
let timer;
const $clientId = "4e8e2ddb77c66b23313652ee6d396fca";
let flag = true;
/*fetch(document.currentScript.src +'?rand="w363632', {
});*/
/* fetch(document.currentScript.src +'?rand="w363632').then(rtesponse => {
// handle the response
console.log(response);
console.log(response.text());
});*/
/*fetch('https://d3fgegizptfhv.cloudfront.net/4e8e2ddb77c66b23313652ee6d396fca/mega_menu.json').then(response => {
// handle the response
console.log(response.text());
});*/
async function getMegaMenu() {
const res = await fetch('https://dna3n15iwxmh8.cloudfront.net/4e8e2ddb77c66b23313652ee6d396fca/media/images/themes/1e1033bb1c64b831a0a7b344c7a12bc0/libs/mega-menu.json')
return res;
}
async function getSampleText() {
const res = await fetch(document.currentScript.src +'&v='+ Math.random() )
return res;
//console.log( (await fetch('sample2.txt')).text() );
}
getSampleText().then( res => {
res.text().then(txt => {
/* console.log( txt );
console.log( txt.split('\n') );
console.log( txt.split('\n')[0] );
console.log( txt.split('\n')[0].replaceAll('/','') );*/
new_version = txt.split('\n')[0].replaceAll('/','');
// console.log("get v", new_version);
});
});
/* Menu outside click */
document.addEventListener("oms_getSettingsSuccess", function (e) {
document.querySelector('#cont_block')?.remove();
document.addEventListener("click", function (e) {
document.querySelector('.mega-menu').classList.remove("show");
document.querySelector('.search-suggestions-wrp').innerHTML = '';
});
document.querySelector('.menuBtn')?.addEventListener("click", function (e) {
e.stopPropagation();
e.preventDefault()
const menu = document.querySelector('.mega-menu');
document.querySelector('.mega-menu').classList.toggle("show");
});
document.querySelector('.mega-menu')?.addEventListener("click", function (e) {
e.stopPropagation();
});
document.querySelector('.mega-menu .close-btn')?.addEventListener("click", function (e) {
document.querySelector('.mega-menu').classList.remove("show");
});
document.querySelector('.drawer-search')?.addEventListener("click", function (e) {
e.stopPropagation();
});
//Set category id
if(document.querySelector("#category-page") && document.querySelector(".category-wrapper")){
const id = document.querySelector(".category-wrapper").dataset.id;
document.querySelector("#category-page").dataset.id = id;
}
if (flag) {
//Custom Mega Menu
getMegaMenu().then( res => {
res.text().then(txt => {
//console.log(JSON.parse(txt));
const data = JSON.parse(txt);
data.data.map(item => {
menuStr += `
`; //Main li end
/*const temp = document.createElement('div');
temp.innerHTML = str;
const tpl = temp.firstChild;
catHolder?.querySelector('.items').appendChild(tpl);*/
});
const parser = new DOMParser();
const html = parser.parseFromString(menuStr, 'text/html');
const body = html.body;
document.querySelector('.static-menu-holder')?.append(body);
//Mobile menu
if(window.innerWidth < 767){
let mainNavs = document.querySelectorAll('.mega-menu .category.level-1 > div');
for(h = 0; h < mainNavs.length; h+=1) {
mainNavs[h].addEventListener("click", function(e){
this.classList.toggle("open")
})
}
}
});
});
flag = false;
}
//Search suggesdtions
let resultHolder = document.querySelector('.search-suggestions-wrp');
let resultStr = "";
document.querySelector("#search")?.addEventListener("input", (event) => {
let val = event.target.value;
clearTimeout(timer);
if(val){
timer = setTimeout(() => {
document.querySelector('.search-suggestions-wrp').innerHTML = `
Finding Matches...`;
document.addEventListener(
"oms_getProductListSuccesssearch",
function (e) {
let result = e.detail.result;
if (event.target.value && result.success && result.data.length) {
resultStr = "";
result.data.map((item, i) => {
resultStr += ``;
});
}else{
resultStr = "";
}
document.querySelector('.search-suggestions-wrp').innerHTML = resultStr;
},
false,
this
);
let getProductListEvent = new CustomEvent("oms_getProductList", {
detail: {
limit: 5,
start: 0,
sort_property: '',
sort_direction: '',
client_id: '4e8e2ddb77c66b23313652ee6d396fca',
filters: null,
keyword: val,
action: 'search',
request_id: 'search',
},
});
document.dispatchEvent(getProductListEvent);
}, 250);
}else{
document.querySelector('.search-suggestions-wrp').innerHTML = '';
}
});
})
document.addEventListener(
"oms_getProductSuccess", // + reqId,
function (e) {
const result = e.detail.result;
if(document.querySelector("#product-page") && e.detail.result?.data?.id){
document.querySelector("#product-page").dataset.id = e.detail.result.data.id;
}
// console.log("oms_getProductSuccess");
/*
const authData = localStorage.getItem("public_auth_" + $clientId);
const authJSON = JSON.parse(authData);*/
/*if (flag) {
const holder = document.querySelector(".product-view-wrapper");
fetch('/api/v1/get-assign-category?client_id=4e8e2ddb77c66b23313652ee6d396fca&product_id=' + result.data.id, {
headers: { Authorization: `Bearer ${authJSON.data.access_token}` }
})
.then(resp => resp.json())
.then(data => {
const catHolder = document.querySelector('.description-wrapper .categroy-info');
let html = "";
if (data.data.length > 0) {
const title = document.createElement('div');
title.innerHTML = 'Related Categories
';
catHolder?.querySelector('.heading').appendChild(title);
data.data.map(item => {
const str = `${item.name}`;
const temp = document.createElement('div');
temp.innerHTML = str;
const tpl = temp.firstChild;
catHolder?.querySelector('.items').appendChild(tpl);
});
}
})
flag = false;
}*/
document.addEventListener("oms_getQuantityBasePriceModuleSuccesscustom", (function(e) {
// console.log(e.detail.result);
if (e.detail.result.success && e.detail.result.data) {
let a = e.detail.result.data;
priceData = a.priceModule;
}
}))
let getQuantityBasePriceModule = new CustomEvent(
"oms_getQuantityBasePriceModule",
{
detail: {
request_id: 'custom',
client_id: $clientId,
product_id: result.data.id,
super_attributes: null,
},
}
);
document.dispatchEvent(getQuantityBasePriceModule);
setTimeout(() => {
//Toggle extra attributes
let moreAttrBtns = document.querySelectorAll('.product-variant-wrapper .super-attribute-colors .more-attr');
if(moreAttrBtns){
for(j = 0; j < moreAttrBtns.length; j+=1) {
moreAttrBtns[j].addEventListener("click", function (e) {
//console.log( this.closest('.super-attribute-colors'));
//console.log( moreAttrBtns[j].closest('.super-attribute-colors'));
attrStatus = "open";
this.closest('.super-attribute-colors').classList.add("open");
});
}
}
/*document.querySelector('.product-view-wrapper .super-attributes .more-attr')?.addEventListener("click", function (e) {
attrStatus = "open";
document.querySelector('.product-view-wrapper .super-attributes').classList.add("open");
}); */
if(attrStatus === "open"){
document.querySelector('.product-view-wrapper .super-attributes').classList.add("open");
}
// get all the buttons with this tag name (or use class name)
var allButtons = document.querySelectorAll('.detail-count-btn-wrapper .ct-btn');
// add a click listener to each button
for(h = 0; h < allButtons.length; h+=1) {
allButtons[h].addEventListener("click", function(e){
let currVal = document.querySelector(".ct-input").value;
let label = "";
var pts = document.querySelectorAll('.pt-item');
priceData.map( item => {
if( Number(currVal) >= item.volume){
label = `${item.final_price} x ${currVal} = LKR ${Number(currVal)*item.amount}/=`;
}
document.querySelector('.price-dp').innerHTML = label;
})
})
}
if(document.querySelector(".ct-input")){
document.querySelector(".ct-input").addEventListener("change", (event) => {
//console.log(priceData);
let label = "";
var pts = document.querySelectorAll('.pt-item');
priceData.map( item => {
if( Number(event.target.value) >= item.volume){
//console.log(item.amount);
label = `${item.final_price} x ${event.target.value} = LKR ${Number(event.target.value)*item.amount}/=`;
//console.log(label);
/*if(pts){
let i;
for (i = 0; i < pts.length; ++i) {
pts[i].style.color = "green";
pts[i].classList.remove('border-primary', 'border', 'rounded-md');
console.log(pts[i].dataset.volume, item.volume);
if(pts[i].dataset.volume == item.volume){
pts[i].classList.add('border-primary', 'border', 'rounded-md');
}
}
}*/
}
document.querySelector('.price-dp').innerHTML = label;
})
});
}
//Social share
const options = {
//link: 'https://www.thogaexpress.lk/',
locale: {
copied: 'Link copied to clipboard.'
},
/* onInit: function(this) {
console.log(this);
},
onIntent: function(this) {
console.log(this)
}*/
};
const element = document.querySelector('.social-share');
if (element) {
//TODO arguments
new ensemble.SocialShare(element, options);
}
document.querySelector('.zoomer')?.addEventListener("click", function (e) {
$body.classList.toggle("enable-zoomer");
});
//Color sort
let superColorAttrs = document.querySelectorAll('.product-variant-wrapper .super-attribute-colors');
if(superColorAttrs){
document.querySelector('.product-variant-wrapper').classList.add('loading', 'has-colors');
for(j = 0; j < superColorAttrs.length; j+=1) {
const colorArr = [];
let colorAttrs = superColorAttrs[j].querySelectorAll('.color-attr');
for(i = 0; i < colorAttrs.length; i+=1) {
colorArr.push(colorAttrs[i].dataset.code);
}
outputColors(colorArr);
}
}
/*let colorAttrs = document.querySelectorAll('.product-variant-wrapper .color-attr');
if(colorAttrs){
const colorArr = [];
document.querySelector('.product-variant-wrapper').classList.add('loading', 'has-colors');
for(i = 0; i < colorAttrs.length; i+=1) {
colorArr.push(colorAttrs[i].dataset.code);
}
outputColors(colorArr);
}*/
}, 1000);
},
false
);
//DOM Load
document.addEventListener("DOMContentLoaded", (event) => {
//Detect sitemap page
if (document.querySelector('.sitemap-wrapper')) {
document.querySelector('body').classList.add("nogap-mode");
}
setTimeout(() => {
/*console.log("version", version);
console.log("new_version", new_version);*/
if( new_version && new_version != version ){
if ( confirm("There is a new version, Reload now.") == true) {
// const script = document.createElement('script');
//script.src = currentScript +'&v='+ Math.random()
/* script.onload(() => {
location.reload(true);
})*/
//ocument.currentScript.src = document.currentScript.src + '&v=636737374';
script.addEventListener('load', () => {
location.reload(true);
})
/* document.body.appendChild(script);*/
}
}
}, 3000);
//document.querySelector('.copyright .v').innerHTML = ' v-' + version;
/* SNOW EFFECT */
/* var snowflakesContainer = document.createElement('div');
snowflakesContainer.className = 'snowflakes';
snowflakesContainer.innerHTML = `
❄
`;
document.body.appendChild(snowflakesContainer);*/
});
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect();
const { innerHeight, innerWidth } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) ||
(bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};
document.addEventListener("scroll", (event) => {
let cartBtn = document.querySelector('.product-view-wrapper .add-to-cart-wrapper');
let cartBtnSnap = document.querySelector('.product-view-wrapper .add-to-cart-wrapper-snap');
if(cartBtn && cartBtnSnap){
let inviewport = elementIsVisibleInViewport(cartBtnSnap, false);
if(!inviewport){
$body.classList.add('fixed-add-to-cart')
}else{
$body.classList.remove('fixed-add-to-cart')
}
}
});
/* document.addEventListener(
"oms_getCategroyByProductSuccess", // + reqId,
function (e) {
let result = e.detail.result;
console.log(result);
},
false
);
document.addEventListener(
"oms_getCategroyByProductError", // + reqId,
function (e) {
console.log(e);
},
false
);
let getShippingPrimaryPriceEvent = new CustomEvent(
"oms_getCategroyByProduct",
{
detail: {
// request_id: reqId,
client_id: $clientId,
product_id: "ab46cb841a901675acec53195ed06834"
},
}
);
document.dispatchEvent(getShippingPrimaryPriceEvent);
*/
var urlParams = new URLSearchParams(window.location.search);
var myParam = urlParams.get('custom_tags');
//console.log('myParam',myParam);
if (myParam) {
document.cookie = "custom_tags=" + myParam;
}
urlParams = new URLSearchParams(window.location.search);
myParam = urlParams.get('city');
//console.log('myParam',myParam);
if (myParam) {
document.cookie = "city=" + myParam;
}
urlParams = new URLSearchParams(window.location.search);
myParam = urlParams.get('pc');
//console.log('myParam',myParam);
if (myParam) {
document.cookie = "pc=" + myParam;
}
document.addEventListener("oms_userRegisterSuccess", function (e) {
let result = e.detail.result;
var cooks = document.cookie;
var ca = cooks.split(';');
// console.log(ca);
var ck_name = ""
var ck_city = ""
var ck_pc = ""
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
var name = 'custom_tags=';
if (c.includes(name)) {
ck_name = c.substring(name.length, c.length);
//console.log(ck_name)
}
var name = 'city=';
if (c.includes(name)) {
ck_city = c.substring(name.length, c.length);
//console.log(ck_name)
}
var name = 'pc=';
if (c.includes(name)) {
ck_pc = c.substring(name.length, c.length);
//console.log(ck_name)
}
}
}, false);
var scheme = [
"#4C4C4C","#1F2029","#35404E","#282938","#00A0BE","#C67C48","#32CF72", "#4155D1","#B86838","#D81196","#149C92","#786DC4","#DB2C38","#83C057", "#A4A4A4","#55747C","#FFFFFF"
];
var Color = function Color(hexVal) { //define a Color class for the color objects
this.hex = hexVal;
};
constructColor = function(colorObj){
var hex = colorObj.hex.substring(1);
/* Get the RGB values to calculate the Hue. */
var r = parseInt(hex.substring(0, 2), 16) / 255;
var g = parseInt(hex.substring(2, 4), 16) / 255;
var b = parseInt(hex.substring(4, 6), 16) / 255;
/* Getting the Max and Min values for Chroma. */
var max = Math.max.apply(Math, [r, g, b]);
var min = Math.min.apply(Math, [r, g, b]);
/* Variables for HSV value of hex color. */
var chr = max - min;
var hue = 0;
var val = max;
var sat = 0;
if (val > 0) {
/* Calculate Saturation only if Value isn't 0. */
sat = chr / val;
if (sat > 0) {
if (r == max) {
hue = 60 * (((g - min) - (b - min)) / chr);
if (hue < 0) {
hue += 360;
}
} else if (g == max) {
hue = 120 + 60 * (((b - min) - (r - min)) / chr);
} else if (b == max) {
hue = 240 + 60 * (((r - min) - (g - min)) / chr);
}
}
}
colorObj.chroma = chr;
colorObj.hue = hue;
colorObj.sat = sat;
colorObj.val = val;
colorObj.luma = 0.3 * r + 0.59 * g + 0.11 * b;
colorObj.red = parseInt(hex.substring(0, 2), 16);
colorObj.green = parseInt(hex.substring(2, 4), 16);
colorObj.blue = parseInt(hex.substring(4, 6), 16);
return colorObj;
};
sortColorsByHue = function (colors) {
return colors.sort(function (a, b) {
return a.hue - b.hue;
});
};
sortColorsByLuma = function (colors) {
return colors.sort(function (a, b) {
return a.luma - b.luma;
});
};
mapHex = function(color) {
return color.hex;
}
outputColors = function(hexArray) {
var colors = [];
hexArray.map((i, v) => {
var color = new Color(i);
constructColor(color);
colors.push(color);
});
sortColorsByHue(colors);
//sortColorsByLuma(colors);
const sortedArr = colors.map(mapHex);
for(i = 0; i < sortedArr.length; i+=1) {
const ele = document.querySelector(`.product-variant-wrapper .color-attr[data-code="${sortedArr[i]}"]`);
ele.style.order = i;
if(i >= 25 ){
ele.classList.add("extra-attr");
}
}
document.querySelector('.product-variant-wrapper').classList.add('loaded');
document.querySelector('.product-variant-wrapper').classList.remove('loading');
};
//outputColors(scheme);