luv-assets 1.1.4 → 1.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/js/category.min.js +1 -1
- package/dist/js/js.min.js +1 -1
- package/dist/js/product.min.js +1 -1
- package/dist/js/search-text.min.js +1 -0
- package/dist/js/search.min.js +1 -0
- package/package.json +1 -1
- package/readme.txt +2 -1
package/dist/js/category.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function resetUrl(){var url=category_url;var path="";
|
|
1
|
+
function resetUrl(p){var url=category_url;var path="";path+="/p"+p;url+=path;url+=window.location.search;return url}$(document).ready(function(){const lazyLoadInstance=new LazyLoad({});$(document).on("click","#filter-reset-js",function(){window.location.href=category_url});$(document).on("click","#apply-filter-js",function(){var url=new URL(category_url,window.location.origin);var params=new URLSearchParams;var keyword=$("#filter-keyword-js").val().trim();if(keyword)params.set("q",keyword);var begin=$("#filter-price-min-js").val().trim();var end=$("#filter-price-max-js").val().trim();var priceValid=val=>{let n=parseFloat(val);return!isNaN(n)&&n>=0};if(begin&&priceValid(begin)||end&&priceValid(end)){let min=begin&&priceValid(begin)?parseFloat(begin):0;let max=end&&priceValid(end)?parseFloat(end):0;params.set("price",min+"-"+max)}$(".filter-attr-js").each(function(){var attrCode=$(this).data("attr-code");var selectedIds=[];$(this).find(".filter-value-item-js.active").each(function(){selectedIds.push($(this).data("value-id"))});if(selectedIds.length>0){params.set(attrCode,selectedIds.join(","))}});url.search=params.toString();window.location.href=url.toString()});$(document).on("click",".filter-value-item-js",function(){var $item=$(this);var attrCode=$item.closest(".filter-attr-js").data("attr-code");var valueName=$item.text().replace(/\s*✓\s*$/,"").trim();var valueId=$item.data("value-id");if($item.hasClass("active")){$item.removeClass("active bg-primary text-white");var idx=selected_attr_values_map[attrCode].indexOf(valueName);if(idx!==-1)selected_attr_values_map[attrCode].splice(idx,1)}else{if(selected_attr_values_map[attrCode].length>=10){alert("You can select up to ten items");return}$item.addClass("active bg-primary text-white");selected_attr_values_map[attrCode].push(valueName)}});$("#product-list-more").infiniteScroll({path:function(){if(this.loadCount<maxPage-1){return resetUrl(this.loadCount+2)}},append:".col-6.col-sm-4.col-md-3.flex-shrink-0",history:"replace",historyTitle:false,responseBody:"text",checkLastPage:true,scrollThreshold:100,status:".page-load-status",prefill:false,debug:false});$("#product-list-more").on("load.infiniteScroll",function(event,body,path){});$("#product-list-more").on("error.infiniteScroll",function(event,error,path){alert("Failed to load more products.")});$("#product-list-more").on("append.infiniteScroll",function(event,body,path,items){if(lazyLoadInstance){lazyLoadInstance.update()}});$("#product-list-more").on("last.infiniteScroll",function(){})});
|
package/dist/js/js.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function isStrictMode(){return function(){return!this}()}function isSurportedLoading(){return"loading"in HTMLImageElement.prototype}function
|
|
1
|
+
function isStrictMode(){return function(){return!this}()}function isSurportedLoading(){return"loading"in HTMLImageElement.prototype}function getUrlParams(){const url=new URL(window.location.href);const searchParams=new URLSearchParams(url.search);return searchParams}const UrlUtils={create:(url,origin=window.location.origin)=>new URL(url,origin),getCurrentParams:()=>new URLSearchParams(window.location.search),mergeParams:(url,paramsObj)=>{const newUrl=typeof url==="string"?new URL(url,window.location.origin):url;Object.keys(paramsObj).forEach(key=>{if(paramsObj[key]!==undefined&¶msObj[key]!==null){newUrl.searchParams.set(key,paramsObj[key])}});return newUrl.toString()},buildQuery:paramsObj=>{const params=new URLSearchParams;Object.keys(paramsObj).forEach(key=>{if(paramsObj[key]!==undefined&¶msObj[key]!==null){params.set(key,paramsObj[key])}});return params.toString()},getParam:(url,paramName)=>{try{const urlObj=new URL(url,window.location.origin);return urlObj.searchParams.get(paramName)}catch(e){console.error("Invalid URL:",url);return null}}};function webLoadScript(url,callback){var script=document.createElement("script");script.type="text/javascript";if(typeof callback!="undefined"){if(script.readyState){script.onreadystatechange=function(){if(script.readyState=="loaded"||script.readyState=="complete"){script.onreadystatechange=null;callback()}}}else{script.onload=function(){callback()}}}script.src=url;document.body.appendChild(script)}function check_email(email){if(!email||email==""){return false}const myreg=/^([a-zA-Z0-9]+[_|\_|\.|-|\-]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.|-|\-]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;if(!myreg.test(email)){return false}return true}function check_pass(str){const re=/^\w{6,30}$/;if(re.test(str)){return true}else{return false}}function setCookie(name,value){const Days=30;const exp=new Date;exp.setTime(exp.getTime()+Days*24*60*60*1e3);document.cookie=name+"="+escape(value)+";expires="+exp.toGMTString()}function getCookie(name){const arr=document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));if(arr){return unescape(arr[2])}else{return null}}function showToast(msg,element){$(element).find(".toast-body").text(msg);const toastEl=$(element);if(toastEl){const toast=bootstrap.Toast.getOrCreateInstance(toastEl[0]);toast.show()}}$(document).ready(function(){if(typeof memberCheckUrl!=="undefined"&&!isEmpty(memberCheckUrl)){const ajax_params={};if(typeof product_id!=="undefined"&&!isEmpty(product_id)){ajax_params["product_id"]=product_id}$.ajax({async:true,timeout:6e3,dataType:"json",type:"get",data:ajax_params,url:memberCheckUrl,success:function(data,textStatus){if(data.loginStatus){$("#header-welcome-js").removeClass("d-none");$("#header-email-js").text(data.customer_email);$("#header-login-js").addClass("d-none")}if(data.favorite){$("#product-favorite-js").addClass("text-danger")}if(data.favorite_product_count){}if(data.affiliate){$("#affiliate-link-js").show()}if(data.cart_qty){$(".cart-item-count-js").text(data.cart_qty)}},error:function(XMLHttpRequest,textStatus,errorThrown){}})}$("#subscribe_btn").click(function(){$(this).prop("disabled",true);email=$("#subscribe_email").val();if(!check_email(email)){alert("Enter your email address");$("#subscribe_btn").prop("disabled",false);return false}$.ajax({dataType:"json",type:"post",data:{email:email},url:"/member/account/subscribe",success:function(data,textStatus){$("#subscribe_btn").prop("disabled",false);if(data.success){alert(data.message);$("#subscribe_email").val("")}else{alert(data.message)}},error:function(error){alert("Oops! Something went wrong. Please try again later.");$("#subscribe_btn").prop("disabled",false)}})})});function isValidSearchKeyword(keyword,maxLength=100){keyword=keyword.trim();if(keyword===""){return false}if(keyword.length>maxLength){return false}const safePattern=/^[\p{L}\p{N}\s.;:'"!?-]+$/u;if(!safePattern.test(keyword)){return false}const escapedKeyword=keyword.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");return true}const historyKey="search_history";function pullSearchHistory(Url){let localHistory=getCompatibleSearchHistoryFromLocalStorage();if(!isSyncNeeded(localHistory)){return}$.ajax({async:true,timeout:6e3,dataType:"json",type:"get",url:Url,success:function(data,textStatus){if(data.data.length>0){mergeLocalSearchHistory(data.data)}},error:function(XMLHttpRequest,textStatus,errorThrown){}})}function saveOneSearchHistory(keyword,Url){$.ajax({async:true,timeout:6e3,dataType:"json",type:"post",url:Url,data:{keyword:keyword},success:function(data,textStatus){},error:function(XMLHttpRequest,textStatus,errorThrown){}})}function saveSearchToLocalStorage(keyword){let searchHistory=getCompatibleSearchHistoryFromLocalStorage();const index=searchHistory.data.indexOf(keyword);if(index>-1){searchHistory.data.splice(index,1)}searchHistory.data.unshift(keyword);if(searchHistory.data.length>maxSearchHistoryLength){searchHistory.data=searchHistory.data.slice(0,maxSearchHistoryLength)}searchHistory.update_time=(new Date).toISOString();localStorage.setItem(historyKey,JSON.stringify(searchHistory))}function removeSearchFromLocalStorage(keyword){let searchHistory=JSON.parse(localStorage.getItem(historyKey));if(searchHistory&&Array.isArray(searchHistory.data)){if(keyword){searchHistory.data=searchHistory.data.filter(item=>item!==keyword)}else{localStorage.removeItem(historyKey);return}searchHistory.update_time=(new Date).toISOString();localStorage.setItem(historyKey,JSON.stringify(searchHistory));return}else{localStorage.removeItem(historyKey);return}}function getSearchHistoryFromLocalStorage(){let searchHistory=JSON.parse(localStorage.getItem(historyKey))||{update_time:null,last_sync_time:null,data:[]};return searchHistory}function getCompatibleSearchHistoryFromLocalStorage(){const rawHistory=localStorage.getItem(historyKey);if(!rawHistory){return{update_time:null,last_sync_time:null,data:[]}}let history;try{history=JSON.parse(rawHistory)}catch(e){console.error("Failed to parse history:",e);return{update_time:null,last_sync_time:null,data:[]}}if(Array.isArray(history)){history={update_time:null,last_sync_time:null,data:history};localStorage.setItem(historyKey,JSON.stringify(history))}return history}function isSyncNeeded(history){if(!history||!history.last_sync_time)return true;const lastSyncTime=new Date(history.last_sync_time);const currentTime=new Date;const diffInMinutes=(currentTime-lastSyncTime)/(1e3*60);return diffInMinutes>15}function mergeLocalSearchHistory(serverHistory){let localHistory=getCompatibleSearchHistoryFromLocalStorage();localHistory.last_sync_time=(new Date).toISOString();let mergedData=Array.from(new Set([...localHistory.data,...serverHistory]));localHistory.data=mergedData;localStorage.setItem(historyKey,JSON.stringify(localHistory))}function is_valid_url(url){var regex=new RegExp(/^(https?|s):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i);return regex.test(url)}function is_same_domain(base_url,custom_url){base_url=base_url.replace("http://","").replace("https://","").replace("www.","").replace("m.","").split(/[/?#]/)[0];custom_url=custom_url.replace("http://","").replace("https://","").replace("www.","").replace("m.","").split(/[/?#]/)[0];return base_url==custom_url||base_url.indexOf(custom_url)!=-1||custom_url.indexOf(base_url)!=-1}function process_friendly_url(param,value,url){var hash=url.split("#")[1];url=url.split("#")[0];var re=new RegExp("([/]"+param+"[/][^?]*)"),match=re.exec(url);var re2=new RegExp("([?].*)"),match2=re2.exec(url);if(match&&match[0])url=url.replace(match[0],"");if(match2&&match2[0])url=url.replace(match2[0],"");var re3=new RegExp("([/]"+param+"$)"),match3=re3.exec(url);if(match3&&match3[0])url=url.replace(match3[0],"");url=url.replace(/\/+$/,"");url=url+"/"+param+"/"+value+"/";if(match2&&match2[0])url=url+match2[0];if(hash)url+="#"+hash;return url}function add_query_arg(param,value,url){var re=new RegExp("[\\?&]"+param+"=([^&#]*)"),match=re.exec(url),delimiter,newString;var hash=url.split("#")[1];url=url.split("#")[0];if(match===null){var hasQuestionMark=/\?/.test(url);delimiter=hasQuestionMark?"&":"?";newString=url+delimiter+param+"="+value}else{delimiter=match[0].charAt(0);newString=url.replace(re,delimiter+param+"="+value)}if(hash){newString+="#"+hash}return newString}
|
package/dist/js/product.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function saveProductToLocalStorage(product_spu,maxHistoryLength=30){let productHistory=JSON.parse(localStorage.getItem(product_history_key))||[];const index=productHistory.indexOf(product_spu);if(index>-1){productHistory.splice(index,1)}productHistory.unshift(product_spu);if(productHistory.length>maxHistoryLength){productHistory=productHistory.slice(0,maxHistoryLength)}localStorage.setItem(product_history_key,JSON.stringify(productHistory))}function fetchAndDisplayViewedProducts(history_url){let productHistory=JSON.parse(localStorage.getItem(product_history_key)||"[]");if(productHistory.length===0){return}const viewedProductsElement=$("#viewed-products-js");viewedProductsElement.empty();$.ajax({url:history_url,method:"POST",data:{productIds:productHistory},success:function(response){viewedProductsElement.html(response.html)},error:function(){viewedProductsElement.html("<p>Failed to load viewed products.</p>")}})}function scrollToElement(targetElement,header_height){const headerHeight=header_height||60;const targetOffsetTop=targetElement.offset().top-headerHeight;$("html, body").animate({scrollTop:targetOffsetTop},{duration:300,easing:"swing"})}function renderSizeChart(){const sizes=Object.keys($size_charts);if(sizes.length===1){renderSizeChartSingle()}else{renderSizeChartMulti()}const tab=['<ul class="nav nav-tabs mb-4" id="sizeTabs" role="tablist">'];for(i=0;i<sizes.length;i++){const key=sizes[i];tab.push('<li class="nav-item" role="presentation">');tab.push(`<button class="nav-link ${i===0?"active":""}" id="${key}-tab" data-bs-toggle="tab" data-bs-target="#${key}" type="button">${key}</button>`);tab.push("</li>")}tab.push("</ul>");const content=['<div class="tab-content" id="sizeTabsContent">'];for(i=0;i<sizes.length;i++){const key=sizes[i];const size=$size_charts[key];content.push(`<div class="table-responsive tab-pane fade ${i===0?"show active":""}" id="${key}" role="tabpanel" aria-labelledby="${key}-tab">`);content.push(renderTable(size));content.push("</div>")}content.push("</div>");$("#panelsStayOpen-sizeChart .accordion-body").append(tab.join(""));$("#panelsStayOpen-sizeChart .accordion-body").append(content.join(""))}function renderSizeChartMulti(){}function renderSizeChartSingle(){}function renderTable(data){const table=['<table class="table table-sm table-bordered table-striped size-table">'];const thead=["<thead>"];const tbody=["<tbody>"];const attrNames=[];for(const size in data){data[size].forEach(item=>{if(!attrNames.includes(item.attr_name)){attrNames.push(item.attr_name)}});break}thead.push("<tr>");thead.push("<th>Size</th>");attrNames.forEach(name=>{thead.push(`<th>${name}</th>`)});thead.push("</tr>");tbody.push("");for(const size in data){const row=["<tr><td>"+size.toUpperCase()+"</td>"];const measurements={};data[size].forEach(m=>{measurements[m.attr_name]=`${m.inch}`});attrNames.forEach(name=>{row.push(`<td>${measurements[name]||"—"}</td>`)});tbody.push(row.join(""))}tbody.push("</tbody>");table.push(thead.join(""));table.push(tbody.join(""));table.push("</table>");return table.join("")}function renderSizeChartEle(){const sizes=Object.keys($size_charts);for(i=0;i<sizes.length;i++){const key=sizes[i];const size=$size_charts[key];renderTableEle(size,key+"Table"+default_size_unit,default_size_unit);renderTableEle(size,key+"Table"+second_size_unit,second_size_unit)}}function renderTableEle(data,tableId,system){const $table=$(`#${tableId}`);const $thead=$table.find("thead tr");const $tbody=$table.find("tbody");const key=system.toLowerCase();const attrNames=[];for(const size in data){data[size].forEach(item=>{if(!attrNames.includes(item.attr_name)){attrNames.push(item.attr_name)}});break}$thead.empty().append("<th>Size</th>");attrNames.forEach(name=>{$thead.append(`<th>${name}</th>`)});$tbody.empty();for(const size in data){const row=["<tr><td>"+size.toUpperCase()+"</td>"];const measurements={};data[size].forEach(m=>{measurements[m.attr_name]=`${m[key]}`});attrNames.forEach(name=>{row.push(`<td>${measurements[name]||"—"}</td>`)});row.push("</tr>");$tbody.append(row.join(""))}}function loadProductDetail(productInfo){let rows="";if(productInfo.spu_attr.length>0){for(let index=0;index<productInfo.spu_attr.length;index++){const detail=productInfo.spu_attr[index];const row=`\n <tr>\n <td>${detail.attr_name}</td>\n <td>${detail.value_name}</td>\n </tr>`;rows+=row}}if(productInfo.custom_attr.length>0){for(let index=0;index<productInfo.custom_attr.length;index++){const detail=productInfo.custom_attr[index];const tr="<tr>";const td=`<td>${detail.attr_name}</td>`;let lists="<td><ul>";for(let i=0;i<detail.list.length;i++){const value=detail.list[i];const listItem=`<li>${value.measurements_name}: ${value.value_with_unit}</li>`;lists+=listItem}lists+="</ul></td>";rows+=tr+td+lists+"</tr>"}}$(".product_detail_img").attr("src",productInfo["image"]);$(".product_detail_name").html(productInfo["name"]);$(".product_detail_price").html(`${ecommerce_product.symbol}${productInfo["price"]}`);$(".product_qty_val").html(productInfo["qty"]);$(".product-options-js tbody").html(rows);return}function parseHeight(heightStr){const match=heightStr.match(/^(\d+)'?(\d*)"?$/);if(!match){throw new Error("Invalid height format. Expected format like '5'6 or 5'6\"")}const feet=parseInt(match[1],10)||0;const inches=parseInt(match[2],10)||0;return{feet:feet,inches:inches}}function initCustomize(relatedAttr,sizeSystem,attrValue){let sizeUnit;if(sizeSystem==="imperial"){sizeUnit="inch"}else{sizeUnit="cm"}let selectedAttr={};let pointCode;for(let i=0;i<$size_charts[relatedAttr][attrValue].length;i++){pointCode=$size_charts[relatedAttr][attrValue][i]["point_code"];if(pointCode==="height"){if(sizeUnit==="inch"){const{feet:feet,inches:inches}=parseHeight($size_charts[relatedAttr][attrValue][i]["ft"]);$("#feet").val(feet);$("#inches").val(inches)}else{$("#cm").val($size_charts[relatedAttr][attrValue][i][sizeUnit])}}else{selectedAttr[pointCode]=$size_charts[relatedAttr][attrValue][i][sizeUnit]}}const $inputs=$(`#${relatedAttr}-custom-form-container input.custom-input-js`);$inputs.each(function(){const name=$(this).attr("name");if(selectedAttr[name]){$(this).val(selectedAttr[name])}})}function calculateProductPrice(productInfo){let totalPrice=parseFloat(ecommerce_product.price);if(productInfo["spu_attr"]&&typeof productInfo["spu_attr"]==="object"&&productInfo["spu_attr"]!==null){for(let key in productInfo["spu_attr"]){if(productInfo["spu_attr"][key].value_price>0){totalPrice+=parseFloat(productInfo["spu_attr"][key].value_price)}}}if(productInfo["custom_attr"]&&typeof productInfo["custom_attr"]==="object"&&productInfo["custom_attr"]!==null){for(let key in productInfo["custom_attr"]){if(productInfo["custom_attr"][key].value_price>0){totalPrice+=parseFloat(productInfo["custom_attr"][key].value_price)}}}totalPrice=totalPrice.toFixed(2);product_info.price=totalPrice;return totalPrice}function checkCustomInfo($input){const value=$input.val();const required=$input.prop("required");if(required&&(value===""||value===0)){return false}const min=parseFloat($input.attr("min"));if(!isNaN(min)&&value<min){return false}const max=parseFloat($input.attr("max"));if(!isNaN(max)&&value>max){return false}return true}function getSpuAttrValueInfo(attr,attrValue){const attrValueInfo={attr_code:attr,value_code:attrValue,attr_name:$sku_map[attr].attr_name,value_name:$sku_map[attr]["values"][attrValue].value_name,value_price:$sku_map[attr]["values"][attrValue].value_price,base_value_price:$sku_map[attr]["values"][attrValue].base_value_price};return attrValueInfo}function getCustomAttrValueInfo(attr,attrValue,value_price,base_value_price){let value_code,value_name;if(!attrValue){value_code="";value_name=""}else{value_code=attrValue;value_name=$sku_map[attr]["values"][attrValue].value_name}const attrValueInfo={attr_code:attr,value_code:value_code,attr_name:$sku_map[attr].attr_name,value_name:value_name,value_price:value_price,base_value_price:base_value_price};return attrValueInfo}function setProductSpuAttr(attr,attrValue,options){const attrValueInfo=getSpuAttrValueInfo(attr,attrValue);const newSpuAttr={...product_info.spu_attr,[attr]:attrValueInfo};if(product_info.custom_attr&&product_info.custom_attr.hasOwnProperty(attr)){delete product_info.custom_attr[attr]}const updates={spu_attr:newSpuAttr};if(options&&options.attrImg){updates.image=options.imgSrc}updateProductInfo(updates)}function setProductCustomAttr(attr,attrValue,value_price,base_value_price){const attrValueInfo=getCustomAttrValueInfo(attr,attrValue,value_price,base_value_price);const newCustomAttr={...product_info.custom_attr,[attr]:attrValueInfo};if(product_info.spu_attr&&product_info.spu_attr.hasOwnProperty(attr)){delete product_info.spu_attr[attr]}updateProductInfo({custom_attr:newCustomAttr})}function switchToSpuAttr(attr,attrValue){if(product_info.custom_attr&&product_info.custom_attr.hasOwnProperty(attr)){delete product_info.custom_attr[attr]}if(attrValue){setProductSpuAttr(attr,attrValue)}}function setProductImage(img_src){var filename=img_src.split("/").splice(-1).toString();product_info["image"]=img_src;updateProductInfo({image:img_src})}function initProductAttr(){product_info["name"]=ecommerce_product.name;product_info["price"]=ecommerce_product.price;product_info["image"]=$("#product-main-image-js").val();product_info["product_id"]=ecommerce_product.id;product_info["spu"]=ecommerce_product.spu;product_info["qty"]=1;product_info["spu_attr"]={};product_info["custom_attr"]={};for(let index=0;index<$selected_sku_list.length;index++){const attr=$selected_sku_list[index].attr_code;const attrValue=$selected_sku_list[index].value_code;setProductSpuAttr(attr,attrValue)}}function getFilenameFromImgSrc(imgSrc){const filename=imgSrc.split("/").splice(-1).toString();return filename}function getIndexByImgSrc(imgSrc){let index=-1;$(".swiper-slide img").each(function(i,element){const currentImgSrc=$(this).data("src");const filename=getFilenameFromImgSrc(currentImgSrc);if(filename===getFilenameFromImgSrc(imgSrc)){index=i;return}});return index}function goToSlide(index,speed=null){swiper.slideTo(index,speed,false)}function updateProductInfo(updates){const keys=Object.keys(updates);for(let index=0;index<keys.length;index++){const key=keys[index];if(key==="image"){const imgSrc=updates[key];const index=getIndexByImgSrc(imgSrc);goToSlide(index)}}Object.assign(product_info,updates);$(document).trigger("product:updated",[product_info])}function renderProductUI(info){const price=calculateProductPrice(info);$("#total-price").text(`${ecommerce_product.symbol}${price}`)}function showAttrErrorMessage(attr){$(`#${attr}-error-message`).addClass("d-block")}function hideAttrErrorMessage(attr){$(`#${attr}-error-message`).removeClass("d-block")}function isAllRequiredAttrsSelected(requiredAttrs=$spu_attr){return requiredAttrs.every(attr=>product_info.spu_attr[attr]||product_info.custom_attr[attr])}function getProductInfo(){var result={success:false,data:{name:product_info.name,product_id:product_info.product_id,spu:product_info.spu,qty:product_info.qty,image:product_info.image,price:product_info.price,spu_attr:[],size_chart:{},custom_attr:[]},errors:[]};var $selected_size_charts={};for(var index=0;index<$spu_attr.length;index++){var errror={type:null,key:null,jQueryElement:null};var attr=$spu_attr[index];if(product_info.spu_attr&&typeof product_info.spu_attr==="object"&&product_info.spu_attr!==null&&product_info.spu_attr[attr]&&typeof product_info.spu_attr[attr]==="object"&&product_info.spu_attr[attr]!==null){result.data.spu_attr.push(product_info.spu_attr[attr]);var value_code=product_info.spu_attr[attr].value_code;if($size_charts.hasOwnProperty(attr)&&$size_charts[attr].hasOwnProperty(value_code)){$selected_size_charts[attr]=$size_charts[attr][value_code]}}else if(product_info.custom_attr&&typeof product_info.custom_attr==="object"&&product_info.custom_attr!==null&&product_info.custom_attr[attr]&&typeof product_info.custom_attr[attr]==="object"&&product_info.custom_attr[attr]!==null){product_info.custom_attr[attr].list=[];cusResult=collectCustomMeasurements(attr);if(cusResult.errors.length>0){errror.type="custom_attr";errror.jQueryElement=cusResult.errors[0];result.errors.push(errror);return result}else{cusResult.data.forEach(function(item){product_info.custom_attr[attr].list.push(item)})}result.data.custom_attr.push(product_info.custom_attr[attr])}else{errror.type="spu_attr";errror.key=attr;errror.jQueryElement=$(`#${attr}`);result.errors.push(errror);return result}}if(Object.keys($selected_size_charts).length>0){product_info.size_chart=$selected_size_charts;result.data.size_chart=product_info.size_chart}result.success=true;return result}function renderErrorMsg(err){scrollToElement(err.jQueryElement);if(err.type==="spu_attr"){showAttrErrorMessage(err.key)}else if(err.type==="custom_attr"){err.jQueryElement.addClass("is-invalid");err.jQueryElement.focus()}}function collectCustomMeasurements(attr){var result={success:true,data:[],errors:[]};var $container=$("#"+attr+"-custom-form-container");$container.find("div.input-group").each(function(){var $group=$(this);if(!$group.is(":visible")){return true}var $input=$group.find("input").first();if(!checkCustomInfo($input)){result.success=false;result.errors.push($input);return false}var name=$input.attr("name");var $labelSpan=$group.find(".measurements-label-js");var measurements_name=$labelSpan.length?$labelSpan.text().trim():"Unknown";if(name==="feet"){var feet=$input.val();var $inchesEle=$group.find("#inches");if(!checkCustomInfo($inchesEle)){result.success=false;result.errors.push($inchesEle);return false}var inches=$inchesEle.val();if(feet!==""&&inches!==""){var measurements_code=$group.data("measurements-code");result.data.push({measurements_code:measurements_code,measurements_name:measurements_name,value_with_unit:feet+"'"+inches+'"'})}}else{var value=$input.val();if(value!==""){var measurements_code=name;var $unitSpan=$group.find(".custom-input-unit-js");var unit=$unitSpan.length?$unitSpan.text().trim():"";result.data.push({measurements_code:measurements_code,measurements_name:measurements_name,value_with_unit:value+" "+unit})}}});return result}function init_share(){var ogUrl=$('meta[property="og:url"]').attr("content");var ogTitle=$('meta[property="og:title"]').attr("content");var elems=$("[data-sharer]");for(var i=0;i<elems.length;i++){elems[i].setAttribute("data-url",ogUrl);elems[i].setAttribute("data-title",ogTitle)}$("#affiliate-link-url-input-js").val(ogUrl)}function handleFavoriteClickThrottle(e){e.preventDefault();var self=$(this);$.ajax({url:productFavoriteUrl,method:"GET",data:{spu:ecommerce_product.spu},dataType:"json",timeout:5e3}).done(function(response){loginStatus=response.loginStatus;if(!loginStatus){window.location.href=memberLoginUrl;return}if(response.favoriteStatus){self.addClass("text-danger")}else{self.removeClass("text-danger")}showToast(response.content,"#toast-js")}).fail(function(){alert("Operation failed. Please try again later.")}).always(function(){})}function handleFavoriteClickA(e){e.preventDefault();e.stopPropagation();var self=$(this);if(self.prop("disabled")){return}self.prop("disabled",true);self.addClass("opacity-50");$.ajax({url:productFavoriteUrl,method:"GET",data:{spu:ecommerce_product.spu},dataType:"json",timeout:5e3}).done(function(response){loginStatus=response.loginStatus;if(!loginStatus){window.location.href=memberLoginUrl;return}if(response.favoriteStatus){self.addClass("text-danger")}else{self.removeClass("text-danger")}showToast(response.content,"#toast-js")}).fail(function(){alert("Operation failed. Please try again later.")}).always(function(){self.prop("disabled",false);self.removeClass("opacity-50")})}function handleFavoriteClickB(e){e.preventDefault();e.stopPropagation();var self=$(this);self.toggleClass("text-danger");$.ajax({url:productFavoriteUrl,method:"GET",data:{spu:ecommerce_product.spu},dataType:"json",timeout:5e3}).done(function(response){loginStatus=response.loginStatus;if(!loginStatus){window.location.href=memberLoginUrl;return}if(response.favoriteStatus){self.addClass("text-danger")}else{self.removeClass("text-danger")}showToast(response.content,"#toast-js")}).fail(function(){self.toggleClass("text-danger");showToast("Operation failed","#toast-js")}).always(function(){})}function checkRemark(customer_remark){if(customer_remark.length>order_remark_max_length){return false}return true}function handleAddToCartClick(e){e.preventDefault();e.stopPropagation();var self=$(this);if(self.prop("disabled")){return}self.prop("disabled",true);self.addClass("opacity-50");var result=getProductInfo();if(!result.success){self.prop("disabled",false);self.removeClass("opacity-50");showToast("Failed to obtain product information. Please refresh and try again.","#toast-js");return}var remark=$("#customer-remark-js").val();if(!checkRemark(remark)){self.prop("disabled",false);self.removeClass("opacity-50");showToast(order_remark_message,"#toast-js")}var data_params=result.data;data_params["customer_remark"]=remark;$.ajax({async:true,timeout:6e3,dataType:"json",type:"post",data:JSON.stringify(data_params),url:addToCartUrl,success:function(response){if(response.status=="success"){var items_count=response.items_count;$(".cart-item-count-js").text(items_count);var $modal=$("#productBottomSheet");var modalInstance=bootstrap.Modal.getOrCreateInstance($modal[0]);modalInstance.hide()}showToast(response.message,"#toast-js")},error:function(XMLHttpRequest,textStatus,errorThrown){let message="Operation failed. Please try again later.";if(textStatus==="timeout"){message="Request timed out. Please check your network and try again."}else if(XMLHttpRequest.status===0){message="Network connection failed. Please check your internet."}else if(XMLHttpRequest.status===401){window.location.href=memberLoginUrl;return}else if(XMLHttpRequest.status>=500){message="Server is busy. Please try again later."}else if(XMLHttpRequest.status>=400){message="Invalid request. Please try again."}else{console.error("AJAX Error:",textStatus,errorThrown)}console.log(message)},complete:function(){self.prop("disabled",false);self.removeClass("opacity-50")}})}function paypalBuynowCreatePayment(){var FUNDING_SOURCES=[paypal.FUNDING.PAYPAL];FUNDING_SOURCES.forEach(function(fundingSource){var button=paypal.Buttons({fundingSource:fundingSource,style:{label:"buynow"},onClick:function(){var remark=$("#customer-remark-js").val();if(!checkRemark(remark)){self.prop("disabled",false);self.removeClass("opacity-50");showToast(order_remark_message,"#toast-js");return false}return true},createOrder:(data,actions)=>{var result=getProductInfo();var data_params=result.data;data_params["customer_remark"]=$("#customer-remark-js").val();return fetch(paypalCreateOrderUrl,{method:"post",body:JSON.stringify(data_params),headers:{"content-type":"application/json"}}).then(response=>{if(!response.ok){throw new Error("Network response was not ok")}return response.json()}).then(order=>{if(order.id=="-1"){throw new Error(order.message)}return order.id}).catch(error=>{alert(error)})},onApprove:(data,actions)=>fetch(paypalCaptureOrderUrl,{method:"post",body:JSON.stringify(data),headers:{"content-type":"application/json"}}).then(response=>{if(!response.ok){throw new Error("Network response was not ok!")}return response.json()}).then(orderData=>{if(orderData.order_sn=="-1"){if(orderData.error_issue==="INSTRUMENT_DECLINED"){alert(orderData.message);return actions.restart()}else{throw new Error(orderData.message)}}const order_sn=orderData.order_sn;actions.redirect(`${paypalFinishOrderUrl}?order_sn=${order_sn}`)}).catch(error=>{alert(error)})});if(button.isEligible()){button.render("#product-paypal-container-js")}})}$(function(){const lazyLoadInstance=new LazyLoad({});$(document).on("product:updated",(e,info)=>{renderProductUI(info)});swiper=new Swiper(".swiper",{autoplay:{delay:5e3},pagination:{el:".swiper-pagination",type:"fraction",renderFraction:function(currentClass,totalClass){return'<span class="swiper-pagination-current">'+currentClass+'</span> / <span class="swiper-pagination-total">'+totalClass+"</span>"}}});initProductAttr();fetchAndDisplayViewedProducts(historyUrl);saveProductToLocalStorage(ecommerce_product.spu);if(products_more_count>products_more_count_min){let isLoading=false;let morePageNum=1;function loadMoreProducts(){if(isLoading)return;isLoading=true;$("#product-list-more").append('<div id="loading-more" class="col-12 text-center my-3">Loading...</div>');$.ajax({url:productsMoreUrl,method:"GET",data:{p:morePageNum},dataType:"json",timeout:5e3}).done(function(response){if(response.html&&response.html.trim()!==""){$("#product-list-more").append(response.html);lazyLoadInstance.update();morePageNum=response.next_page}else{observer.unobserve(document.getElementById("load-trigger"));$("#product-list-more").append('<div class="col-12 text-center text-muted">No more products.</div>')}}).fail(function(){alert("Failed to load more products.")}).always(function(){$("#loading-more").remove();isLoading=false})}const throttledLoad=_.throttle(function(){if(!isLoading){loadMoreProducts()}},1e3,{trailing:true});const observer=new IntersectionObserver(entries=>{if(entries[0].isIntersecting){throttledLoad()}},{rootMargin:"100px"});if(document.getElementById("load-trigger")){observer.observe(document.getElementById("load-trigger"))}}$("#panelsStayOpen-sizeChart").on("show.bs.collapse",function(){if(!$(this).data("rendered")){renderSizeChartEle();$(this).data("rendered",true)}});let currentUnit=default_size_unit;function switchSizeUnit(unit){currentUnit=unit;const activeTabContentPrefix=$("#sizeTabs .nav-link.active").data("content-prefix");const contentId=activeTabContentPrefix+unit;$("#"+contentId).addClass("show active").siblings(".tab-pane").removeClass("show active");if(unit===default_size_unit){$("#switchToDefault-js").addClass("btn-danger").removeClass("btn-secondary");$("#switchToSecond-js").addClass("btn-secondary").removeClass("btn-danger")}else{$("#switchToSecond-js").addClass("btn-danger").removeClass("btn-secondary");$("#switchToDefault-js").addClass("btn-secondary").removeClass("btn-danger")}}$("#switchToDefault-js").on("click",function(){switchSizeUnit(default_size_unit)});$("#switchToSecond-js").on("click",function(){switchSizeUnit(second_size_unit)});$("#sizeTabs .nav-link").on("shown.bs.tab",function(){switchSizeUnit(currentUnit)});$("#affiliate-link-url-copy-js").on("click",function(e){e.preventDefault();var $this=$(this);$("#affiliate-link-url-input-js").select();document.execCommand("copy");$this.find(".affiliate-link-url-copy-label-js").addClass("d-none");$this.find(".affiliate-link-url-copy-label-copied-js").removeClass("d-none");setTimeout(function(){$this.find(".affiliate-link-url-copy-label-js").removeClass("d-none");$this.find(".affiliate-link-url-copy-label-copied-js").addClass("d-none")},2e3)});$(".product-info-attr-js").on("click",".attr-value-js button",function(e){e.preventDefault();const self=$(this);const $fieldset=self.closest("fieldset");const attr=$fieldset.attr("id");const attrValue=self.data("attr-value");self.closest("div").find("button").removeClass("border-danger");self.removeClass("border-light");self.addClass("border-danger");hideAttrErrorMessage(attr);$fieldset.find(".product-selected-attr-value-js").data("value",attrValue).data("value-for-restore",attrValue).text($sku_map[attr]["values"][attrValue].value_name);const attrHasPrice=$sku_map[attr].attr_has_price;const attrImg=self.data("attr-img");const options={attrHasPrice:attrHasPrice,attrImg:attrImg};if(attrImg===1){var img_src=self.find("img").attr("src");options.imgSrc=img_src}setProductSpuAttr(attr,attrValue,options);const showSizeChart=$sku_map[attr].show_size_value_chart;if(showSizeChart===1){const $chartContainer=$fieldset.find(".product-selected-chart-js");const $chartBody=$chartContainer.find("tbody");if($size_charts[attr][attrValue]){let rows="";$.each($size_charts[attr][attrValue],function(index,detail){const imperialValue=detail.ft?detail.ft:detail.inch?detail.inch+" in":"";const row=`\n <tr>\n <td>${detail.attr_name}</td>\n <td>${imperialValue}</td>\n <td>${detail.cm} cm</td>\n </tr>`;rows+=row});$chartBody.html(rows);$chartContainer.removeClass("d-none")}}const showSizeCustom=$sku_map[attr].show_size_custom;if(showSizeCustom===1){const $customCheckbox=$fieldset.find(".custom-toggle-checkbox-js");if($customCheckbox.is(":checked")){$customCheckbox.prop("checked",false).trigger("change")}}});$(".product-info-attr-js").on("change",".custom-toggle-checkbox-js",function(){const self=$(this);const customPrice=self.data("custom_price");const baseCustomPrice=self.data("base-custom-price");const $fieldset=self.closest("fieldset");const targetFormId=self.attr("aria-controls");const isChecked=self.is(":checked");$("#"+targetFormId).toggleClass("d-none",!isChecked).attr("aria-hidden",!isChecked);self.attr("aria-expanded",isChecked);const relatedAttr=$fieldset.attr("id");const relatedAttrValue=$fieldset.find(".product-selected-attr-value-js").data("value-for-restore");if(isChecked){$fieldset.find(".d-flex button").removeClass("border-danger");$fieldset.find(".product-selected-attr-value-js").data("value","").text("");hideAttrErrorMessage(relatedAttr);if(relatedAttrValue){const size_unit=$("#"+targetFormId).find(".unit-selector-js").val();initCustomize(relatedAttr,size_unit,relatedAttrValue)}$fieldset.find(".product-selected-chart-js").addClass("d-none");setProductCustomAttr(relatedAttr,relatedAttrValue,customPrice,baseCustomPrice)}else{$fieldset.find(".d-flex button").each(function(){if($(this).data("attr-value")==relatedAttrValue){$(this).removeClass("border-light");$(this).addClass("border-danger")}});if(relatedAttrValue){$fieldset.find(".product-selected-attr-value-js").data("value",relatedAttrValue).data("value-for-restore",relatedAttrValue).text($sku_map[relatedAttr]["values"][relatedAttrValue].value_name)}$fieldset.find(".product-selected-chart-js").removeClass("d-none");switchToSpuAttr(relatedAttr,relatedAttrValue)}});$(".product-info-attr-js").on("change",".unit-selector-js",function(){const $this=$(this);const sizeUnit=$this.val();const $fieldset=$this.closest("fieldset");const relatedAttr=$fieldset.attr("id");const relatedAttrValue=$fieldset.find(".product-selected-attr-value-js").data("value-for-restore");const imperialHeight=$("#imperial-height");const metricHeight=$("#metric-height");const weightUnitLabel=$("#weight-unit-label");const $cus_units=$fieldset.find(".custom-input-unit-js");if(sizeUnit==="imperial"){if(imperialHeight){imperialHeight.removeClass("d-none");metricHeight.addClass("d-none");weightUnitLabel.text("lb")}$cus_units.each(function(){$(this).text("in")})}else{if(imperialHeight){imperialHeight.addClass("d-none");metricHeight.removeClass("d-none");weightUnitLabel.text("kg")}$cus_units.each(function(){$(this).text("cm")})}if(relatedAttrValue){initCustomize(relatedAttr,sizeUnit,relatedAttrValue)}});$(".product-info-attr-js").on("focus",".custom-form-container-js input",function(){$(this).removeClass("is-invalid")}).on("blur",".custom-form-container-js input",function(){if(!checkCustomInfo($(this))){$(this).addClass("is-invalid")}});$("#qty-minus-js").click(function(){let v=parseInt($("#quantity").val());v-=1;if(v<=1){v=1}$("#quantity").val(v);product_info.qty=v;if(v<=1){$(this).addClass("disabled")}else{$(this).removeClass("disabled")}});$("#qty-plus-js").click(function(){let v=parseInt($("#quantity").val());v+=1;if(v>=100){v=100}$("#quantity").val(v);product_info.qty=v;$("#qty-minus-js").removeClass("disabled")});$("#product-detail-icon-share-js").click(function(e){e.preventDefault();init_share();var $modal=$("#shareBottomSheet");var modalInstance=new bootstrap.Modal($modal[0]);modalInstance.show()});$("#shareBottomSheet").on("hidden.bs.modal",function(){});$(".product-info-attr-js").on("click","button.measurement-trigger-js",function(e){e.preventDefault();var code=$(this).data("measurements-code");var name=$size_custom_image[code]["local_img_title"];$("#measurementBottomSheetModalLabel").text(name);const imagePath=$size_custom_image[code]["local_img"];if(imagePath){$("#modalImage").attr("src",imagePath)}const htmlContent=$size_custom_image[code]["local_img_desc"];if(htmlContent){$("#modalHtml").html(htmlContent)}var trigger=code;var $modal=$("#measurementBottomSheet");$modal.data("trigger-source",trigger);console.log("this modal is triggered by:",trigger);var modalInstance=new bootstrap.Modal($modal[0]);modalInstance.show()});$("#measurementBottomSheet").on("hidden.bs.modal",function(){var triggerSource=$(this).data("trigger-source");console.log("this modal is triggered by:",triggerSource,"and it is hidden");$(this).removeData("trigger-source")});$("#product-favorite-js").click(handleFavoriteClickA);$(".product-view-js").on("click","button",function(e){e.preventDefault();var result=getProductInfo();if(!result.success){renderErrorMsg(result.errors[0]);return false}loadProductDetail(result.data);var trigger=$(this).data("trigger");$("#productBottomSheetModalLabel").text($(this).text());if(trigger=="product-add-cart-view-js"){$("#product-add-cart-js").removeClass("d-none");$("#product-paypal-container-js").addClass("d-none")}else if(trigger=="product-buy-now-view-js"){if(typeof paypal=="undefined"){webLoadScript(paypalSdkUrl,function(){paypalBuynowCreatePayment()})}else{paypalBuynowCreatePayment()}$("#product-add-cart-js").addClass("d-none");$("#product-paypal-container-js").removeClass("d-none")}var $modal=$("#productBottomSheet");$modal.data("trigger-source",trigger);console.log("该 modal 是由:",trigger,"触发的");var modalInstance=bootstrap.Modal.getOrCreateInstance($modal[0]);modalInstance.show()});$("#productBottomSheet").on("hidden.bs.modal",function(){var triggerSource=$(this).data("trigger-source");console.log("this modal is triggered by:",triggerSource,"and it is hidden");if(triggerSource==="product-buy-now-view-js"){$("#paypal-button-container").empty()}$(this).removeData("trigger-source")});$("#product-add-cart-js").click(handleAddToCartClick);$("#customer-remark-js").on("focus",function(){$(this).removeClass("is-invalid")}).on("blur",function(){if(!checkRemark($(this).val())){$(this).addClass("is-invalid");showToast(order_remark_message,"#toast-js")}})});
|
|
1
|
+
function saveProductToLocalStorage(product_spu,maxHistoryLength=30){let productHistory=JSON.parse(localStorage.getItem(product_history_key))||[];const index=productHistory.indexOf(product_spu);if(index>-1){productHistory.splice(index,1)}productHistory.unshift(product_spu);if(productHistory.length>maxHistoryLength){productHistory=productHistory.slice(0,maxHistoryLength)}localStorage.setItem(product_history_key,JSON.stringify(productHistory))}function fetchAndDisplayViewedProducts(history_url){let productHistory=JSON.parse(localStorage.getItem(product_history_key)||"[]");if(productHistory.length===0){return}const viewedProductsElement=$("#viewed-products-js");viewedProductsElement.empty();$.ajax({url:history_url,method:"POST",data:{productIds:productHistory},success:function(response){viewedProductsElement.html(response.html)},error:function(){viewedProductsElement.html("<p>Failed to load viewed products.</p>")}})}function scrollToElement(targetElement,header_height){const headerHeight=header_height||60;const targetOffsetTop=targetElement.offset().top-headerHeight;$("html, body").animate({scrollTop:targetOffsetTop},{duration:300,easing:"swing"})}function renderSizeChart(){const sizes=Object.keys($size_charts);if(sizes.length===1){renderSizeChartSingle()}else{renderSizeChartMulti()}const tab=['<ul class="nav nav-tabs mb-4" id="sizeTabs" role="tablist">'];for(i=0;i<sizes.length;i++){const key=sizes[i];tab.push('<li class="nav-item" role="presentation">');tab.push(`<button class="nav-link ${i===0?"active":""}" id="${key}-tab" data-bs-toggle="tab" data-bs-target="#${key}" type="button">${key}</button>`);tab.push("</li>")}tab.push("</ul>");const content=['<div class="tab-content" id="sizeTabsContent">'];for(i=0;i<sizes.length;i++){const key=sizes[i];const size=$size_charts[key];content.push(`<div class="table-responsive tab-pane fade ${i===0?"show active":""}" id="${key}" role="tabpanel" aria-labelledby="${key}-tab">`);content.push(renderTable(size));content.push("</div>")}content.push("</div>");$("#panelsStayOpen-sizeChart .accordion-body").append(tab.join(""));$("#panelsStayOpen-sizeChart .accordion-body").append(content.join(""))}function renderSizeChartMulti(){}function renderSizeChartSingle(){}function renderTable(data){const table=['<table class="table table-sm table-bordered table-striped size-table">'];const thead=["<thead>"];const tbody=["<tbody>"];const attrNames=[];for(const size in data){data[size].forEach(item=>{if(!attrNames.includes(item.attr_name)){attrNames.push(item.attr_name)}});break}thead.push("<tr>");thead.push("<th>Size</th>");attrNames.forEach(name=>{thead.push(`<th>${name}</th>`)});thead.push("</tr>");tbody.push("");for(const size in data){const row=["<tr><td>"+size.toUpperCase()+"</td>"];const measurements={};data[size].forEach(m=>{measurements[m.attr_name]=`${m.inch}`});attrNames.forEach(name=>{row.push(`<td>${measurements[name]||"—"}</td>`)});tbody.push(row.join(""))}tbody.push("</tbody>");table.push(thead.join(""));table.push(tbody.join(""));table.push("</table>");return table.join("")}function renderSizeChartEle(){const sizes=Object.keys($size_charts);for(i=0;i<sizes.length;i++){const key=sizes[i];const size=$size_charts[key];renderTableEle(size,key+"Table"+default_size_unit,default_size_unit);renderTableEle(size,key+"Table"+second_size_unit,second_size_unit)}}function renderTableEle(data,tableId,system){const $table=$(`#${tableId}`);const $thead=$table.find("thead tr");const $tbody=$table.find("tbody");const key=system.toLowerCase();const attrNames=[];for(const size in data){data[size].forEach(item=>{if(!attrNames.includes(item.attr_name)){attrNames.push(item.attr_name)}});break}$thead.empty().append("<th>Size</th>");attrNames.forEach(name=>{$thead.append(`<th>${name}</th>`)});$tbody.empty();for(const size in data){const row=["<tr><td>"+size.toUpperCase()+"</td>"];const measurements={};data[size].forEach(m=>{measurements[m.attr_name]=`${m[key]}`});attrNames.forEach(name=>{row.push(`<td>${measurements[name]||"—"}</td>`)});row.push("</tr>");$tbody.append(row.join(""))}}function loadProductDetail(productInfo){let rows="";if(productInfo.spu_attr.length>0){for(let index=0;index<productInfo.spu_attr.length;index++){const detail=productInfo.spu_attr[index];const row=`\n <tr>\n <td>${detail.attr_name}</td>\n <td>${detail.value_name}</td>\n </tr>`;rows+=row}}if(productInfo.custom_attr.length>0){for(let index=0;index<productInfo.custom_attr.length;index++){const detail=productInfo.custom_attr[index];const tr="<tr>";const td=`<td>${detail.attr_name}</td>`;let lists="<td><ul>";for(let i=0;i<detail.list.length;i++){const value=detail.list[i];const listItem=`<li>${value.measurements_name}: ${value.value_with_unit}</li>`;lists+=listItem}lists+="</ul></td>";rows+=tr+td+lists+"</tr>"}}$(".product_detail_img").attr("src",productInfo["image"]);$(".product_detail_name").html(productInfo["name"]);$(".product_detail_price").html(`${ecommerce_product.symbol}${productInfo["price"]}`);$(".product_qty_val").html(productInfo["qty"]);$(".product-options-js tbody").html(rows);return}function parseHeight(heightStr){const match=heightStr.match(/^(\d+)'?(\d*)"?$/);if(!match){throw new Error("Invalid height format. Expected format like '5'6 or 5'6\"")}const feet=parseInt(match[1],10)||0;const inches=parseInt(match[2],10)||0;return{feet:feet,inches:inches}}function initCustomize(relatedAttr,sizeSystem,attrValue){let sizeUnit;if(sizeSystem==="imperial"){sizeUnit="inch"}else{sizeUnit="cm"}let selectedAttr={};let pointCode;for(let i=0;i<$size_charts[relatedAttr][attrValue].length;i++){pointCode=$size_charts[relatedAttr][attrValue][i]["point_code"];if(pointCode==="height"){if(sizeUnit==="inch"){const{feet:feet,inches:inches}=parseHeight($size_charts[relatedAttr][attrValue][i]["ft"]);$("#feet").val(feet);$("#inches").val(inches)}else{$("#cm").val($size_charts[relatedAttr][attrValue][i][sizeUnit])}}else{selectedAttr[pointCode]=$size_charts[relatedAttr][attrValue][i][sizeUnit]}}const $inputs=$(`#${relatedAttr}-custom-form-container input.custom-input-js`);$inputs.each(function(){const name=$(this).attr("name");if(selectedAttr[name]){$(this).val(selectedAttr[name])}})}function calculateProductPrice(productInfo){let totalPrice=parseFloat(ecommerce_product.price);if(productInfo["spu_attr"]&&typeof productInfo["spu_attr"]==="object"&&productInfo["spu_attr"]!==null){for(let key in productInfo["spu_attr"]){if(productInfo["spu_attr"][key].value_price>0){totalPrice+=parseFloat(productInfo["spu_attr"][key].value_price)}}}if(productInfo["custom_attr"]&&typeof productInfo["custom_attr"]==="object"&&productInfo["custom_attr"]!==null){for(let key in productInfo["custom_attr"]){if(productInfo["custom_attr"][key].value_price>0){totalPrice+=parseFloat(productInfo["custom_attr"][key].value_price)}}}totalPrice=totalPrice.toFixed(2);product_info.price=totalPrice;return totalPrice}function checkCustomInfo($input){const value=$input.val();const required=$input.prop("required");if(required&&(value===""||value===0)){return false}const min=parseFloat($input.attr("min"));if(!isNaN(min)&&value<min){return false}const max=parseFloat($input.attr("max"));if(!isNaN(max)&&value>max){return false}return true}function getSpuAttrValueInfo(attr,attrValue){const attrValueInfo={attr_code:attr,value_code:attrValue,attr_name:$sku_map[attr].attr_name,value_name:$sku_map[attr]["values"][attrValue].value_name,value_price:$sku_map[attr]["values"][attrValue].value_price,base_value_price:$sku_map[attr]["values"][attrValue].base_value_price};return attrValueInfo}function getCustomAttrValueInfo(attr,attrValue,value_price,base_value_price){let value_code,value_name;if(!attrValue){value_code="";value_name=""}else{value_code=attrValue;value_name=$sku_map[attr]["values"][attrValue].value_name}const attrValueInfo={attr_code:attr,value_code:value_code,attr_name:$sku_map[attr].attr_name,value_name:value_name,value_price:value_price,base_value_price:base_value_price};return attrValueInfo}function setProductSpuAttr(attr,attrValue,options){const attrValueInfo=getSpuAttrValueInfo(attr,attrValue);const newSpuAttr={...product_info.spu_attr,[attr]:attrValueInfo};if(product_info.custom_attr&&product_info.custom_attr.hasOwnProperty(attr)){delete product_info.custom_attr[attr]}const updates={spu_attr:newSpuAttr};if(options&&options.attrImg){updates.image=options.imgSrc}updateProductInfo(updates)}function setProductCustomAttr(attr,attrValue,value_price,base_value_price){const attrValueInfo=getCustomAttrValueInfo(attr,attrValue,value_price,base_value_price);const newCustomAttr={...product_info.custom_attr,[attr]:attrValueInfo};if(product_info.spu_attr&&product_info.spu_attr.hasOwnProperty(attr)){delete product_info.spu_attr[attr]}updateProductInfo({custom_attr:newCustomAttr})}function switchToSpuAttr(attr,attrValue){if(product_info.custom_attr&&product_info.custom_attr.hasOwnProperty(attr)){delete product_info.custom_attr[attr]}if(attrValue){setProductSpuAttr(attr,attrValue)}}function setProductImage(img_src){var filename=img_src.split("/").splice(-1).toString();product_info["image"]=img_src;updateProductInfo({image:img_src})}function initProductAttr(){product_info["name"]=ecommerce_product.name;product_info["price"]=ecommerce_product.price;product_info["image"]=$("#product-main-image-js").val();product_info["product_id"]=ecommerce_product.id;product_info["spu"]=ecommerce_product.spu;product_info["qty"]=1;product_info["spu_attr"]={};product_info["custom_attr"]={};for(let index=0;index<$selected_sku_list.length;index++){const attr=$selected_sku_list[index].attr_code;const attrValue=$selected_sku_list[index].value_code;setProductSpuAttr(attr,attrValue)}}function getFilenameFromImgSrc(imgSrc){const filename=imgSrc.split("/").splice(-1).toString();return filename}function getIndexByImgSrc(imgSrc){let index=-1;$(".swiper-slide img").each(function(i,element){const currentImgSrc=$(this).data("src");const filename=getFilenameFromImgSrc(currentImgSrc);if(filename===getFilenameFromImgSrc(imgSrc)){index=i;return}});return index}function goToSlide(index,speed=null){swiper.slideTo(index,speed,false)}function updateProductInfo(updates){const keys=Object.keys(updates);for(let index=0;index<keys.length;index++){const key=keys[index];if(key==="image"){const imgSrc=updates[key];const index=getIndexByImgSrc(imgSrc);goToSlide(index)}}Object.assign(product_info,updates);$(document).trigger("product:updated",[product_info])}function renderProductUI(info){const price=calculateProductPrice(info);$("#total-price").text(`${ecommerce_product.symbol}${price}`)}function showAttrErrorMessage(attr){$(`#${attr}-error-message`).addClass("d-block")}function hideAttrErrorMessage(attr){$(`#${attr}-error-message`).removeClass("d-block")}function isAllRequiredAttrsSelected(requiredAttrs=$spu_attr){return requiredAttrs.every(attr=>product_info.spu_attr[attr]||product_info.custom_attr[attr])}function getProductInfo(){var result={success:false,data:{name:product_info.name,product_id:product_info.product_id,spu:product_info.spu,qty:product_info.qty,image:product_info.image,price:product_info.price,spu_attr:[],size_chart:{},custom_attr:[]},errors:[]};var $selected_size_charts={};for(var index=0;index<$spu_attr.length;index++){var errror={type:null,key:null,jQueryElement:null};var attr=$spu_attr[index];if(product_info.spu_attr&&typeof product_info.spu_attr==="object"&&product_info.spu_attr!==null&&product_info.spu_attr[attr]&&typeof product_info.spu_attr[attr]==="object"&&product_info.spu_attr[attr]!==null){result.data.spu_attr.push(product_info.spu_attr[attr]);var value_code=product_info.spu_attr[attr].value_code;if($size_charts.hasOwnProperty(attr)&&$size_charts[attr].hasOwnProperty(value_code)){$selected_size_charts[attr]=$size_charts[attr][value_code]}}else if(product_info.custom_attr&&typeof product_info.custom_attr==="object"&&product_info.custom_attr!==null&&product_info.custom_attr[attr]&&typeof product_info.custom_attr[attr]==="object"&&product_info.custom_attr[attr]!==null){product_info.custom_attr[attr].list=[];cusResult=collectCustomMeasurements(attr);if(cusResult.errors.length>0){errror.type="custom_attr";errror.jQueryElement=cusResult.errors[0];result.errors.push(errror);return result}else{cusResult.data.forEach(function(item){product_info.custom_attr[attr].list.push(item)})}result.data.custom_attr.push(product_info.custom_attr[attr])}else{errror.type="spu_attr";errror.key=attr;errror.jQueryElement=$(`#${attr}`);result.errors.push(errror);return result}}if(Object.keys($selected_size_charts).length>0){product_info.size_chart=$selected_size_charts;result.data.size_chart=product_info.size_chart}result.success=true;return result}function renderErrorMsg(err){scrollToElement(err.jQueryElement);if(err.type==="spu_attr"){showAttrErrorMessage(err.key)}else if(err.type==="custom_attr"){err.jQueryElement.addClass("is-invalid");err.jQueryElement.focus()}}function collectCustomMeasurements(attr){var result={success:true,data:[],errors:[]};var $container=$("#"+attr+"-custom-form-container");$container.find("div.input-group").each(function(){var $group=$(this);if(!$group.is(":visible")){return true}var $input=$group.find("input").first();if(!checkCustomInfo($input)){result.success=false;result.errors.push($input);return false}var name=$input.attr("name");var $labelSpan=$group.find(".measurements-label-js");var measurements_name=$labelSpan.length?$labelSpan.text().trim():"Unknown";if(name==="feet"){var feet=$input.val();var $inchesEle=$group.find("#inches");if(!checkCustomInfo($inchesEle)){result.success=false;result.errors.push($inchesEle);return false}var inches=$inchesEle.val();if(feet!==""&&inches!==""){var measurements_code=$group.data("measurements-code");result.data.push({measurements_code:measurements_code,measurements_name:measurements_name,value_with_unit:feet+"'"+inches+'"'})}}else{var value=$input.val();if(value!==""){var measurements_code=name;var $unitSpan=$group.find(".custom-input-unit-js");var unit=$unitSpan.length?$unitSpan.text().trim():"";result.data.push({measurements_code:measurements_code,measurements_name:measurements_name,value_with_unit:value+" "+unit})}}});return result}function init_share(){var ogUrl=$('meta[property="og:url"]').attr("content");var ogTitle=$('meta[property="og:title"]').attr("content");var elems=$("[data-sharer]");for(var i=0;i<elems.length;i++){elems[i].setAttribute("data-url",ogUrl);elems[i].setAttribute("data-title",ogTitle)}$("#affiliate-link-url-input-js").val(ogUrl)}function handleFavoriteClickThrottle(e){e.preventDefault();var self=$(this);$.ajax({url:productFavoriteUrl,method:"GET",data:{spu:ecommerce_product.spu},dataType:"json",timeout:5e3}).done(function(response){loginStatus=response.loginStatus;if(!loginStatus){window.location.href=memberLoginUrl;return}if(response.favoriteStatus){self.addClass("text-danger")}else{self.removeClass("text-danger")}showToast(response.content,"#toast-js")}).fail(function(){alert("Operation failed. Please try again later.")}).always(function(){})}function handleFavoriteClickA(e){e.preventDefault();e.stopPropagation();var self=$(this);if(self.prop("disabled")){return}self.prop("disabled",true);self.addClass("opacity-50");$.ajax({url:productFavoriteUrl,method:"GET",data:{spu:ecommerce_product.spu},dataType:"json",timeout:5e3}).done(function(response){loginStatus=response.loginStatus;if(!loginStatus){window.location.href=memberLoginUrl;return}if(response.favoriteStatus){self.addClass("text-danger")}else{self.removeClass("text-danger")}showToast(response.content,"#toast-js")}).fail(function(){alert("Operation failed. Please try again later.")}).always(function(){self.prop("disabled",false);self.removeClass("opacity-50")})}function handleFavoriteClickB(e){e.preventDefault();e.stopPropagation();var self=$(this);self.toggleClass("text-danger");$.ajax({url:productFavoriteUrl,method:"GET",data:{spu:ecommerce_product.spu},dataType:"json",timeout:5e3}).done(function(response){loginStatus=response.loginStatus;if(!loginStatus){window.location.href=memberLoginUrl;return}if(response.favoriteStatus){self.addClass("text-danger")}else{self.removeClass("text-danger")}showToast(response.content,"#toast-js")}).fail(function(){self.toggleClass("text-danger");showToast("Operation failed","#toast-js")}).always(function(){})}function checkRemark(customer_remark){if(customer_remark.length>order_remark_max_length){return false}return true}function handleAddToCartClick(e){e.preventDefault();e.stopPropagation();var self=$(this);if(self.prop("disabled")){return}self.prop("disabled",true);self.addClass("opacity-50");var result=getProductInfo();if(!result.success){self.prop("disabled",false);self.removeClass("opacity-50");showToast("Failed to obtain product information. Please refresh and try again.","#toast-js");return}var remark=$("#customer-remark-js").val();if(!checkRemark(remark)){self.prop("disabled",false);self.removeClass("opacity-50");showToast(order_remark_message,"#toast-js")}var data_params=result.data;data_params["customer_remark"]=remark;$.ajax({async:true,timeout:6e3,dataType:"json",type:"post",data:JSON.stringify(data_params),url:addToCartUrl,success:function(response){if(response.status=="success"){var items_count=response.items_count;$(".cart-item-count-js").text(items_count);var $modal=$("#productBottomSheet");var modalInstance=bootstrap.Modal.getOrCreateInstance($modal[0]);modalInstance.hide()}showToast(response.message,"#toast-js")},error:function(XMLHttpRequest,textStatus,errorThrown){let message="Operation failed. Please try again later.";if(textStatus==="timeout"){message="Request timed out. Please check your network and try again."}else if(XMLHttpRequest.status===0){message="Network connection failed. Please check your internet."}else if(XMLHttpRequest.status===401){window.location.href=memberLoginUrl;return}else if(XMLHttpRequest.status>=500){message="Server is busy. Please try again later."}else if(XMLHttpRequest.status>=400){message="Invalid request. Please try again."}else{console.error("AJAX Error:",textStatus,errorThrown)}console.log(message)},complete:function(){self.prop("disabled",false);self.removeClass("opacity-50")}})}function paypalBuynowCreatePayment(){var FUNDING_SOURCES=[paypal.FUNDING.PAYPAL];FUNDING_SOURCES.forEach(function(fundingSource){var button=paypal.Buttons({fundingSource:fundingSource,style:{label:"buynow"},onClick:function(){var remark=$("#customer-remark-js").val();if(!checkRemark(remark)){self.prop("disabled",false);self.removeClass("opacity-50");showToast(order_remark_message,"#toast-js");return false}return true},createOrder:(data,actions)=>{var result=getProductInfo();var data_params=result.data;data_params["customer_remark"]=$("#customer-remark-js").val();return fetch(paypalCreateOrderUrl,{method:"post",body:JSON.stringify(data_params),headers:{"content-type":"application/json"}}).then(response=>{if(!response.ok){throw new Error("Network response was not ok")}return response.json()}).then(order=>{if(order.id=="-1"){throw new Error(order.message)}return order.id}).catch(error=>{alert(error)})},onApprove:(data,actions)=>fetch(paypalCaptureOrderUrl,{method:"post",body:JSON.stringify(data),headers:{"content-type":"application/json"}}).then(response=>{if(!response.ok){throw new Error("Network response was not ok!")}return response.json()}).then(orderData=>{if(orderData.order_sn=="-1"){if(orderData.error_issue==="INSTRUMENT_DECLINED"){alert(orderData.message);return actions.restart()}else{throw new Error(orderData.message)}}const order_sn=orderData.order_sn;actions.redirect(`${paypalFinishOrderUrl}?order_sn=${order_sn}`)}).catch(error=>{alert(error)})});if(button.isEligible()){button.render("#product-paypal-container-js")}})}$(function(){const lazyLoadInstance=new LazyLoad({});$(document).on("product:updated",(e,info)=>{renderProductUI(info)});swiper=new Swiper(".swiper",{autoplay:{delay:5e3},pagination:{el:".swiper-pagination",type:"fraction",renderFraction:function(currentClass,totalClass){return'<span class="swiper-pagination-current">'+currentClass+'</span> / <span class="swiper-pagination-total">'+totalClass+"</span>"}}});initProductAttr();fetchAndDisplayViewedProducts(historyUrl);saveProductToLocalStorage(ecommerce_product.spu);if(products_more_count>products_more_count_min){$("#product-list-more").infiniteScroll({path:function(){if(this.loadCount<products_more_max_page-1){return UrlUtils.mergeParams(productsMoreUrl,{p:this.loadCount+1})}},append:false,history:false,responseBody:"json",fetchOptions:{method:"GET",headers:{"X-Requested-With":"XMLHttpRequest","Content-Type":"application/json",Accept:"application/json"}},checkLastPage:true,scrollThreshold:100,status:".page-load-status",prefill:false,debug:false});$("#product-list-more").on("load.infiniteScroll",function(event,body,path){if(body&&body.html&&body.html.trim()!==""){$(this).append(body.html);if(lazyLoadInstance){lazyLoadInstance.update()}}});$("#product-list-more").on("error.infiniteScroll",function(event,error,path){alert("Failed to load more products.")});$("#product-list-more").on("append.infiniteScroll",function(event,body,path,items){});$("#product-list-more").on("last.infiniteScroll",function(){})}$("#panelsStayOpen-sizeChart").on("show.bs.collapse",function(){if(!$(this).data("rendered")){renderSizeChartEle();$(this).data("rendered",true)}});let currentUnit=default_size_unit;function switchSizeUnit(unit){currentUnit=unit;const activeTabContentPrefix=$("#sizeTabs .nav-link.active").data("content-prefix");const contentId=activeTabContentPrefix+unit;$("#"+contentId).addClass("show active").siblings(".tab-pane").removeClass("show active");if(unit===default_size_unit){$("#switchToDefault-js").addClass("btn-danger").removeClass("btn-secondary");$("#switchToSecond-js").addClass("btn-secondary").removeClass("btn-danger")}else{$("#switchToSecond-js").addClass("btn-danger").removeClass("btn-secondary");$("#switchToDefault-js").addClass("btn-secondary").removeClass("btn-danger")}}$("#switchToDefault-js").on("click",function(){switchSizeUnit(default_size_unit)});$("#switchToSecond-js").on("click",function(){switchSizeUnit(second_size_unit)});$("#sizeTabs .nav-link").on("shown.bs.tab",function(){switchSizeUnit(currentUnit)});$("#affiliate-link-url-copy-js").on("click",function(e){e.preventDefault();var $this=$(this);$("#affiliate-link-url-input-js").select();document.execCommand("copy");$this.find(".affiliate-link-url-copy-label-js").addClass("d-none");$this.find(".affiliate-link-url-copy-label-copied-js").removeClass("d-none");setTimeout(function(){$this.find(".affiliate-link-url-copy-label-js").removeClass("d-none");$this.find(".affiliate-link-url-copy-label-copied-js").addClass("d-none")},2e3)});$(".product-info-attr-js").on("click",".attr-value-js button",function(e){e.preventDefault();const self=$(this);const $fieldset=self.closest("fieldset");const attr=$fieldset.attr("id");const attrValue=self.data("attr-value");self.closest("div").find("button").removeClass("border-danger");self.removeClass("border-light");self.addClass("border-danger");hideAttrErrorMessage(attr);$fieldset.find(".product-selected-attr-value-js").data("value",attrValue).data("value-for-restore",attrValue).text($sku_map[attr]["values"][attrValue].value_name);const attrHasPrice=$sku_map[attr].attr_has_price;const attrImg=self.data("attr-img");const options={attrHasPrice:attrHasPrice,attrImg:attrImg};if(attrImg===1){var img_src=self.find("img").attr("src");options.imgSrc=img_src}setProductSpuAttr(attr,attrValue,options);const showSizeChart=$sku_map[attr].show_size_value_chart;if(showSizeChart===1){const $chartContainer=$fieldset.find(".product-selected-chart-js");const $chartBody=$chartContainer.find("tbody");if($size_charts[attr][attrValue]){let rows="";$.each($size_charts[attr][attrValue],function(index,detail){const imperialValue=detail.ft?detail.ft:detail.inch?detail.inch+" in":"";const row=`\n <tr>\n <td>${detail.attr_name}</td>\n <td>${imperialValue}</td>\n <td>${detail.cm} cm</td>\n </tr>`;rows+=row});$chartBody.html(rows);$chartContainer.removeClass("d-none")}}const showSizeCustom=$sku_map[attr].show_size_custom;if(showSizeCustom===1){const $customCheckbox=$fieldset.find(".custom-toggle-checkbox-js");if($customCheckbox.is(":checked")){$customCheckbox.prop("checked",false).trigger("change")}}});$(".product-info-attr-js").on("change",".custom-toggle-checkbox-js",function(){const self=$(this);const customPrice=self.data("custom_price");const baseCustomPrice=self.data("base-custom-price");const $fieldset=self.closest("fieldset");const targetFormId=self.attr("aria-controls");const isChecked=self.is(":checked");$("#"+targetFormId).toggleClass("d-none",!isChecked).attr("aria-hidden",!isChecked);self.attr("aria-expanded",isChecked);const relatedAttr=$fieldset.attr("id");const relatedAttrValue=$fieldset.find(".product-selected-attr-value-js").data("value-for-restore");if(isChecked){$fieldset.find(".d-flex button").removeClass("border-danger");$fieldset.find(".product-selected-attr-value-js").data("value","").text("");hideAttrErrorMessage(relatedAttr);if(relatedAttrValue){const size_unit=$("#"+targetFormId).find(".unit-selector-js").val();initCustomize(relatedAttr,size_unit,relatedAttrValue)}$fieldset.find(".product-selected-chart-js").addClass("d-none");setProductCustomAttr(relatedAttr,relatedAttrValue,customPrice,baseCustomPrice)}else{$fieldset.find(".d-flex button").each(function(){if($(this).data("attr-value")==relatedAttrValue){$(this).removeClass("border-light");$(this).addClass("border-danger")}});if(relatedAttrValue){$fieldset.find(".product-selected-attr-value-js").data("value",relatedAttrValue).data("value-for-restore",relatedAttrValue).text($sku_map[relatedAttr]["values"][relatedAttrValue].value_name)}$fieldset.find(".product-selected-chart-js").removeClass("d-none");switchToSpuAttr(relatedAttr,relatedAttrValue)}});$(".product-info-attr-js").on("change",".unit-selector-js",function(){const $this=$(this);const sizeUnit=$this.val();const $fieldset=$this.closest("fieldset");const relatedAttr=$fieldset.attr("id");const relatedAttrValue=$fieldset.find(".product-selected-attr-value-js").data("value-for-restore");const imperialHeight=$("#imperial-height");const metricHeight=$("#metric-height");const weightUnitLabel=$("#weight-unit-label");const $cus_units=$fieldset.find(".custom-input-unit-js");if(sizeUnit==="imperial"){if(imperialHeight){imperialHeight.removeClass("d-none");metricHeight.addClass("d-none");weightUnitLabel.text("lb")}$cus_units.each(function(){$(this).text("in")})}else{if(imperialHeight){imperialHeight.addClass("d-none");metricHeight.removeClass("d-none");weightUnitLabel.text("kg")}$cus_units.each(function(){$(this).text("cm")})}if(relatedAttrValue){initCustomize(relatedAttr,sizeUnit,relatedAttrValue)}});$(".product-info-attr-js").on("focus",".custom-form-container-js input",function(){$(this).removeClass("is-invalid")}).on("blur",".custom-form-container-js input",function(){if(!checkCustomInfo($(this))){$(this).addClass("is-invalid")}});$("#qty-minus-js").click(function(){let v=parseInt($("#quantity").val());v-=1;if(v<=1){v=1}$("#quantity").val(v);product_info.qty=v;if(v<=1){$(this).addClass("disabled")}else{$(this).removeClass("disabled")}});$("#qty-plus-js").click(function(){let v=parseInt($("#quantity").val());v+=1;if(v>=100){v=100}$("#quantity").val(v);product_info.qty=v;$("#qty-minus-js").removeClass("disabled")});$("#product-detail-icon-share-js").click(function(e){e.preventDefault();init_share();var $modal=$("#shareBottomSheet");var modalInstance=new bootstrap.Modal($modal[0]);modalInstance.show()});$("#shareBottomSheet").on("hidden.bs.modal",function(){});$(".product-info-attr-js").on("click","button.measurement-trigger-js",function(e){e.preventDefault();var code=$(this).data("measurements-code");var name=$size_custom_image[code]["local_img_title"];$("#measurementBottomSheetModalLabel").text(name);const imagePath=$size_custom_image[code]["local_img"];if(imagePath){$("#modalImage").attr("src",imagePath)}const htmlContent=$size_custom_image[code]["local_img_desc"];if(htmlContent){$("#modalHtml").html(htmlContent)}var trigger=code;var $modal=$("#measurementBottomSheet");$modal.data("trigger-source",trigger);console.log("this modal is triggered by:",trigger);var modalInstance=new bootstrap.Modal($modal[0]);modalInstance.show()});$("#measurementBottomSheet").on("hidden.bs.modal",function(){var triggerSource=$(this).data("trigger-source");console.log("this modal is triggered by:",triggerSource,"and it is hidden");$(this).removeData("trigger-source")});$("#product-favorite-js").click(handleFavoriteClickA);$(".product-view-js").on("click","button",function(e){e.preventDefault();var result=getProductInfo();if(!result.success){renderErrorMsg(result.errors[0]);return false}loadProductDetail(result.data);var trigger=$(this).data("trigger");$("#productBottomSheetModalLabel").text($(this).text());if(trigger=="product-add-cart-view-js"){$("#product-add-cart-js").removeClass("d-none");$("#product-paypal-container-js").addClass("d-none")}else if(trigger=="product-buy-now-view-js"){if(typeof paypal=="undefined"){webLoadScript(paypalSdkUrl,function(){paypalBuynowCreatePayment()})}else{paypalBuynowCreatePayment()}$("#product-add-cart-js").addClass("d-none");$("#product-paypal-container-js").removeClass("d-none")}var $modal=$("#productBottomSheet");$modal.data("trigger-source",trigger);console.log("该 modal 是由:",trigger,"触发的");var modalInstance=bootstrap.Modal.getOrCreateInstance($modal[0]);modalInstance.show()});$("#productBottomSheet").on("hidden.bs.modal",function(){var triggerSource=$(this).data("trigger-source");console.log("this modal is triggered by:",triggerSource,"and it is hidden");if(triggerSource==="product-buy-now-view-js"){$("#paypal-button-container").empty()}$(this).removeData("trigger-source")});$("#product-add-cart-js").click(handleAddToCartClick);$("#customer-remark-js").on("focus",function(){$(this).removeClass("is-invalid")}).on("blur",function(){if(!checkRemark($(this).val())){$(this).addClass("is-invalid");showToast(order_remark_message,"#toast-js")}})});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function renderSearchHistory(){let searchHistory=getCompatibleSearchHistoryFromLocalStorage();if(searchHistory.data.length===0){return}const $searchHistoryList=$("#search-history-items-js");searchHistory.data.forEach(function(keyword){const $listItem=$("<li>",{class:"q-js py-2 px-2",text:keyword});$searchHistoryList.append($listItem)});$("#search-history-js").removeClass("d-none")}$(document).ready(function(){pullSearchHistory(pullSearchHistoryUrl);renderSearchHistory();$("#removeDialog .btn-primary").click(function(){removeSearchFromLocalStorage();removeHistory(removeHistoryUrl);location.reload()});const $input=$("#q");const $btnClearContainer=$("#btn-clear-container-js");const $btnContainer=$("#btn-container-js");$input.on("input focus",function(){const q=$(this).val().trim();if(q.length>0){$btnClearContainer.removeClass("d-none");$btnContainer.addClass("d-none")}else{$btnClearContainer.addClass("d-none");$btnContainer.removeClass("d-none")}});$btnClearContainer.on("click",function(){$input.val("").focus();$(this).addClass("d-none");$btnContainer.removeClass("d-none")});$("#searchForm").on("submit",function(e){if(!$input.val().trim()){e.preventDefault();$input.focus();return false}});$(".q-js").click(function(){const search_text=$(this).text();$("#q").val(search_text);$("#searchForm").submit()})});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function resetUrl(){return UrlUtils.mergeParams(base_search_url,{...url_params,p:pageNum})}$(document).ready(function(){const lazyLoadInstance=new LazyLoad({});const params=UrlUtils.getCurrentParams();const q=params.get("q");const p=params.get("p");if(q){if(!p||p==1){saveSearchToLocalStorage(q);saveOneSearchHistory(q,saveSearchHistoryUrl)}}$(document).on("click","#filter-reset-js",function(){window.location.href=search_url});$(document).on("click","#apply-filter-js",function(){var params={};params["q"]=url_params["q"];var begin=$("#filter-price-min-js").val().trim();var end=$("#filter-price-max-js").val().trim();var priceValid=val=>{let n=parseFloat(val);return!isNaN(n)&&n>=0};if(begin&&priceValid(begin)||end&&priceValid(end)){let min=begin&&priceValid(begin)?parseFloat(begin):0;let max=end&&priceValid(end)?parseFloat(end):0;params["price"]=min+"-"+max}$(".filter-attr-js").each(function(){var attrCode=$(this).data("attr-code");var selectedIds=[];$(this).find(".filter-value-item-js.active").each(function(){selectedIds.push($(this).data("value-id"))});if(selectedIds.length>0){params[attrCode]=selectedIds.join(",")}});const finalUrl=UrlUtils.mergeParams(base_search_url,params);window.location.href=finalUrl});$(document).on("click",".filter-value-item-js",function(){var $item=$(this);var parent=$item.parent();if($item.hasClass("active")){$item.removeClass("active bg-primary text-white")}else{parent.find(".filter-value-item-js").removeClass("active bg-primary text-white");$item.addClass("active bg-primary text-white")}});$("#product-list-more").infiniteScroll({path:function(){if(this.loadCount<maxPage-1){return UrlUtils.mergeParams(base_search_url,{...url_params,p:this.loadCount+2})}},append:false,history:false,responseBody:"json",fetchOptions:{method:"GET",headers:{"X-Requested-With":"XMLHttpRequest","Content-Type":"application/json",Accept:"application/json"}},checkLastPage:true,scrollThreshold:100,status:".page-load-status",prefill:false,debug:false});$("#product-list-more").on("load.infiniteScroll",function(event,body,path){if(body&&body.html&&body.html.trim()!==""){$(this).append(body.html);if(lazyLoadInstance){lazyLoadInstance.update()}}});$("#product-list-more").on("error.infiniteScroll",function(event,error,path){alert("Failed to load more products.")});$("#product-list-more").on("append.infiniteScroll",function(event,body,path,items){});$("#product-list-more").on("last.infiniteScroll",function(){})});
|
package/package.json
CHANGED
package/readme.txt
CHANGED
|
@@ -11,7 +11,8 @@ terser 负责压缩js
|
|
|
11
11
|
terser src/js/js.js -o dist/js/js.min.js
|
|
12
12
|
terser src/js/product.js -o dist/js/product.min.js
|
|
13
13
|
terser src/js/category.js -o dist/js/category.min.js
|
|
14
|
-
|
|
14
|
+
terser src/js/search.js -o dist/js/search.min.js
|
|
15
|
+
terser src/js/search-text.js -o dist/js/search-text.min.js
|
|
15
16
|
-----------
|
|
16
17
|
// load any GitHub release, commit, or branch
|
|
17
18
|
// note: we recommend using npm for projects that support it
|