Repair Cost Estimator
Get a quick cost estimate for your repair before booking a service appointment.
${this.options
.map(
(option) =>
`${option.text} `
)
.join("")}
`;
this.select2Container = container.querySelector(".select2-container");
this.select2Selection =
this.select2Container.querySelector(".select2-selection");
this.select2Dropdown =
this.select2Container.querySelector(".select2-dropdown");
this.select2ResultsOptions = this.select2Container.querySelectorAll(
".select2-results__option"
);
this.select2Rendered = this.select2Container.querySelector(
".select2-selection__rendered"
);
this.select2Selection.addEventListener("click", (e) => {
e.stopPropagation();
this.toggleDropdown();
});
this.select2ResultsOptions.forEach((option) => {
option.addEventListener("click", (e) => {
const selectedValue = e.target.getAttribute("data-value");
this.setValue(selectedValue);
});
});
document.addEventListener("click", (e) => {
if (!this.select2Container.contains(e.target)) {
this.select2Dropdown.classList.remove("show");
this.select2Selection.classList.remove("rotate-arrow");
}
});
}
toggleDropdown() {
document.querySelectorAll(".select2-dropdown").forEach((dropdown) => {
if (dropdown !== this.select2Dropdown) {
dropdown.classList.remove("show");
}
});
this.select2Dropdown.classList.toggle("show");
this.select2Selection.classList.toggle("rotate-arrow");
}
setValue(value) {
const option = Array.from(this.select2ResultsOptions).find(
(option) => option.getAttribute("data-value") === value
);
if (option) {
this.selectedValue = value;
this.selectedText = option.textContent;
this.select2Rendered.textContent = this.selectedText;
this.select2ResultsOptions.forEach((option) => {
option.classList.remove("select2-results__option--selected");
});
option.classList.add("select2-results__option--selected");
this.select2Dropdown.classList.remove("show");
this.select2Selection.classList.remove("rotate-arrow");
if (this.onChangeCallback) {
this.onChangeCallback(value);
}
}
}
setValueWithoutCallBack(value) {
const option = Array.from(this.select2ResultsOptions).find(
(option) => option.getAttribute("data-value") === value
);
if (option) {
this.selectedValue = value;
this.selectedText = option.textContent;
this.select2Rendered.textContent = this.selectedText;
this.select2ResultsOptions.forEach((option) => {
option.classList.remove("select2-results__option--selected");
});
option.classList.add("select2-results__option--selected");
this.select2Dropdown.classList.remove("show");
this.select2Selection.classList.remove("rotate-arrow");
}
}
getValue() {
return this.selectedValue ?? "";
}
getSelectedText() {
return this.selectedText ?? "";
}
clearOptions() {
this.options = [];
this.selectedValue = null;
this.selectedText = null;
this.select2Rendered.textContent = this.placeholder;
this.updateOptions();
}
replaceOptions(newOptions) {
this.options = newOptions;
this.selectedValue = null;
this.selectedText = null;
this.select2Rendered.textContent = this.placeholder;
this.updateOptions();
}
resetValue() {
this.selectedValue = null;
this.selectedText = null;
this.select2Rendered.textContent = this.placeholder;
this.select2ResultsOptions.forEach((option) => {
option.classList.remove("select2-results__option--selected");
});
if (this.onChangeCallback) {
this.onChangeCallback(null);
}
}
updateOptions() {
const optionsContainer =
this.select2Container.querySelector(".select2-results");
optionsContainer.innerHTML = this.options
.map(
(option) =>
`
${option.text} `
)
.join("");
this.select2ResultsOptions = this.select2Container.querySelectorAll(
".select2-results__option"
);
this.select2ResultsOptions.forEach((option) => {
option.addEventListener("click", (e) => {
const selectedValue = e.target.getAttribute("data-value");
this.setValue(selectedValue);
});
});
}
}
// Example usage:
// const dropdown1 = new Select2Component('dropdown1', [
// { value: 'option1', text: 'Option 1' },
// { value: 'option2', text: 'Option 2' },
// { value: 'option3', text: 'Option 3' }
// ]);
//Configuration
const CategoriesDisplay = [
/*{
id: 1,
name: 'Smartphones'
},{
id: 2,
name: 'TVs'
}*/
];
// Search UI
const resultsBox = $(".result-box");
const inputBox = $("#input-box");
const resetIcon = $("#reset-icon");
let productIdSeleted = 0;
//Handle change dropdown
const onCategoryChange = async (value) => {
if (value === null) return;
dropdownProductChange();
checkDisableReset();
setInputValue("");
const data = await fetch(
`${API_URL}/api/series?subcategoryId=${value}`
);
const series = await data.json();
seriesDropdown.replaceOptions(
series.map((e) => {
return {
value: e.id,
text: e.name,
};
})
);
modelCodeDropdown.clearOptions();
showSymptom([]);
isSymptomDisable(true);
checkHideDropdownErrors();
};
const displayCTAButton = ()=>{
const ctaDom = document.querySelector(".estimated-cost-cta")
if(isDisplayCTAButton){
ctaDom.style.display = 'block';
}else{
ctaDom.style.display = 'none';
}
}
const onSeriesChange = async (value) => {
dropdownProductChange();
checkDisableReset();
setInputValue("");
const data = await fetch(`${API_URL}/api/products?serieId=${value}`);
const models = await data.json();
modelCodeDropdown.replaceOptions(
models.map((e) => {
return {
value: e.id,
text: e.name + " | " + e.modelCode,
};
})
);
showSymptom([]);
isSymptomDisable(true);
checkHideDropdownErrors();
};
const onModelChange = async (value) => {
dropdownProductChange();
inputSearchChange();
checkDisableReset();
const data = await fetch(`${API_URL}/api/symptoms?productId=${value}`);
const symptoms = await data.json();
const selectBox = document.querySelector("#model-code");
const searchInputDom = modelCodeDropdown.getSelectedText();
setInputValue(searchInputDom);
if (
searchInputDom.length !== 0 &&
searchInputDom.split("|").length === 2
) {
showSymptom(symptoms);
document.querySelector(".symptom-title").classList.remove("disable");
//set attribute for button
const estimateButton = document.querySelector("#get-estimate");
//replaced value model
const modelCode = searchInputDom.split("|")[1];
estimateButton.setAttribute(
"data-omni",
`sg:support sparepartestimator:${modelCode.trim()}_getestimate`
);
estimateButton.setAttribute(
"ga-la",
`sparepartestimator:${modelCode.trim()}_getestimate`
);
isSymptomDisable(false);
checkHideDropdownErrors();
}
};
//Initial all dropdow
const categoryDropdown = new Select2Component(
"sub-category",
[],
onCategoryChange,
globalContentJson?.category?.content
);
const seriesDropdown = new Select2Component(
"series",
[],
onSeriesChange,
globalContentJson?.series?.content
);
const modelCodeDropdown = new Select2Component(
"model-code",
[],
onModelChange,
globalContentJson?.model?.content
);
const updateDropdownTitle = (contentJson) =>{
categoryDropdown.updatePlaceholder(contentJson?.category.content);
seriesDropdown.updatePlaceholder(contentJson?.series.content);
modelCodeDropdown.updatePlaceholder(contentJson?.model.content);
}
// changing color of categories:
$("#sub-category")
.on("mouseenter", "option", function () {
$(this).addClass("hover-option");
})
.on("mouseleave", "option", function () {
$(this).removeClass("hover-option");
});
//Action validation when click button get estimate
const inputSearchValidation = () => {
const inputValue = $("#input-box").val();
const subCategory = $("#sub-category").val();
if (inputValue.length === 0 && subCategory.length === 0) {
$("#input-product-info").show();
return false;
} else {
$("#input-product-info").hide();
return true;
}
};
const clearDropdownOption = () => {
categoryDropdown.resetValue();
seriesDropdown.clearOptions();
modelCodeDropdown.clearOptions();
};
const changeSearchValue = async (product) => {
categoryDropdown.setValueWithoutCallBack(product.subCategoriesId);
await setValueForSeries(product.seriesId, product.subCategoriesId);
await setModelCode(product.seriesId, product.productId);
};
const setValueForSeries = async (seriesId, subCategoriesId) => {
const data = await fetch(
`${API_URL}/api/series?subcategoryId=${subCategoriesId}`
);
const series = await data.json();
seriesDropdown.replaceOptions(
series.map((e) => {
return {
value: e.id,
text: e.name,
};
})
);
seriesDropdown.setValueWithoutCallBack(seriesId);
// showSeries(series);
// document.querySelector("#series").value = seriesId;
};
const setModelCode = async (seriesId, productId) => {
const data = await fetch(`${API_URL}/api/products?serieId=${seriesId}`);
const models = await data.json();
modelCodeDropdown.replaceOptions(
models.map((e) => {
return {
value: e.id,
text: e.name + " | " + e.modelCode,
};
})
);
modelCodeDropdown.setValueWithoutCallBack(productId);
// showModel(model);
// document.querySelector("#model-code").value = productId;
};
const dropdownInfoValidation = () => {
const inputValue = $("#input-box").val();
const subCategory = categoryDropdown.getValue() ?? "";
const series = seriesDropdown.getValue() ?? "";
const modelCode = modelCodeDropdown.getValue() ?? "";
let validInput = true;
if (inputValue.length === 0) {
if (subCategory.length === 0) {
$("#required-subcategory").show();
validInput = false;
} else {
$("#required-subcategory").hide();
}
if (series.length === 0) {
$("#required-series").show();
validInput = false;
} else {
$("#required-series").hide();
}
if (modelCode.length === 0) {
$("#required-model-code").show();
validInput = false;
} else {
$("#required-model-code").hide();
}
return validInput;
}
$("#required-subcategory").hide();
$("#required-series").hide();
$("#required-model-code").hide();
return true;
};
const checkHideDropdownErrors = () => {
const subCategory = categoryDropdown.getValue() ?? "";
const series = seriesDropdown.getValue() ?? "";
const modelCode = modelCodeDropdown.getValue() ?? "";
if (subCategory.length !== 0) {
$("#required-subcategory").hide();
}
if (modelCode.length != 0) {
$("#input-product-info").hide();
$("#required-model-code").hide();
}
if (series.length != 0) {
$("#required-series").hide();
}
};
const validationSymptom = () => {
let modelCode = modelCodeDropdown.getValue() ?? "";
const symtomSelected = getSymtomValue();
if (symtomSelected.length === 0 || modelCode.length === 0) {
$("#symptom-at-least-one").show();
return false;
} else {
$("#symptom-at-least-one").hide();
return true;
}
};
//Action hide error message when change input value
const inputSearchChange = () => {
const inputValue = $("#input-box").val();
//const subCategory = $('#sub-category').val();
const modelCode = modelCodeDropdown.getValue() ?? "";
if (inputValue.length > 0 || modelCode.length > 0) {
$("#input-product-info").hide();
$("#required-subcategory").hide();
$("#required-series").hide();
$("#required-model-code").hide();
}
};
const dropdownProductChange = () => {
const inputValue = $("#input-box").val();
const subCategory = $("#sub-category").val();
const series = $("#series").val();
const modelCode = $("#model-code").val();
if (inputValue.length === 0) {
if (subCategory.length > 0) {
$("#required-subcategory").hide();
}
if (series.length > 0) {
$("#required-series").hide();
}
if (modelCode.length > 0) {
$("#required-model-code").hide();
}
} else {
$("#required-subcategory").hide();
$("#required-series").hide();
$("#required-model-code").hide();
}
};
const dropdownSymptomChange = () => {
const symtomSelected = getSymtomValue();
if (symtomSelected.length > 0) {
$("#symptom-at-least-one").hide();
}
};
resultsBox.focusout(function () {
checkValidation();
});
const getSymtomValue = () => {
var self = $(".multiSelect");
var field = self.find(".multiSelect_field");
var selectedOptions = field.find("option:selected");
const values = [];
for (const element of selectedOptions) {
values.push(element.value);
}
return values;
};
const getSymtomName = () => {
var symptomSelecteds = document.querySelectorAll(".multiSelect_choice");
var estimateName = [];
symptomSelecteds.forEach((e, index) => {
estimateName.push(e.textContent);
});
return estimateName;
};
const filterByKeyword = (products, keyword) => {
keyword = keyword.replaceAll(" inch", '"');
keyword = keyword.replaceAll("inch", '"');
const words = keyword.split(" ");
const values = products.filter((product) => {
const rs = words.every((word) => {
const workCheck = word.includes("inch") === true ? '"' : word;
if (workCheck.length === 0) {
return false;
}
return (
product?.name?.toLowerCase().includes(workCheck.toLowerCase()) ||
product?.serieName
?.toLowerCase()
.includes(workCheck.toLowerCase()) ||
product?.modelCode
?.toLowerCase()
.includes(workCheck.toLowerCase())
);
});
return rs;
});
return values;
};
filterByCategory = (products, categoriesId) => {
return products.filter((product) =>
categoriesId.includes(product?.subcategoriesId)
);
};
const searchByKeyword = (keyword) => {
let filterResult = filterByKeyword(products, keyword);
if (CategoriesDisplay.length > 0) {
const categoriesId = CategoriesDisplay.map((e) => e.id);
filterResult = filterByCategory(filterResult, categoriesId);
}
return filterResult;
};
const checkValidation = () => {
let isValid = true;
isValid = inputSearchValidation() && isValid;
isValid = dropdownInfoValidation() && isValid;
isValid = validationSymptom() && isValid;
$("#only-two-symptom").hide();
return isValid;
};
let timeoutId;
inputBox.on("keyup", async (e) => {
const keyTyping = $("#input-box").val();
if (
keyTyping.length >= 1 ||
keyTyping === "Backspace" ||
keyTyping == "Control"
) {
let result = [];
let input = inputBox.val();
inputSearchChange();
checkDisableReset();
isSymptomDisable(true);
clearDropdownOption();
clearSymptom();
if (input.length >= 2) {
clearTimeout(timeoutId);
timeoutId = setTimeout(async () => {
const response = searchByKeyword(input.trim());
if (response.length === 0 && input.length >= 10) {
const newInput = input.substring(0, 7);
const newResponse = searchByKeyword(newInput.trim());
display(newResponse);
} else {
display(response);
}
}, 500);
resetIcon.show();
} else {
resetIcon.hide();
}
if (!result.length) {
resultsBox.html("");
}
} else {
const boxResult = document.querySelectorAll(".result-box li");
let indexFocus = -1;
boxResult.forEach((e, index) => {
if (e.classList.contains("focus")) {
indexFocus = index;
}
});
switch (keyTyping) {
case "ArrowUp":
indexFocus = indexFocus === -1 ? 0 : indexFocus;
boxResult[indexFocus].classList.remove("focus");
if (indexFocus === 0) {
indexFocus = boxResult.length - 1;
} else {
indexFocus = indexFocus - 1;
}
boxResult[indexFocus].scrollIntoView();
boxResult[indexFocus].classList.add("focus");
break;
case "ArrowDown":
indexFocus = indexFocus === -1 ? 0 : indexFocus;
boxResult[indexFocus].classList.remove("focus");
if (indexFocus === boxResult.length - 1) {
indexFocus = 0;
} else {
indexFocus = indexFocus + 1;
}
boxResult[indexFocus].scrollIntoView();
boxResult[indexFocus].classList.add("focus");
break;
case "Enter":
if (indexFocus === -1) {
indexFocus = 0;
}
const { textContent } = boxResult[indexFocus];
inputBox.val(textContent);
productSelected(boxResult[indexFocus]);
resultsBox.html("");
resetIcon.show();
break;
default:
break;
}
}
});
resetIcon.on("click", function () {
inputBox.val("");
resetIcon.hide();
resultsBox.html("");
inputBox.focus("");
clearSymptom();
clearDropdownOption();
});
const setInputValue = (input) => {
if (input.length === 0) {
inputBox.val("");
resetIcon.hide();
} else {
inputBox.val(input);
resetIcon.show();
}
};
const clearSymptom = () => {
const selectBox = document.querySelector(".multiSelect_field");
//Clear option
selectBox.innerHTML = "";
//SetUpMultiSelect
setUpMultiSelect();
isSymptomDisable(true);
};
function display(result) {
if (result.length === 0 && inputBox.val().length !== 0) {
const html = `
`;
resultsBox.html(html);
return;
}
const content = result
.sort((obj1, obj2) => obj1.name.localeCompare(obj2.name))
.map((list, index) => {
return `
${list.name} | ${list.modelCode} `;
});
resultsBox.html(
"
"
);
resultsBox.find("li").on("click", function () {
selectInput($(this), this);
});
}
function selectInput(list, dom) {
inputBox.val(list.text());
productSelected(dom);
resultsBox.html("");
resetIcon.show();
}
const productSelected = async (product) => {
productIdSeleted = product.dataset.value;
const subCategoriesId = product.dataset.categoryid;
const seriesId = product.dataset.seriesid;
const estimateButton = document.querySelector("#get-estimate");
//replaced value model
const modelCode = product.textContent.split("|")[1];
estimateButton.setAttribute(
"data-omni",
`sg:support sparepartestimator:${modelCode.trim()}_getestimate`
);
estimateButton.setAttribute(
"ga-la",
`sparepartestimator:${modelCode.trim()}_getestimate`
);
if (productIdSeleted) {
isSymptomDisable(false);
document.querySelector(".symptom-title").classList.remove("disable");
} else {
isSymptomDisable(true);
document.querySelector(".symptom-title").classList.add("disable");
}
const data = await fetch(
`${API_URL}/api/symptoms?productId=${productIdSeleted}`
);
const symptoms = await data.json();
showSymptom(symptoms);
changeSearchValue({
productId: productIdSeleted,
subCategoriesId,
seriesId,
});
};
// Jorn code - multi dropdown
//$('#Symptom').select2();
const getDistinField = (data, fieldName) => {
const allItems = data.map((e) => {
return e[fieldName];
});
const displayItem = [...new Set(allItems)];
return displayItem;
};
let dataJson = [];
const parternTrim = /\s+/g;
const main = async () => {
const data = await fetch(`${API_URL}/api/subcategories`);
const subcategories = await data.json();
let categories = subcategories;
if (CategoriesDisplay.length > 0) {
const categoriesName = CategoriesDisplay.map(
(category) => category.name
);
categories = subcategories.filter((e) => {
return categoriesName.includes(e.name);
});
}
categoryDropdown.replaceOptions(
categories.map((e) => {
return {
value: e.id,
text: e.name,
};
})
);
};
//Handle show
const showSymptom = (data) => {
let html = `
${globalContentJson.locale.symptom.name} `;
data.forEach((Symptom) => {
html += `
${Symptom.name} `;
});
document.querySelector(".multiSelect_field").innerHTML = html;
setUpMultiSelect();
};
//Event document change
document
.querySelector("#sub-category")
.addEventListener("change", async (event) => {
dropdownProductChange();
checkDisableReset();
setInputValue("");
const data = await fetch(
`${API_URL}/api/series?subcategoryId=${event.target.value}`
);
const series = await data.json();
isSymptomDisable(true);
});
const onSubSelected = () => {
const subSelected = "";
const data = dataJson.filter((e) => {
return e.Subcategory == subSelected;
});
return data;
};
const removeAllWhiteSpace=(str)=>{
return str.replace(/\s+/g,'');
}
const checkArrayAreEqual = (arr1,arr2)=>{
if(arr1.length!==arr2.length){
return false;
}
return arr1.every((item)=>arr2.includes(item));
}
document
.querySelector("#get-estimate")
.addEventListener("click", async (e) => {
const isValid = checkValidation();
if (isValid) {
const modelCode = modelCodeDropdown.getValue() ?? "";
const productId =
modelCode.length > 0 ? modelCode : productIdSeleted;
const data = await fetch(API_URL + "/api/estimate", {
method: "POST",
headers: {
"Content-Type": "application/json-patch+json",
},
body: JSON.stringify({
productId,
symptomIds: getSymtomValue(),
}),
});
let estimate = await data.json();
const seriesSelectedNames = seriesDropdown.getSelectedText();
const symptomSelectedNames = getSymtomName();
// Check if series name is Galaxy Z and lenght of product issues = 2 and symptomSelectedNames
// is 'External Display Issues (Broken / Colour Inaccurate)'
// and 'Internal Display Issues (Broken / Colour Inaccurate)' then return estimate data with type replacement
const seriesNameCheck = "Galaxy Z";
const issuesCheck = [
"External Display Issues (Broken / Colour Inaccurate)",
"Internal Display Issues (Broken / Colour Inaccurate)"
];
const repairType = "Replacement";
if (removeAllWhiteSpace(seriesSelectedNames).toLocaleLowerCase() === removeAllWhiteSpace(seriesNameCheck).toLocaleLowerCase()) {
const issuesSelectedLowerCase = symptomSelectedNames.map((e)=> removeAllWhiteSpace(e).toLocaleLowerCase());
const issuseCheckLowerCase = issuesCheck.map((e)=>removeAllWhiteSpace(e).toLocaleLowerCase());
if (
checkArrayAreEqual(issuesSelectedLowerCase,issuseCheckLowerCase)
) {
// e.repairType is string like:'Screen Replacement'
estimate = estimate.filter((e) => {
return e.repairType.toLocaleLowerCase().includes(repairType.toLocaleLowerCase());
});
}
}
//process sort item by pricing here
const newEstimateData = isSortPrice?
estimate.map((part)=>{
const repairParts = part?.repairParts.sort((item1,item2)=>{
if(item1.maxPrice==item2.maxPrice) return 0;
if(item1.maxPrice-item2.maxPrice>0){
return -1;
}
return 1;
});
return {
...part,
repairParts
}
}):estimate;
displayEstimate(newEstimateData);
var showMe = $("#showEstimate").offset().top;
$("html, body").animate({ scrollTop: showMe }, 1000);
//Dispatch Event
const faqEvent = new CustomEvent("FAQEvent", {
detail: {
symptom: getSymtomName().join(";"),
modelCode: modelCodeDropdown
.getSelectedText()
.split("|")[1]
.trim(),
},
});
document.dispatchEvent(faqEvent);
}
});
// })
// Toggle hidden down and up icons
const SetUpToggleIcon = () => {
$(".toggle-icon").click(function () {
var icon = $(this);
var target = $(this).data("target");
var toggleDiv = $('.toggle-option[data-target="' + target + '"]');
if (icon.find("use").attr("href") === "#open-down-bold") {
icon.find("use").attr("href", "#close-up-bold");
toggleDiv.removeClass("hidden");
} else {
icon.find("use").attr("href", "#open-down-bold");
toggleDiv.addClass("hidden");
}
});
};
const showEstimateText = () => {
const estimateNameDom = document.querySelector("#estimate-name");
const productNameDom = document.querySelector("#est-product-name");
const estimateName = getSymtomName();
const textBox = $("#input-box").val().trim();
const selectBox = document.querySelector("#model-code");
productNameDom.textContent =
textBox.length > 0
? textBox
: selectBox.options[selectBox.selectedIndex].text;
if (estimateName.length === 2) {
estimateNameDom.textContent =
estimateName[0] + " & " + estimateName[1];
} else {
estimateNameDom.textContent = estimateName[0];
}
};
const checkDisableReset = () => {
const buttonDisable = document.querySelector(
".reset-block .secondary-button"
);
if (
$("#input-box").val().length > 0 ||
categoryDropdown.getValue().length > 0 ||
modelCodeDropdown.getValue().length > 0 ||
getSymtomValue().length > 0
) {
buttonDisable.disabled = false;
} else {
buttonDisable.disabled = true;
}
};
const clearOptions = (id) => {
const options = document.querySelectorAll("#" + id + " option");
options.forEach((e, index) => {
if (index !== 0) {
e.remove();
}
});
};
document
.querySelector(".reset-block .secondary-button")
.addEventListener("click", (e) => {
categoryDropdown.resetValue();
seriesDropdown.clearOptions();
modelCodeDropdown.clearOptions();
document
.querySelector(".sp-search-box-row")
.classList.remove("disable");
inputBox.val("");
resetIcon.hide();
resultsBox.html("");
inputBox.focus("");
setUpMultiSelect();
isSymptomDisable(true);
$(".estimated-cost-wrapper-result").hide();
document.querySelector(
".reset-block .secondary-button"
).disabled = true;
});
const formatCurrency = (number) => {
number = Math.ceil(number);
return number.toFixed(number % 1 === 0 ? 0 : 2);
};
const formatPercentage = (decimal)=>{
const percentage = (value*100).toFixed(1);
const wholeNumber = Math.floor(percentage);
const decimalPart = (percentage-wholeNumber).toFixed(1).slice(2);
if(parseFloat(decimalPart)===0){
return `${wholeNumber}%`
}
return `${wholeNumber}.${decimalPart}%`;
}
const preciseMultiply = (value,multiplier) =>{
return Math.floor(value*multiplier*100)/100;
}
const formatPricing = (minValue,maxValue,symbol,isFront)=>{
minValue = formatCurrency(minValue);
maxValue = formatCurrency(maxValue);
if(minValue===maxValue){
if(isFront){
return symbol + minValue;
}
return minValue + symbol;
}
if(isFront){
return symbol + minValue +" - "+ symbol + maxValue;
}
return minValue + " - " + maxValue +symbol;
}
const showEstimateRepair = (
dataInput,
type,
isHiddenBlock = false,
optionText = ""
) => {
const id = type === 0 ? "repair":"replacement";
const domHtml = document.querySelector(`#${id} .option-col-content`);
const classColor = type === 0 ? "blue" : "black";
if (isHiddenBlock) {
$(".estimated-cost-wrapper").addClass("one-cardonly");
$(`#replacement`).hide();
}
document.querySelector(`#${id} .option-col-header`).textContent =
optionText + dataInput.repairType;
//make labour to bottom of pricing
const dataSortedWithSpecialKey = dataInput.repairParts.
sort((item1,item2)=>{
const listMap = labourKey.map(e=>e.toLowerCase());
const itemKey1 = item1.name.toLowerCase();
const itemKey2 = item2.name.toLowerCase();
const foundKey1 = listMap.filter(key=>itemKey1.includes(key));
const foundKey2 = listMap.filter(key=>itemKey2.includes(key));
if(foundKey1.length>0&&foundKey2.length===0){
return 1;
}else if(foundKey1.length===0&&foundKey2.length>0){
return -1;
}
return 0;
});
dataInput.repairParts = dataSortedWithSpecialKey
.map((e,index) => {
return {
...e,
group: e.group !== undefined&&e.group!=="" ? e.group : "non-group-"+index,
};
});
//group data by group name
const newData = Object.groupBy(
dataInput.repairParts,
({ group }) => group
);
const dataKeys = Object.keys(newData);
const subCategoryContent = categoryDropdown.getSelectedText();
const optionDisplayArrow = {
class: subCategoryContent !== "TV" ? "hidden" : "",
id:
subCategoryContent !== "TV" ? "#open-down-bold" : "#close-up-bold",
};
let content = ``;
const keyTop = "Likely needed";
const likeLyIndex = dataKeys.indexOf(keyTop);
if (likeLyIndex !== -1) {
dataKeys.splice(likeLyIndex, 1);
dataKeys.unshift(keyTop);
}
const isFront = SYMBOL_POSITION.FRONT === globalContentJson.locale.currency.position;
const symbol = globalContentJson.locale.currency.symbol;
dataKeys.forEach((key) => {
let data = newData[key];
let totalMin = 0;
let totalMax = 0;
if (!key.includes("non-group")) {
let subSymtom = "";
data.forEach((e) => {
totalMin += e.minPrice;
totalMax += e.maxPrice;
const itemPriceMinMax = formatPricing( e.minPrice,e.maxPrice,symbol,isFront);
subSymtom += `
• ${
e.name
}
${itemPriceMinMax}
`;
});
const dataTarget = (key + optionText).replace(" ", "-").trim();
const itemPriceMinMax = formatPricing(totalMin,totalMax,symbol,isFront);
content += `
${key}
${itemPriceMinMax}
${subSymtom}
`;
} else {
data.forEach((e, index) => {
const itemPriceMinMax = formatPricing( e.minPrice,e.maxPrice,symbol,isFront);
content += `
${e.name}
${itemPriceMinMax}
`;
});
}
});
let totalMinMax = formatPricing(dataInput.totalMin,dataInput.totalMax,symbol,isFront);
let subMinMax = formatPricing(dataInput.subtotalMin,dataInput.subtotalMax,symbol,isFront);
let gstMinMax = formatPricing(dataInput.gstMin,dataInput.gstMax, symbol, isFront);
if (dataInput.gst === 0) {
content += `
${globalContentJson.locale.result['total-cost']}
${totalMinMax}
`;
} else {
content += `
${globalContentJson.locale.result['total-cost']}
${subMinMax}
${globalContentJson.locale["gst-tax"]} (${
preciseMultiply(dataInput.gst,100)
}%)
${gstMinMax}
${globalContentJson.locale.result['total-cost']}
${totalMinMax}
`;
}
domHtml.innerHTML = content;
};
const displayEstimate = (data) => {
//0-> Repair, 1-> Replacement, 2 both
if (data.length > 0) {
showEstimateText();
$(".estimated-cost-subheader").hide();
if (data.length == 1) {
showEstimateRepair(data[0], 0, true);
} else if (data.length == 2) {
//By default data[1]=> Repair, data[0] replacement
showEstimateRepair(data[0], 0, false, globalContentJson.locale.optiontext.option1);
showEstimateRepair(data[1], 1, false, globalContentJson.locale.optiontext.option2);
// const id = type === 0?'repair':'replacement'
if (
data[0].repairType === "Screen Replacement" ||
data[0].repairType === "Screen Repair"
) {
$(".estimated-cost-subheader").show();
}
$("#repair").show();
$("#replacement").show();
$(".estimated-cost-wrapper").removeClass("one-cardonly");
}
SetUpToggleIcon();
displayCTAButton();
$(".estimated-cost-wrapper-result").show();
}
};
// multi select
const setUpMultiSelect = () => {
$(".multiSelect").each(function (e) {
var self = $(this);
var field = self.find(".multiSelect_field");
var fieldOption = field.find("option");
var placeholder = field.attr("data-placeholder");
const disableClass =
document
.querySelector(".multiSelect_dropdown")
?.classList?.contains("disable") === true
? "disable"
: "";
document.querySelector(".multiSelect_dropdown")?.remove();
document.querySelector(".multiSelect_placeholder")?.remove();
const multiSelect_option = document.querySelectorAll(
".multiSelect_option"
);
multiSelect_option.forEach((e) => {
e?.remove();
});
field.nextAll().remove();
field.hide().after(
`
` +
placeholder +
`
`
);
fieldOption.each(function (e) {
const customClass = e === 0 ? "disable" : "";
$(".multiSelect_list").append(
`
` +
$(this).text() +
`
`
);
});
//Add event for arrow function
document
.querySelector(".multiSelect .multiSelect_arrow")
?.addEventListener("click", (e) => {
e.stopPropagation();
e.preventDefault();
dropdown.toggleClass("-open");
list
.toggleClass("-open")
.scrollTop(0)
.css("top", dropdown.height() + 15);
});
var dropdown = self.find(".multiSelect_dropdown");
var list = self.find(".multiSelect_list");
var option = self.find(".multiSelect_option");
var optionText = self.find(".multiSelect_text");
dropdown.attr("data-multiple", "true");
list.css("top", dropdown.height() + 20);
function updateSelectedItems() {
selectedBox.empty();
field.find("option:selected").each(function () {
var text = $(this).text();
selectedBox.append(
`
${text}
`
);
});
selectedBox
.parent()
.toggle(field.find("option:selected").length > 0);
}
option.click(function (e) {
var self = $(this);
var selectedOptions = field.find("option:selected").length;
if (e.target.classList[0] === "multiSelect_option") {
//If Item selected is Symptom then ignore
return;
}
checkDisableReset();
if (self.hasClass("selected-highlight")) return;
if (selectedOptions < 2 || self.hasClass("-selected")) {
//e.stopPropagation();
self.addClass("selected-highlight");
field
.find("option:contains(" + self.children().text() + ")")
.prop("selected", true);
dropdown
.append(function (e) {
return $(
`
` +
self.children().text() +
' '
).click(function (e) {
var self = $(this);
//e.stopPropagation();
self.remove();
list
.find(".multiSelect_option:contains(" + self.text() + ")")
.removeClass("selected-highlight");
list
.css("top", dropdown.height() + 15)
.find(".multiSelect_noselections")
.remove();
field
.find("option:contains(" + self.text() + ")")
.prop("selected", false);
if (dropdown.children(":visible").length === 0) {
dropdown.removeClass("-hasValue");
}
//Logic hide pricing
$(".estimated-cost-wrapper-result").hide();
});
})
.addClass("-hasValue");
list.css("top", dropdown.height() + 15);
if (!option.not(".-selected").length) {
list.append(
'
No Selections '
);
}
} else {
$("#only-two-symptom").show();
}
dropdownSymptomChange();
});
$(document).on("click", ".multiSelect_deselect", function (e) {
var text = $(this).parent().text();
field.find("option:contains(" + text + ")").prop("selected", false);
list
.find(".multiSelect_option:contains(" + text + ")")
.removeClass("-selected");
updateSelectedItems();
});
dropdown.click(function (e) {
e.stopPropagation();
e.preventDefault();
dropdown.toggleClass("-open");
list
.toggleClass("-open")
.scrollTop(0)
.css("top", dropdown.height() + 15);
});
$(document).on("click touch", function (e) {
if (dropdown.hasClass("-open")) {
dropdown.toggleClass("-open");
list.removeClass("-open");
}
});
});
};
/*End JS */
const isSymptomDisable = (isDisable) => {
const dropdown = document.querySelector(".multiSelect_dropdown");
const dropdownPlacehorder = document.querySelector(
".multiSelect_placeholder"
);
const titleofMultiSelect = document.querySelector(".symptom-title");
if (isDisable) {
dropdown.classList.add("disable");
dropdownPlacehorder.classList.add("disable");
titleofMultiSelect.classList.add("disable");
} else {
dropdown.classList.remove("disable");
dropdownPlacehorder.classList.remove("disable");
titleofMultiSelect.classList.remove("disable");
}
};
const isDropdownInfoDisable = (isDisable) => {
const subCategory = document.querySelector("#sub-category");
const series = document.querySelector("#series");
const modelCode = document.querySelector("#model-code");
const titleofMultiSelect = document.querySelector(".symptom-title");
if (isDisable) {
subCategory.classList.add("disable");
series.classList.add("disable");
modelCode.classList.add("disable");
titleofMultiSelect.classList.add("disable");
} else {
subCategory.classList.remove("disable");
series.classList.remove("disable");
modelCode.classList.remove("disable");
titleofMultiSelect.classList.remove("disable");
}
};
const isDisableInput = (isDisable) => {
const input = document.querySelector(".sp-search-box-row");
if (isDisable) {
input.classList.add("disable");
} else {
input.classList.remove("disable");
}
};
const updateTextContent = (jsonContent) => {
document.querySelector("#select_your_product_and_issue").textContent = jsonContent.select_your_product_and_issue
document.querySelector("#input-box").placeholder = jsonContent.input_search_product.content;
document.querySelector("#input-product-info").textContent = jsonContent.input_search_product.msg_error;
document.querySelector("#or_select_dropdown").textContent = jsonContent.or_select_dropdown;
document.querySelector("#required-subcategory").textContent = jsonContent.category.msg_erorr;
document.querySelector("#required-series").textContent = jsonContent.series.msg_erorr;
document.querySelector("#required-model-code").textContent = jsonContent.model.msg_erorr;
//symptom-title
document.querySelector("#symptom-title").textContent = jsonContent["symptom-title"];
document.querySelector("#symptom-at-least-one").textContent = jsonContent.symptom["symptom-at-least-one"];
document.querySelector("#only-two-symptom").textContent = jsonContent.symptom["only-two-symptom"];
document.querySelector("#symptom-selected").textContent = jsonContent.symptom["symptom-selected"];
document.querySelector("#not-found-issues").textContent = jsonContent["support-msg"]["not-found-issues"];
if(jsonContent["support-msg"]["support-url"]===undefined||jsonContent["support-msg"]["support-url"]===null||jsonContent["support-msg"]["support-url"].length===0){
document.querySelector("#contact-for-us-block").innerHTML = jsonContent["support-msg"]["contact-for-us"];
}else{
document.querySelector("#contact-for-us").textContent = jsonContent["support-msg"]["contact-for-us"];
document.querySelector("#contact-for-us").href = jsonContent["support-msg"]["support-url"];
}
document.querySelector("#get-estimate").textContent = jsonContent["get-estimate"];
document.querySelector("#reset").textContent = jsonContent["reset"];
document.querySelector("#showEstimate").textContent = jsonContent.result["title-repair"];
//Special case if have more 2 urls like NZ
if(jsonContent.result["url-learn-difference"]===null||jsonContent.result["url-learn-difference"]===undefined||jsonContent.result["url-learn-difference"]?.length===0){
document.querySelector("#learn-difference-between-block").innerHTML =`
${ jsonContent.result["repair-learn-title"]} `
}else{
document.querySelector("#learn-difference-between").textContent = jsonContent.result["repair-learn-title"];
document.querySelector("#learn-difference-between").href = jsonContent.result["url-learn-difference"];
}
document.querySelector("#showEstimate").textContent = jsonContent['title-show-estimate'];
document.querySelector("#symtom-multi-selector").setAttribute("data-placeholder",jsonContent.symptom.name)
};
const TIME_CACHED = 15; // unit minues
const APP_CONFIG_KEY = "APP_CONFIG_KEY";
const countryUrl = {
vn:'https://vnrepaircostestimatorstg.blob.core.windows.net/upload/vn-repair-cost-estimator-11664/@country-code.json',
th:'https://threpaircostestimatorstg.blob.core.windows.net/upload/th-repair-cost-estimator-11660/@country-code.json',
au:'https://phrepaircostestimatorstg.blob.core.windows.net/upload/ph-repair-cost-estimator-11663/@country-code.json',
my:'https://myrepaircostestimatorstg.blob.core.windows.net/upload/my-repair-cost-estimator-11661/@country-code.json',
nz:'https://nzrepaircostestimatorstg.blob.core.windows.net/upload/nz-repair-cost-estimator-11662/@country-code.json',
ph:'https://phrepaircostestimatorstg.blob.core.windows.net/upload/ph-repair-cost-estimator-11663/@country-code.json',
sg:'https://phrepaircostestimatorstg.blob.core.windows.net/upload/ph-repair-cost-estimator-11663/@country-code.json',
id:'https://idrepaircostestimatorstg.blob.core.windows.net/upload/@country-code.json'
}
//Run when everything ready
const appStart = async (country) => {
const commonConfig = configByCountry[country]
labourKey = commonConfig?.labour??labourKey;
isSortPrice =commonConfig?.isSortPrice;
isDisplayCTAButton = commonConfig?.isDisplayCTAButton;
let ENDPOINT_GET_CONFIGURATION = `/seao/locale/${country}.json`;
//Check if not in local
if(!window.location.href.includes('127.0.0.1')){
ENDPOINT_GET_CONFIGURATION = countryUrl[country].replace('@country-code',country).trim(); //update here
}
isLoading(true);
const countryKey= APP_CONFIG_KEY+"_"+country.toUpperCase();
let jsonContent = localStorage.getItem(countryKey);
const now = new Date();
const lastUpdated = new Date(JSON.parse(jsonContent)?.lastUpdate);
const validTime =Math.floor(Math.abs(now-lastUpdated)/(1000*60)) < TIME_CACHED;
const checkConfigValid = jsonContent!==null&&validTime;
if(!checkConfigValid) {
try {
const jsonRes = await fetch(ENDPOINT_GET_CONFIGURATION);
jsonContent = await jsonRes.json();
jsonContent.lastUpdate = now.getTime();
localStorage.setItem(countryKey,JSON.stringify(jsonContent));
} catch (ex) {
alert(ex.message);
}
}else{
jsonContent = (JSON.parse(jsonContent));
}
API_URL = jsonContent.configuration.backendStgUrl;//Testing on local
if (window.document.location.origin.indexOf('p6-qa.samsung.com') > 0) {
API_URL = jsonContent.configuration.backendStgUrl;//for stg
} else if (window.document.location.origin.indexOf('www.samsung.com') > 0) {
API_URL = jsonContent.configuration.backendProdUrl;//for prod
}
globalContentJson = jsonContent;
defer(async () => {
$(document).ready(async () => {
const data = await fetch(API_URL + `/api/all`);
products = await data.json();
});
});
updateDropdownTitle(jsonContent.locale);
updateTextContent(jsonContent.locale);
main();
setUpMultiSelect();
isSymptomDisable(true);
isLoading(false)
};
const urlObj = new URL(window.location.href);
var paths = urlObj.pathname.split("/");
let country = DEFAULT_COUNTRY;
if(paths.length> 2){
country = paths[1];
}
appStart(country);
/*End JS */
});
The cost of repair (which may include parts and its corresponding prices) indicated above is an estimate only and does not include any applicable taxes and/or labour cost for any removal/shifting of appliances which may be necessary to facilitate the repair.
The final repair quotation (including the final list of parts to be repaired) will be provided to you upon inspection by authorised Samsung technicians.
Upgrade now
Enjoy the latest products and features for less!
`;
});
if (htmlContent.length > 0) {
document.querySelector("#faq-wrapper").style.display = "block";
} else {
document.querySelector("#faq-wrapper").style.display = "none";
}
document.querySelector(".faq-spacer").textContent = "FAQs";
dom.innerHTML = htmlContent;
});
});