UNPKG

carget

Version:

optimization js code for carget website

26 lines 58 kB
const isExelLoadingFinish=false;let Google_DB={};let carData={};const customConsoleLog=async(description,value,descriptionStyle,valueStyle)=>{await console.log(`%c${description}`,descriptionStyle,value)};let TEST3,TEST4;let modelsArray=[];const data4=["Работаем за свои средства","Белая и прозрачная структура договоров","Официальные оплаты по счетам","Быстрый возврат средств клиенту в случае нарушения условий договора","Исключены таможенные риски","Большой парк электромобилей в наличии в Москве","Русификация авто и техническая поддержка"];const data5=[{img:"https://carget.su/wp-content/uploads/2023/11/phone-icon.png",contact:"+7 996 410-01-87"},{img:"https://carget.su/wp-content/uploads/2023/11/whatsapp-icon.png",contact:"+7 996 410-01-87"},{img:"https://carget.su/wp-content/uploads/2023/11/telegram-icon.png",contact:"+7 996 410-01-87"},{img:"https://carget.su/wp-content/uploads/2023/11/email-icon.png",contact:"carget@bk.ru"}];let carState={model:[],models:[],options:{color:[0,"",[]],wheels:[0,"",[],true],interiorColor:[0,"",[]],runningBoards:[[],true]},delivery:{},labFees:0,recyclingFee:0,carLocalization:0,marga:[]};let updatedCarState;let myPriceModels;const priceInRub={};const pricecustomInRub={};let savedSlides={};let originalColorOptions={};let originalWheelsOptions={};let originalInteriorColorOptions={};const divPriceModels={};let previousModel,previousColor=null;let saleAll=0;let pdfDoc;let totalPrice=0;let indexDisk=0;let myArrowDiskImages;let myDiskImage,mySalonImage;let isUpdatingCarousel=false;let modelNames,modelElements;let arrayImagesForPDF=["https://carget.su/wp-content/uploads/2023/11/carget-logo.jpg","https://carget.su/wp-content/uploads/2023/11/carget-logo.jpg","https://carget.su/wp-content/uploads/2023/11/carget-logo.jpg"];const arrayTitlePrice={color:"#carget-acordion-color-price span",wheels:"#carget-acordion-wheels-price span",interiorColor:"#carget-acordion-interiorColor-price span"};const arrayWrappers=[".carget-color",".carget-wheels",".carget-interiorColor",".carget-runningBoards"];const cargetModels=document.querySelector("#carget-models .elementor-container");const totalpriceElements=document.querySelectorAll(".header-totalprice");const checkbox=document.getElementById("myCheckbox");const checkboxLabel=document.querySelector(".custom-checkbox-label");const checkboxSpan=document.getElementById("custom-checkbox-span");const checkImages=document.querySelectorAll(".check-list-image");const discountCheck=document.getElementById("check-list-items-discount");const priceItemDiscount=document.getElementById("price-items-discount");const colorKuzovaElements=document.querySelectorAll(".check-color");const colorSalonaElements=document.querySelectorAll(".check-color-salon");const diskElements=document.querySelectorAll(".check-disk");const dopOptionsElements=document.querySelector(".check-dop-option");const totalPriceCarElements=document.querySelectorAll(".total-price-car");const totalSaleCarElements=document.querySelectorAll(".total-discount");const priceColorElements=document.querySelectorAll(".check-color-price");const priceColorSalonElements=document.querySelectorAll(".check-color-salon-price");const priceDiskElements=document.querySelectorAll(".check-disk-price");const priceDopOptionsElements=document.querySelector(".check-dop-option-price");const colorCarousel=document.getElementById("carget-acordion-color").querySelector(".swiper");const colorImageCarousel=document.getElementById("carget-acordion-color-image").querySelector(".swiper");const diskDiametr=document.getElementById("carget-acordion-disk")?document.getElementById("carget-acordion-disk").querySelector(".swiper"):"";const diskImage=document.getElementById("carget-acordion-disk-image")?document.getElementById("carget-acordion-disk-image").querySelector(".swiper"):"";const colorSalon=document.getElementById("carget-acordion-salon").querySelector(".swiper");const salonImage=document.getElementById("carget-acordion-salon-color").querySelector(".swiper");function addNewElementInCheck(customs){try{var wrapperBlock=document.getElementById("check-list-wrapper-block");if(!wrapperBlock)throw new Error("Элемент с id 'check-list-wrapper-block' не найден.");var existingElement=document.querySelector(".check-list-items.new-element-custom");if(existingElement){wrapperBlock.removeChild(existingElement)}var newCheckListItem=document.createElement("div");newCheckListItem.className="check-list-items new-element-custom";newCheckListItem.innerHTML=` <div class="check-list-row"> <span class="check-list-item">${customs.title}</span> <span class="check-list-item check-new-item"></span> <span class="check-list-item check-new-item-price">${customs.price}</span> </div> `;var discountElement=document.getElementById("check-list-items-discount");if(!discountElement)throw new Error("Элемент с id 'check-list-items-discount' не найден.");wrapperBlock.insertBefore(newCheckListItem,discountElement);document.querySelectorAll(".new-element-custom .check-list-item").forEach(e=>{e.style.borderBottom="0"})}catch(error){console.error("Произошла ошибка при добавлении нового элемента:",error.message)}}const loader=document.getElementById("header-loader");const cargetLoader=document.getElementById("carget-loader");function showLoader(){loader.style.display="block";cargetLoader.style.display="block"}function hideLoader(){loader.style.display="none";cargetLoader.style.display="none";console.log("loader hide")}const loaderCar=document.createElement("div");loaderCar.id="loader-car";loaderCar.className="loaderCar-text";loaderCar.textContent="CARGET";const loaderText=document.createElement("div");loaderText.id="loader-text";loaderText.className="loader-text";loaderText.textContent="Подгружаем данные";loader.appendChild(loaderCar);loader.appendChild(loaderText);const texts=["Настраиваем конфигуратор","Почти готово","Загружаем настройки","Финальные штрихи"];let textIndex=0;function changeLoaderText(){loaderText.textContent=texts[textIndex];textIndex=(textIndex+1)%texts.length}const textChangeInterval=setInterval(changeLoaderText,2e3);let selectedColor;const processSlidesColor=(carousel,savedSlides,addedSlides,option,attribute)=>{const isSlideAlreadyAdded=addedSlides.some(slide=>slide.innerHTML.includes(`alt="${option.color}"`));if(!isSlideAlreadyAdded){const filteredSlides=savedSlides.filter(slide=>slide.innerHTML.includes(`alt="${option.color}"`));if(attribute){const uniqueAlts={};filteredSlides.forEach(slide=>{const alt=slide.querySelector(attribute).getAttribute("alt");if(!(alt in uniqueAlts)){uniqueAlts[alt]=true}else{slide.remove()}})}filteredSlides.forEach(slide=>{carousel.swiper.appendSlide(slide);addedSlides.push(slide)})}};const processSlidesWheelsSalon=(swiper,savedSlides,addedSlides,option,attribute,selectedModel,selectedColor)=>{if((option.models.includes(selectedModel)||option.models.includes("All"))&&(option.colors.includes(selectedColor)||option.colors.includes("All"))){const isSlideAlreadyAdded=Array.from(addedSlides).some(slide=>slide.childNodes[0].childNodes[0].alt===option.color);if(!isSlideAlreadyAdded){const filteredSlides=savedSlides.filter(slide=>slide.childNodes[0].childNodes[0].alt===option.color);if(attribute){const uniqueAlts={};filteredSlides.forEach(slide=>{const alt=slide.childNodes[0].childNodes[0].alt;if(!(alt in uniqueAlts)){uniqueAlts[alt]=true}else{slide.remove()}})}filteredSlides.forEach(slide=>{swiper.appendSlide(slide);addedSlides.add(slide)})}}else{}};const checkColor=selectedModel=>{if(carState.options.color[2][0].models){carState.options.color[2]=[...originalColorOptions];carState.options.color[2]=carState.options.color[2].filter(option=>option.models.includes(selectedModel)||option.models.includes("All"));colorCarousel.swiper.removeAllSlides();colorImageCarousel.swiper.removeAllSlides();let addedColorSlides=[];let addedColorImageSlides=[];carState.options.color[2].forEach(option=>{processSlidesColor(colorCarousel,savedSlides.colorCarousel,addedColorSlides,option,".swiper-slide-image");processSlidesColor(colorImageCarousel,savedSlides.colorImageCarousel,addedColorImageSlides,option,".swiper-slide-image")});areAllSlidesWithSameAlt(colorCarousel)?removeDuplicateSlides(colorCarousel):"";areAllSlidesWithSameAlt(colorImageCarousel)?removeDuplicateSlides(colorImageCarousel):"";colorCarousel.swiper.update();colorImageCarousel.swiper.update()}if(colorCarousel.swiper.slides.length>1){customConsoleLog("colorCarousel.swiper.slides.length > 1",colorCarousel.swiper.slides.length,"background: brown; color: white;","font-weight: bold;");setTimeout(()=>{colorCarousel.swiper.slideTo(colorCarousel.swiper.params.slidesPerView)},400)}else if(colorCarousel.swiper.slides.length<=1){customConsoleLog("colorCarousel.swiper.slides.length <= 1",colorCarousel.swiper.slides.length,"background: brown; color: white;","font-weight: bold;");setTimeout(()=>{carState.options.color[1]=colorCarousel.querySelector(".swiper-slide-active img").alt},1500)}else{console.log("сработал не известный сценарий checkColor")}return true};const checkWheels=selectedModel=>{if(diskDiametr.swiper){document.querySelectorAll(arrayWrappers[1]).forEach(e=>{if(diskDiametr.swiper.slides.length>=1||carState.options.wheels[3]){e.style.display="block"}});carState.options.wheels[2]=[...originalWheelsOptions];carState.options.wheels[2]=carState.options.wheels[2].filter(option=>(option.models.includes(selectedModel)||option.models.includes("All"))&&(option.colors.includes(previousColor?previousColor:selectedColor)||option.colors.includes("All")));diskDiametr.swiper.removeAllSlides();diskImage.swiper.removeAllSlides();let addedDiskDiametrSlides=new Set;carState.options.wheels[2].forEach(option=>{processSlidesWheelsSalon(diskDiametr.swiper,savedSlides.diskDiametr,addedDiskDiametrSlides,option,".swiper-slide-image",selectedModel,selectedColor)});areAllSlidesWithSameAlt(diskDiametr)?removeDuplicateSlides(diskDiametr):"";diskDiametr.swiper.update();diskImage.swiper.update();if(diskDiametr.swiper.slides.length>1){customConsoleLog("diskDiametr > 1",diskDiametr.swiper.slides.length,"background: yellow; color: black;","font-weight: bold;");setTimeout(()=>{diskDiametr.querySelectorAll(".elementor-swiper-button").forEach(e=>{e.style.display="inline-flex"})},1500)}else if(diskDiametr.swiper.slides.length<=1){customConsoleLog("diskDiametr <= 1",diskDiametr.swiper.slides.length,"background: yellow; color: black;","font-weight: bold;");setTimeout(()=>{carState.options.wheels[1]=diskDiametr.querySelector(".swiper-slide-active img")?diskDiametr.querySelector(".swiper-slide-active img").alt:"";diskDiametr.querySelectorAll(".elementor-swiper-button").forEach(e=>{e.style.display="none"})},1500)}else{console.log("нет такого СЦЕНАРИЯ для дисков");customConsoleLog("нет такого СЦЕНАРИЯ для дисков",diskDiametr.swiper.slides.length,"background: yellow; color: black;","font-weight: bold;")}}diskImage.swiper?updateCarouselDisk(`${carState.options.color[1]}-0`,"checkWheels"):"";return true};const checkSalon=selectedModel=>{carState.options.interiorColor[2]=[...originalInteriorColorOptions];carState.options.interiorColor[2]=carState.options.interiorColor[2].filter(option=>(option.models.includes(selectedModel)||option.models.includes("All"))&&(option.colors.includes(previousColor?previousColor:selectedColor)||option.colors.includes("All")));colorSalon.swiper.removeAllSlides();salonImage.swiper.removeAllSlides();let addedColorSalonSlides=[];let addedSalonImageSlides=[];carState.options.interiorColor[2].forEach(option=>{processSlidesColor(colorSalon,savedSlides.colorSalon,addedColorSalonSlides,option,".swiper-slide-image");processSlidesColor(salonImage,savedSlides.salonImage,addedSalonImageSlides,option,".swiper-slide-image")});areAllSlidesWithSameAlt(colorSalon)?removeDuplicateSlides(colorSalon):"";colorSalon.swiper.update();salonImage.swiper.update();if(colorSalon.swiper.slides.length>1){setTimeout(()=>{colorSalon.swiper.slideTo(colorSalon.swiper.params.slidesPerView)?colorSalon.swiper.slideTo(colorSalon.swiper.params.slidesPerView):colorSalon.swiper.slideNext();colorSalon.swiper.params.centeredSlides=true;colorSalon.swiper.params.slideToClickedSlide=true;colorSalon.querySelectorAll(".elementor-swiper-button").forEach(e=>{e.style.display="inline-flex"})},1500)}else if(colorSalon.swiper.slides.length<=1){setTimeout(()=>{carState.options.interiorColor[1]=colorSalon.querySelector(".swiper-slide-active img").alt;colorSalon.querySelectorAll(".elementor-swiper-button").forEach(e=>{e.style.display="none"})},1500)}return true};async function updateOptions(selectedModel,where){customConsoleLog("updateOptions",where,"background: blue; color: white;","font-weight: bold;");const{options}=carState;const{wheels,color}=options;const wheelsCheckNeeded=wheels[3]===true;const colorCheckNeeded=selectedModel&&selectedModel!==previousModel;const salonCheckNeeded=colorSalon.swiper?true:false;const runChecks=async({isCheckColor=false,isCheckWheels=false,isCheckSalon=false})=>{try{if(isCheckColor&&colorCarousel.swiper){await checkColor(selectedModel)}if(isCheckWheels){await checkWheels(selectedModel)}if(isCheckSalon&&colorSalon.swiper){await checkSalon(selectedModel)}await updateTitlePrice("updateOptions")}catch(error){console.error("Ошибка при выполнении проверок:",error)}};try{if(colorCheckNeeded){previousModel=selectedModel;customConsoleLog("МОДЕЛЬ ИЗМЕНИЛАСЬ",selectedModel,"background: seagreen; color: white;","font-weight: bold;");await runChecks({isCheckColor:colorCheckNeeded,isCheckWheels:wheelsCheckNeeded,isCheckSalon:salonCheckNeeded});const customs={title:"*Стоимость таможни РФ",description:"—",price:`${numberWithSpaces(roundNumberToNChars(pricecustomInRub[selectedModel],4,"updateOptions"))} руб.`};addNewElementInCheck(customs)}else if(color[1]&&color[1]!==previousColor){previousColor=color[1];customConsoleLog("ЦВЕТ КУЗОВА ИЗМЕНИЛСЯ",color[1],"background: seagreen; color: white;","font-weight: bold;");await runChecks({isCheckColor:colorCheckNeeded,isCheckWheels:wheelsCheckNeeded,isCheckSalon:salonCheckNeeded})}}catch(error){console.error("Ошибка при обновлении опций:",error)}}function removeDuplicateSlides(carouselElement){try{const uniqueAlts=new Set;const slides=carouselElement.querySelectorAll(".swiper-slide");slides.forEach((slide,index)=>{const imgElement=slide.querySelector(".swiper-slide-image");if(imgElement){const alt=imgElement.getAttribute("alt");if(!uniqueAlts.has(alt)){uniqueAlts.add(alt)}else{slide.remove()}}else{console.warn(`Слайд ${index+1} не содержит изображение с классом '.swiper-slide-image'`)}})}catch(error){console.error("Ошибка в функции removeDuplicateSlides:",error)}}function areAllSlidesWithSameAlt(carousel){const slides=carousel.querySelectorAll(".swiper-slide");if(slides.length===0){return true}const firstSlideAlt=slides[0].querySelector(".swiper-slide-image").getAttribute("alt");for(let i=1;i<slides.length;i++){const slideAlt=slides[i].querySelector(".swiper-slide-image").getAttribute("alt");if(slideAlt!==firstSlideAlt){return false}}return true}function calculateWithPercentage(sum,percentage){return roundNumberToNChars(Math.ceil(sum*(1+percentage/100)),4,"calculateWithPercentage")}function numberWithSpaces(x){return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g," ")}function roundNumberToNChars(number,n,where){number=Math.ceil(number);if(typeof number!=="number"||!Number.isInteger(number)||number<0){throw new Error("number должно быть положительным целым числом",where)}if(typeof n!=="number"||!Number.isInteger(n)||n<1){throw new Error("n должно быть положительным целым числом больше или равным 1",where)}const multiplier=Math.pow(10,n-1);const roundedNumber=Math.ceil(number/multiplier)*multiplier;return roundedNumber}async function fetchCurrencyRates(){try{const storedData=localStorage.getItem("currencyRates");if(!storedData){const responseCNY=await fetch("https://open.er-api.com/v6/latest/CNY");const dataCNY=await responseCNY.json();const responseUSD=await fetch("https://open.er-api.com/v6/latest/USD");const dataUSD=await responseUSD.json();const rates={CNY:dataCNY.rates.RUB,USD:dataUSD.rates.RUB};await saveCurrencyRatesToLocalStorage(rates)}else{const currencyRates=JSON.parse(storedData);const lastUpdated=new Date(currencyRates.lastUpdated);const currentDate=new Date;const currentDateString=`${currentDate.getDate()}-${currentDate.getMonth()+1}-${currentDate.getFullYear()}`;const lastUpdatedString=`${lastUpdated.getDate()}-${lastUpdated.getMonth()+1}-${lastUpdated.getFullYear()}`;if(currentDateString!==lastUpdatedString){const responseCNY=await fetch("https://open.er-api.com/v6/latest/CNY");const dataCNY=await responseCNY.json();const responseUSD=await fetch("https://open.er-api.com/v6/latest/USD");const dataUSD=await responseUSD.json();const rates={CNY:dataCNY.rates.RUB,USD:dataUSD.rates.RUB};await saveCurrencyRatesToLocalStorage(rates)}}}catch(error){console.error("Ошибка при загрузке курсов валют:",error);throw error}}async function saveCurrencyRatesToLocalStorage(data){const currentDate=(new Date).toISOString();const currencyRates={rates:data,lastUpdated:currentDate};await localStorage.setItem("currencyRates",JSON.stringify(currencyRates));return data}async function updateCarouselDisk(dc,where){diskImage.swiper.removeAllSlides();const consoleValue={dc:dc,where:where};customConsoleLog("updateCarouselDisk",consoleValue,"background: blue; color: white;","font-weight: bold;");const color=dc.substring(0,dc.lastIndexOf("-"));const matchingIndexes=[];if(carState.options.wheels[2]&&diskDiametr.swiper){carState.options.wheels[2].forEach(option=>{if(option.colors.includes(color)||option.colors.includes("All")){matchingIndexes.push(option.index)}})}else if(carState.options.wheels[2]&&!diskDiametr.swiper){matchingIndexes.push(carState.options.wheels[2][0].index)}else{console.error("matchingIndexes underfind");return}let exactMatchSlides=[];if(Array.isArray(myArrowDiskImages)){exactMatchSlides=myArrowDiskImages.filter(slide=>{return matchingIndexes.some(index=>slide.querySelector("img").alt===`${color}-${index}`)})}else if(myArrowDiskImages){exactMatchSlides=myArrowDiskImages}else{console.error("myArrowDiskImages is undefined");return}exactMatchSlides.forEach(slide=>{diskImage.swiper.appendSlide(slide)});diskImage.swiper.update();const wheelIndexOption=indexOption("wheels",0,"index");if(wheelIndexOption){carState.options.wheels[0]=wheelIndexOption.price;carState.options.wheels[1]=wheelIndexOption.color}else{console.error('indexOption("wheels", 0, "index") returned undefined');return}if(diskDiametr&&diskDiametr.swiper){diskDiametr.swiper.slideTo(diskDiametr.swiper.params.slidesPerView,400);diskDiametr.swiper.update();diskDiametr.querySelectorAll(".elementor-swiper-button").forEach(button=>{button.style.display=diskDiametr.swiper.slides.length<=1?"none":"inline-flex"})}else if(diskDiametr){const slides=Array.from(diskDiametr.children);slides.forEach((slide,index)=>{slide.style.display=index===0?"block":"none"});diskDiametr.querySelectorAll(".elementor-swiper-button").forEach(button=>{button.style.display=slides.length<=1?"none":"inline-flex"})}else{console.error("diskDiametr is undefined");return}updateTitlePrice("updateCarouselDisk")}function findSlideIndexByAlt(slider,altAttribute){const slides=slider.querySelectorAll(".swiper-slide");for(let i=0;i<slides.length;i++){const slide=slides[i];const img=slide.querySelector("img");if(img&&img.alt===altAttribute){const dataIndex=slide.getAttribute("data-swiper-slide-index");return parseInt(dataIndex)}}return-1}async function updateImages(imageElement){if(!imageElement)return;const imgElement=imageElement.querySelector("img");if(!imgElement)return;const src=imgElement.getAttribute("src");if(!src)return;arrayImagesForPDF[1]=src;checkImages[0].innerHTML=myDiskImage.outerHTML}async function loadImageAsDataURLWithLogging(imagePath){try{const imageDataURL=await loadImageAsDataURL(imagePath);return imageDataURL}catch(error){console.error("Error loading image:",error);throw error}}async function loadImageAsDataURL(imagePath){if(!imagePath||imagePath.startsWith("data:image")){return imagePath}try{const response=await fetch(imagePath);if(!response.ok){throw new Error("Failed to fetch image")}let blob=await response.blob();const reader=new FileReader;const isWebP=blob.type==="image/webp";if(isWebP){const image=new Image;image.src=URL.createObjectURL(blob);await image.decode();const canvas=document.createElement("canvas");canvas.width=image.width;canvas.height=image.height;const context=canvas.getContext("2d");context.drawImage(image,0,0);const convertedBlob=await new Promise((resolve,reject)=>{canvas.toBlob(blob=>{if(!blob){reject(new Error("Failed to convert image"))}resolve(blob)})});blob=convertedBlob}return new Promise((resolve,reject)=>{reader.onload=()=>resolve(reader.result);reader.onerror=reject;reader.readAsDataURL(blob)})}catch(error){throw new Error("Error loading image as Data URL: "+error.message)}}const updateTitlePrice=async where=>{customConsoleLog("updateTitlePrice",where,"background: blue; color: white;","font-weight: bold;");if(typeof arrayTitlePrice!=="object"||arrayTitlePrice===null){console.error("arrayTitlePrice не является объектом");return}Object.entries(arrayTitlePrice).forEach(([option,selector])=>{try{const optionData=carState.options[option];if(!optionData)return;const[price,selectedColor,colorOptions]=optionData;let selectedOption=colorOptions.find(({color})=>color===selectedColor);if(!selectedOption&&colorOptions.length>0){selectedOption=colorOptions[0]}const element=document.querySelector(selector);if(element&&selectedOption){const saleHtml=selectedOption.sale!==undefined?`<span style="font-weight:700; display: flex; justify-content: center; gap: 8px;"> ${price} руб. <del style="text-decoration-color:#D10000; font-weight:300;">${selectedOption.sale} руб.</del> </span>`:`<span>${price} руб.</span>`;element.innerHTML=` <div style="display:flex;flex-direction:column;"> <span style="font-weight:700;">${selectedColor===selectedOption.color?selectedColor:selectedOption.color}</span> ${saleHtml} </div>`}}catch(error){console.error(`Error updating option ${option}:`,error)}});if(carState.options.wheels[3]===true&&diskImage){myDiskImage=diskImage.querySelector(".swiper-slide-active")?diskImage.querySelector(".swiper-slide-active"):diskImage.querySelector(".swiper-slide");if(myDiskImage){await updateImages(myDiskImage)}}else if(carState.options.wheels[3]===false&&colorImageCarousel){myDiskImage=colorImageCarousel.querySelector(".swiper-slide-active");if(myDiskImage){await updateImages(myDiskImage)}customConsoleLog("wheels[3] === false","","background: brown; color: white;","font-weight: bold;")}else{myDiskImage=colorImageCarousel.querySelector(".swiper-slide");await updateImages(myDiskImage);customConsoleLog("wheels[3] ни один сценарий не сработал","","background: brown; color: white;","font-weight: bold;")}if(salonImage&&salonImage.querySelector(".swiper-slide-active img")){arrayImagesForPDF[2]=salonImage.querySelector(".swiper-slide-active img")?.src}else if(salonImage&&salonImage.querySelector(".swiper-slide img")){arrayImagesForPDF[2]=salonImage.querySelector(".swiper-slide img")?.src}updateCheck()};const checkDopOtionShow=()=>{const displayValue=carState.options.runningBoards[1]?"flex":"none";document.querySelectorAll(arrayWrappers[3]).forEach(e=>{e.style.display=displayValue})};const removeShowDopOptions=()=>{const dopOptionsWrapper=document.querySelector(".dop-options-wrapper .elementor-widget-wrap");const selectedModel=carState.model[1];const children=dopOptionsWrapper.children;const childrenArray=Array.from(children);carState.options.runningBoards[0].forEach((option,index)=>{const child=children[index];const checkbox=document.getElementById(child.id);const checkboxInput=checkbox.querySelector(`#${child.id}`);if(option.check){option.show=false;checkboxInput.checked=false}const modelsToShow=option.models;const showOption=modelsToShow.includes(selectedModel)||modelsToShow.includes("All");const displayValue=showOption?"flex":"none";childrenArray.forEach(el=>{if(el.id===child.id){el.style.display=displayValue}})})};const updateDopOptions=()=>{const selectedModel=carState.model[1];const dopOptionsWrapper=document.querySelector(".dop-options-wrapper .elementor-widget-wrap");const children=dopOptionsWrapper.children;const childrenArray=Array.from(children);carState.options.runningBoards[0].forEach((option,index)=>{const child=children[index];const modelsToShow=option.models;const showOption=modelsToShow.includes(selectedModel)||modelsToShow.includes("All");const displayValue=showOption?"flex":"none";childrenArray.forEach(el=>{if(el.id===child.id){el.style.display=displayValue}});const checkbox=document.getElementById(child.id);const checkboxInput=checkbox.querySelector(`#${child.id}`);const checkboxLabel2=checkbox.querySelector(".custom-checkbox-label");const checkboxLabel=checkbox.querySelector(`.dop-option-title`);const checkboxDescription=checkbox.querySelector(".dop-option-description");const checkboxSpan=checkbox.querySelector(`#span-${child.id}`);checkboxLabel.textContent=option.title;checkboxDescription.textContent=option.description;checkboxSpan.innerHTML=`<div style="display:flex; gap:8px;"> <span style="font-weight:700;">${numberWithSpaces(option.price)} руб.</span> ${option.sale!==0&&option.sale?`<del style="text-decoration-color:#D10000; font-weight:300; color: #000">${option.sale} руб.</del> `:""} </div>`;const handleClick=()=>{if(option.check){checkboxInput.checked=!checkboxInput.checked;option.show=checkboxInput.checked;updateCheck()}};checkboxLabel2.addEventListener("click",handleClick);checkboxSpan.addEventListener("click",handleClick)})};const checkDopOptions=()=>{const dopOptionsToShow=carState.options.runningBoards[0].filter(option=>option.show);dopOptionsElements.textContent="";priceDopOptionsElements.textContent="";if(dopOptionsToShow.length>0&&carState.options.runningBoards[1]){dopOptionsToShow.forEach(option=>{const title=option.title;const price=option.price;const titleElement=document.createElement("div");titleElement.textContent=title;const priceElement=document.createElement("div");priceElement.textContent=`${numberWithSpaces(price)} руб.`;dopOptionsElements.appendChild(titleElement);priceDopOptionsElements.appendChild(priceElement)})}else{const noOptionsElement=document.createElement("div");noOptionsElement.textContent="Нет";dopOptionsElements.appendChild(noOptionsElement);priceDopOptionsElements.appendChild(noOptionsElement)}};function select(selector){return document.querySelectorAll(selector)}function getElementId(name,prefix="accordion-car-model-"){const id=`${prefix}${name.toLowerCase()}`;return id}function createModelElement(modelName,modelInfo){const lowercaseName=modelName.toLowerCase();const elements={model:select(`.${getElementId(lowercaseName)}`),acc:select(`.${getElementId(lowercaseName)} h4`),mobileButton:select(`.car-${lowercaseName}-mobile`),accordionItem:select(`.${getElementId(lowercaseName)} .elementor-tab-title`)};return elements}function defineModelElements(models){const elements={};models.forEach(model=>{const modelName=Object.keys(model)[0];elements[modelName]=createModelElement(modelName,model[modelName])});return elements}const createDivPriceModel=modelName=>{const divPriceModel=document.createElement("div");divPriceModel.className=`car${modelName}Model`;divPriceModel.id=`carmodel-price-${modelName.toLowerCase()}`;return divPriceModel};async function closeAccordions(){modelNames.forEach(e=>{modelElements[e].accordionItem[0].click()})}const innerPriceTitleModels=()=>{modelNames.forEach((modelName,index)=>{divPriceModels[modelName].innerHTML=` <div style="display:flex;flex-direction:column; gap: 8px;"> ${carState.models[index][modelName].sale!==0&&carState.models[index][modelName].sale?`<span style="font-size:16; font-weight:300"><del style="color: white;">${carState.models[index][modelName].sale} руб.</del></span>`:""} <span style="font-weight:700;">${numberWithSpaces(myPriceModels[index])} руб.</span> </div> `});modelNames.forEach((modelName,index)=>{const price=numberWithSpaces(myPriceModels[index]);modelElements[modelName].acc.forEach(element=>{element.innerHTML=` <div style="display:flex;flex-direction:column; gap: 8px;"> ${carState.models[index][modelName].sale!==0&&carState.models[index][modelName].sale?`<span style="font-size:20px; font-weight:300"><del style="color: white;">${carState.models[index][modelName].sale} руб.</del></span>`:""} <span style="font-weight:700;">${price} руб.</span> </div> `});modelElements[modelName].accordionItem[0].appendChild(divPriceModels[modelName])})};function createAndAttachButtonClickHandler(modelName){const buttons=document.querySelectorAll(`.car-${modelName.toLowerCase()}-mobile`);buttons.forEach(button=>{button.addEventListener("click",()=>{carState.model[1]=`${modelName}`;updateButtonState(carState);removeShowDopOptions();updateCheck()})})}function updateButtonState(carState){modelNames.forEach(modelName=>{const isSelected=carState.model[1]===`${modelName}`;const buttons=document.querySelectorAll(`.car-${modelName.toLowerCase()}-mobile`);buttons.forEach(button=>{const buttonTextElement=button.querySelector(".elementor-button-text");const elementorButton=button.querySelector(".elementor-button");button.style.cursor="pointer";button.style.borderRadius="3px";if(isSelected){button.style.backgroundColor="#fff";elementorButton?elementorButton.style.backgroundColor="#fff":"";buttonTextElement.style.color="#000";updateOptions(modelName,"updateButtonState")}else{button.style.backgroundColor="#DB2424";elementorButton?elementorButton.style.backgroundColor="#DB2424":"";buttonTextElement.style.color="#fff"}buttonTextElement.textContent=isSelected?"ВЫБРАНО":"ВЫБРАТЬ"})})}function convertCarState(carState){const storedData=localStorage.getItem("currencyRates");const currencyRates=JSON.parse(storedData);const usdToRubExchangeRate=currencyRates.rates.USD;const cnyToRubExchangeRate=currencyRates.rates.CNY;modelNames.forEach(modelName=>{const modelPrice=carState.models.find(model=>model[modelName]);const customPrice=modelPrice?modelPrice[modelName].custom:0;const modelPriceCNY=modelPrice?modelPrice[modelName].price:0;pricecustomInRub[modelName]=customPrice*cnyToRubExchangeRate;priceInRub[modelName]=modelPriceCNY*cnyToRubExchangeRate});const updatedCarState={...carState,models:carState.models.map(model=>{const modelName=Object.keys(model)[0];const priceInRub=model[modelName].price*cnyToRubExchangeRate;const customInRub=model[modelName].custom*cnyToRubExchangeRate;return{[modelName]:{price:priceInRub,custom:customInRub}}}),delivery:{...carState.delivery,fromTurgartToBishkek:carState.delivery.fromTurgartToBishkek*usdToRubExchangeRate,customs:carState.delivery.customs*usdToRubExchangeRate,otherExpenses:carState.delivery.otherExpenses*usdToRubExchangeRate,fromBishkekToRussia:carState.delivery.fromBishkekToRussia*usdToRubExchangeRate},labFees:carState.labFees,recyclingFee:carState.recyclingFee,carLocalization:carState.carLocalization};return updatedCarState}function sumCarModelsPrices(carState){const{models,delivery:{fromTurgartToBishkek,customs,otherExpenses,fromBishkekToRussia},labFees,recyclingFee,carLocalization,marga}=carState;const totalPrices=modelNames.map(modelName=>{const modelPriceCNY=models.find(model=>model[modelName])?.[modelName].price||0;const customCNY=models.find(model=>model[modelName])?.[modelName].custom||0;const total=modelPriceCNY+customCNY+fromTurgartToBishkek+customs+otherExpenses+fromBishkekToRussia+labFees+recyclingFee+carLocalization;const totalWithMarga=calculateWithPercentage(total,carState.marga);return roundNumberToNChars(totalWithMarga,4,"sumCarModelsPrices")});return totalPrices}function sumCarPrices(carState,myPriceModels){const{options:{color,wheels,interiorColor,runningBoards}}=carState;const selectedModel=carState.model[1];const modelIndex=modelNames.indexOf(selectedModel);if(modelIndex===-1){console.error("Выбранная модель не найдена в modelNames.");return}const modelPrice=myPriceModels[modelIndex];let total=modelPrice+color[0]+wheels[0]+interiorColor[0];if(runningBoards[1]){const options=runningBoards[0];options.forEach(option=>{if(option.show){total+=option.price}})}totalPrice=total;return numberWithSpaces(total)}const innerPriceHeader=()=>{totalpriceElements.forEach(e=>{e.innerHTML=numberWithSpaces(totalPrice)})};const totalSaleCheck=()=>{const model=carState.models.find(model=>model[carState.model[1]])?.[carState.model[1]];const modelDiscount=model&&model.hasOwnProperty("sale")?model.sale:0;const colorDiscount=carState.options.color[2].find(option=>option.color===carState.options.color[1]&&option.hasOwnProperty("sale"))?.sale||0;const wheelDiscount=carState.options.wheels[2].find(wheel=>wheel.color===carState.options.wheels[1])?.sale||0;const interiorColorDiscount=carState.options.interiorColor[2].find(option=>option.color===carState.options.interiorColor[1])?.sale||0;const runningBoardsDiscount=carState.options.runningBoards[0].filter(option=>option.show&&option.hasOwnProperty("sale")).reduce((totalDiscount,option)=>totalDiscount+(option.sale||0),0);const totalDiscount=modelDiscount+colorDiscount+wheelDiscount+interiorColorDiscount+runningBoardsDiscount;saleAll=numberWithSpaces(totalDiscount);return numberWithSpaces(totalDiscount)};async function updateCheck(){totalSaleCheck();checkDopOtionShow();checkDopOptions();discountCheck.style.display="none";priceItemDiscount.style.display="none";if(saleAll&&saleAll>0){console.log("SALE ALL 1",saleAll);discountCheck.style.display="flex";priceItemDiscount.style.display="flex"}else{console.log("SALE ALL 2",saleAll)}await sumCarPrices(updatedCarState,myPriceModels);totalpriceElements.forEach(e=>{e.innerHTML=sumCarPrices(carState,myPriceModels)});colorKuzovaElements.forEach(element=>{element.textContent=carState.options.color[1]});colorSalonaElements.forEach(element=>{element.textContent=carState.options.interiorColor[1]});diskElements.forEach(element=>{element.textContent=`${carState.options.wheels[1]}`});priceColorElements.forEach(element=>{element.textContent=` ${numberWithSpaces(carState.options.color[0])} руб.`});priceColorSalonElements.forEach(element=>{element.textContent=`${numberWithSpaces(carState.options.interiorColor[0])} руб.`});priceDiskElements.forEach(element=>{element.textContent=` ${numberWithSpaces(carState.options.wheels[0])} руб.`});totalSaleCarElements.forEach(element=>{element.innerHTML=saleAll===0||saleAll===null||saleAll===undefined?"Нет":`${saleAll} руб.`});totalPriceCarElements.forEach(element=>{element.textContent=`${sumCarPrices(carState,myPriceModels)} руб.`});document.querySelector(".check-list-image .swiper-slide").style.transform=""}function saveAllSlides(carousel){const allSlides=[];const slides=carousel.slides;slides.forEach(slide=>{allSlides.push(slide)});return allSlides}const indexColor=(value,searchBy="color")=>{if(searchBy==="color"){const index=carState.options.color[2].findIndex(e=>e.color===value);return index}else if(searchBy==="index"){if(value>=0&&value<carState.options.color[2].length){return carState.options.color[2][value].color}}return null};const indexOption=(property,value,searchBy="color")=>{const option=carState.options[property];if(Array.isArray(option)&&option.length>2&&Array.isArray(option[2])){if(searchBy==="color"){const index=option[2].findIndex(e=>e.color===value);return index}else if(searchBy==="index"){if(value>=0&&value<option[2].length){return option[2][value]}}}return null};const dopOptionsWrapper=document.querySelector(".dop-options-wrapper .elementor-widget-wrap");const children=dopOptionsWrapper.children;const updateWebsite=()=>{cargetModels.style.display="flex";if(cargetModels.children.length<=4){cargetModels.style.flexWrap="nowrap"}if(cargetModels.children.length>=5){cargetModels.style.flexWrap="wrap"}savedSlides.colorCarousel=colorCarousel.swiper?colorCarousel.swiper.slides:"";savedSlides.colorImageCarousel=colorImageCarousel.swiper?colorImageCarousel.swiper.slides:"";savedSlides.diskDiametr=diskDiametr.swiper?diskDiametr.swiper.slides:"";savedSlides.diskImage=diskImage.swiper?diskImage.swiper.slides:"";savedSlides.colorSalon=colorSalon.swiper?colorSalon.swiper.slides:"";savedSlides.salonImage=salonImage.swiper?salonImage.swiper.slides:"";originalColorOptions=[...carState.options.color[2]];originalWheelsOptions=[...carState.options.wheels[2]];originalInteriorColorOptions=[...carState.options.interiorColor[2]];carState.options.runningBoards[0].forEach((option,index)=>{const child=children[index];const checkbox=document.getElementById(child.id);const checkboxInput=checkbox.querySelector(`#${child.id}`);if(!option.check){checkboxInput.checked=true}});const m=document.querySelectorAll("#carget-models .elementor-column").length;let divisor;if(m===1){divisor=1}else if(m%2===0){divisor=2}else{divisor=3}document.querySelectorAll("#carget-models .elementor-column").forEach(e=>{e.style.width=`${96/divisor}%`});if(carState.options.wheels[3]===true&&diskDiametr.swiper){console.log("1");myArrowDiskImages=saveAllSlides(diskImage.swiper)}else if(carState.options.wheels[3]===false){console.log("2");myArrowDiskImages=colorImageCarousel.querySelector(".swiper-slide-active");document.querySelectorAll(arrayWrappers[1]).forEach(e=>{e.style.display="none"})}else{console.log("3");diskImage.swiper?myArrowDiskImages=saveAllSlides(diskImage.swiper):myArrowDiskImages=[diskImage.querySelector(".swiper-slide")]}checkDopOtionShow();closeAccordions();updateButtonState(carState);updateCheck(totalPrice);innerPriceHeader();innerPriceTitleModels();updateTitlePrice("updateWebsite");myPDF();document.querySelectorAll(".check-list-item-price-descr").forEach((e,index)=>{if(index!==0){e.innerHTML=""}else if(index===0){e.innerHTML="*Стоимость таможни может меняться в зависимости от выбранной комплектации, доп. опций и оценки таможни РФ"}})};const tableBody4=data4.map(item=>[{text:item,alignment:"left",fontSize:10,margin:[0,0,0,8]}]);const myPDF=async()=>{const image1=await loadImageAsDataURL(data5[0].img);const image2=await loadImageAsDataURL(data5[1].img);const image3=await loadImageAsDataURL(data5[2].img);const image4=await loadImageAsDataURL(data5[3].img);const data=[{label:"МОДЕЛЬ:",value:carState.model[0]},{label:"КОМПЛЕКТАЦИЯ:",value:carState.model[1]},{label:"ГОД ВЫПУСКА:",value:(new Date).getFullYear()},{label:"ЦВЕТ КУЗОВА:",value:carState.options.color[1]},{label:"ДИСКИ:",value:`${carState.options.wheels[2].length?carState.options.wheels[2][indexDisk].color:""}`},{label:"ЦВЕТ САЛОНА:",value:carState.options.interiorColor[1]}];const data2=[saleAll&&saleAll>0?{label:"СУММАРНАЯ СКИДКА:",value:`${saleAll} руб.`}:"",{label:"*СТОИМОСТЬ ТАМОЖНИ:",value:`${numberWithSpaces(roundNumberToNChars(pricecustomInRub[carState.model[1]],4,"data2"))} руб.`},{label:saleAll&&saleAll>0?"ИТОГОВАЯ СТОИМОСТЬ\nс учетом скидки:":"ИТОГОВАЯ СТОИМОСТЬ",value:`${numberWithSpaces(totalPrice)} руб.`},{label:"СТОИМОСТЬ С НДС:",value:`${numberWithSpaces(calculateWithPercentage(totalPrice,22))} руб.`},{label:"СРОК ПОСТАВКИ:",value:"30-60 ДНЕЙ"}];const runningBoards=carState.options.runningBoards[0];const filteredLabels=runningBoards.filter(label=>label.show);const optionsText=filteredLabels.map(label=>label.title).join(", ");const complectList=modelElements[carState.model[1]].model[0].querySelectorAll(".accordion-ul-items-complect li");const descriptionList=modelElements[carState.model[1]].model[0].querySelectorAll(".accordion-ul-items-description li");function extractTextFromList(list){console.log("Array.from(list)",Array.from(list));return Array.from(list).map(item=>{const text=item.innerHTML.trim();const cleanedText=text.replace(/<[^>]*>/g,"").replace(/\n+/g," ").replace(/\s+/g," ");return cleanedText.trim()})}const complectData=extractTextFromList(complectList);const descriptionData=extractTextFromList(descriptionList);const tableBodycomplectData=complectData.map(item=>[{text:item,alignment:"left",fontSize:10,margin:[0,0,0,8]}]);const tableBodydescriptionData=descriptionData.map(item=>[{text:item,alignment:"left",fontSize:10,margin:[0,0,0,8]}]);const tableBody=data.map(({label,value})=>[{text:label,alignment:"left",border:[0,0,0,0],fontSize:10,margin:[2,4,2,4]},{text:value,alignment:"left",border:[0,0,0,0],margin:[-16,4,2,4],fontSize:10,bold:true}]);const tableBody2=data2.map(({label,value})=>[{text:label,alignment:"left",border:[0,0,0,0],fontSize:10,margin:[0,0,-64,0]},{text:value,alignment:"left",border:[0,0,0,0],fontSize:10,bold:true,margin:[40,0,0,0]}]);var pdfContent={defaultFileName:`${carState.model[0]} ${carState.model[1]}.pdf`,pageOrientation:"portrait",pageSize:{width:600,height:1e3},pageMargins:[32,64,32,64],info:{title:`${carState.model[0]} ${carState.model[1]}`,author:"CARGET",keywords:["CARGET",`${carState.model[0]} ${carState.model[1]}`]},header:{columns:[{image:await loadImageAsDataURL(arrayImagesForPDF[0]),width:196,height:40,margin:[16,16,0,0]},{text:"CARGET.SU\nГ. МОСКВА, УЛ. КУЛАКОВА Д.20 К1, ОФ.213\nООО «ВОСТОКИМПОРТ»",alignment:"right",margin:[0,16,16,0],height:40,fontSize:10}]},footer:{columns:[{text:"CARGET.SU",alignment:"left"},{text:"ООО «ВОСТОКИМПОРТ»",alignment:"center"},{text:"+7 996 410-01-87",alignment:"right"}],margin:[16,16,16,16]},content:[{canvas:[{type:"rect",x:-16,y:0,w:563,h:.5,color:"#000000"}]},{text:"КОММЕРЧЕСКОЕ ПРЕДЛОЖЕНИЕ",fontSize:22,alignment:"center",margin:[32,32,32,8],bold:true},{text:`${carState.model[0]} ${carState.model[1]}`,fontSize:18,margin:[0,0,0,8],alignment:"center",bold:true},{text:"Предлагаем Вам рассмотреть возможность приобретения данного автомобиля.\nС комплектацией, стоимостью и условиями Вы можете ознакомиться ниже",fontSize:10,margin:[0,8,0,32],alignment:"left"},{columns:[{margin:[0,0,0,0],table:{widths:[120,120],body:tableBody}},{margin:[0,0,0,0],table:{widths:["*","*"],marginTop:-100,body:[[{text:"ДОП. ОПЦИИ:",alignment:"left",border:[0,0,0,0],fontSize:9,margin:[4,4,0,4]},{border:[0,0,0,0],text:""}],[{text:"",alignment:"left",border:[0,0,0,0],fontSize:9,margin:[4,4,4,4]},{fontSize:10,border:[0,0,0,0],stack:optionsText!==""?[{text:optionsText,border:[0,0,0,0]}]:[{text:"Нет",border:[0,0,0,0]}],margin:[-130,0,4,4]}],...tableBody2,[{text:"",border:[0,0,0,0],margin:[0,26,0,0]},{text:"*Стоимость таможни может меняться в зависимости от выбранной комплектации, доп. опций и оценки таможни РФ.",border:[0,0,0,0],fontSize:8,margin:[-132,16,16,0]}]]}}]},{image:await loadImageAsDataURLWithLogging(arrayImagesForPDF[1]),width:400,margin:[0,32,0,0],alignment:"center"},{image:await loadImageAsDataURLWithLogging(arrayImagesForPDF[2]),width:340,margin:[0,16,0,0],alignment:"center",pageBreak:"after"},{text:`КОМПЛЕКТАЦИЯ - ${carState.model[0]} ${carState.model[1]}`,margin:[0,32,0,16],fontSize:16,bold:true},{ul:tableBodycomplectData,margin:[0,0,0,16]},{ul:tableBodydescriptionData,margin:[0,0,0,16]},{text:"ПОЧЕМУ СТОИТ ВЫБРАТЬ CARGET?",margin:[0,32,0,16],fontSize:16,bold:true},{ul:tableBody4},{margin:[0,32,0,32],canvas:[{type:"rect",x:-16,y:0,w:563,h:.5,color:"#000000"}]},{text:"ПО ВСЕМ ИНТЕРЕСУЮЩИМ ВОПРОСАМ\nБУДЕМ РАДЫ ВАМ ОТВЕТИТЬ:",margin:[0,0,0,16],fontSize:16,bold:true},{columns:[[{image:image1,width:24,height:24,margin:[0,0,0,16]},{text:data5[0].contact,alignment:"left",fontSize:12,margin:[32,-36,0,16]}],[{image:image2,width:24,height:24,margin:[0,0,0,16]},{text:data5[1].contact,alignment:"left",fontSize:12,margin:[32,-36,0,16]}],[{image:image3,width:24,height:24,margin:[0,0,0,16]},{text:data5[2].contact,alignment:"left",fontSize:12,margin:[32,-36,0,16]}],[{image:image4,width:24,height:24,margin:[0,0,0,16]},{text:data5[3].contact,alignment:"left",fontSize:12,margin:[32,-36,0,16]}]]}],styles:{header:{fontSize:14,color:"#222222",bold:false}}};pdfDoc=pdfMake.createPdf(pdfContent)};let testEvent;const handleColorCarouselChange=async e=>{testEvent=e;colorCarousel.swiper.params.centeredSlides=true;colorCarousel.swiper.params.slideToClickedSlide=true;colorCarousel.swiper.update();if(isUpdatingCarousel){return}try{isUpdatingCarousel=true;colorImageCarousel.swiper.enable();let currentColor,currentPrice;const indexOffset=carState.options.color[2].length<=1?0:e.realIndex;const slideResult=colorImageCarousel.swiper.slideTo(e.realIndex+1,400);if(slideResult){const index=indexOffset;colorImageCarousel.swiper.slideTo(e.realIndex+1,400);const colorOption=await indexOption("color",index,"index");currentColor=colorOption.color;currentPrice=colorOption.price}else{colorImageCarousel.swiper.slideTo(e.realIndex+2,400);const index=indexOffset+1;const colorOption=await indexOption("color",index,"index");currentColor=colorOption.color;currentPrice=colorOption.price}carState.options.color[0]=currentPrice;carState.options.color[1]=currentColor;updateOptions(carState.model[1],"handleColorCarouselChange");colorCarousel.querySelectorAll(".elementor-swiper-button").forEach(button=>{button.style.display=colorCarousel.swiper.slides.length<=1?"none":"inline-flex"});colorImageCarousel.swiper.disable();isUpdatingCarousel=false}catch(error){console.error("Ошибка в обработчике события handleColorCarouselChange:",error);isUpdatingCarousel=false}};async function loadConfigutation(){const waitForSlider=(maxAttempts=50,interval=100)=>{return new Promise((resolve,reject)=>{let attempts=0;resolve();const checkSlider=()=>{if(colorCarousel&&colorCarousel.swiper){resolve()}else{attempts++;if(attempts>=maxAttempts){console.error("Слайдер не инициализировался за максимальное количество попыток.");reject(new Error("Слайдер не инициализировался за максимальное количество попыток."))}else{setTimeout(checkSlider,interval)}}}})};try{await waitForSlider();hideLoader();updateDopOptions();fetchCurrencyRates().then(()=>{updatedCarState=convertCarState(carState);if(updatedCarState){myPriceModels=sumCarModelsPrices(updatedCarState)}if(myPriceModels){sumCarPrices(updatedCarState,myPriceModels);updateWebsite();colorSalon.swiper?colorSalon.swiper.slideTo(0):"";myPDF();clearInterval(textChangeInterval)}});if(colorCarousel&&colorCarousel.swiper){colorCarousel.swiper.on("activeIndexChange",handleColorCarouselChange)}if(colorSalon&&colorSalon.swiper){colorSalon.swiper.params.centeredSlides=true;colorSalon.swiper.params.slideToClickedSlide=true;colorSalon.swiper.update();colorSalon.swiper.on("activeIndexChange",async e=>{try{salonImage.swiper.enable();const currentColor=indexOption("interiorColor",e.realIndex,"index")?indexOption("interiorColor",e.realIndex,"index").color:"";const currentPrice=indexOption("interiorColor",e.realIndex,"index")?indexOption("interiorColor",e.realIndex,"index").price:"";let activeSlideAlt;if(colorSalon.querySelector(".swiper-slide-active img")){activeSlideAlt=colorSalon.querySelector(".swiper-slide-active img")?colorSalon.querySelector(".swiper-slide-active img").alt:""}else{setTimeout(()=>{activeSlideAlt=colorSalon.querySelector(".swiper-slide-active img").alt},1e3)}const slideIndex=findSlideIndexByAlt(colorSalon,activeSlideAlt);carState.options.interiorColor[0]=currentPrice;carState.options.interiorColor[1]=currentColor;if(slideIndex!==-1){salonImage.swiper.slideTo(e.realIndex+1,400)}updateTitlePrice("colorSalon.swiper.on");colorSalon.querySelectorAll(".elementor-swiper-button").forEach(e=>{if(colorSalon.swiper.slides.length<=1){e.style.display="none"}else{e.style.display="inline-flex"}});salonImage.swiper.disable()}catch(error){console.error("Error in diskDiametr activeIndexChange event:",error)}})}if(diskDiametr&&diskDiametr.swiper){diskDiametr.swiper.params.centeredSlides=true;diskDiametr.swiper.params.slideToClickedSlide=true;diskDiametr.swiper.update();diskDiametr.swiper.on("activeIndexChange",async e=>{diskImage.swiper.enable();try{const currentColor=indexOption("wheels",e.realIndex,"index").color;const currentPrice=indexOption("wheels",e.realIndex,"index").price;let activeSlideAlt=null;if(diskDiametr){const activeSlide=diskDiametr.querySelector(".swiper-slide-active img");if(activeSlide){activeSlideAlt=activeSlide.alt}}const slideIndex=findSlideIndexByAlt(diskDiametr,activeSlideAlt);if(slideIndex!==-1){carState.options.wheels[0]=currentPrice;carState.options.wheels[1]=currentColor;diskImage.swiper.slideTo(e.realIndex+1,400);updateTitlePrice("diskDiametr.swiper.on");diskImage.swiper.disable()}}catch(error){console.error("Error in diskDiametr activeIndexChange event:",error)}})}document.querySelectorAll(".generate-pdf").forEach(e=>{e.addEventListener("click",async function(){e.style.opacity="0.4";e.style.pointerEvents="none";await myPDF();if(pdfDoc){pdfDoc.download(`${carState.model[0]} ${carState.model[1]}.pdf`);setTimeout(()=>{e.style.opacity="1";e.style.pointerEvents="auto"},200)}})})}catch(error){console.error("Ошибка инициализации:",error)}}const initializeModels=()=>{if(carState&&carState.models){modelNames=carState.models.map(model=>Object.keys(model)[0]);modelElements=defineModelElements(carState.models);modelNames.forEach(modelName=>{divPriceModels[modelName]=createDivPriceModel(modelName);createAndAttachButtonClickHandler(modelName)});carState.options.color[1]===""?(selectedColor=carState.options.color[2][0].color,carState.options.color[1]=carState.options.color[2][0].color):selectedColor=carState.options.color[1];carState.options.interiorColor[1]===""?carState.options.interiorColor[1]=carState.options.interiorColor[2][0].color:"";if(carState.options.wheels[3]){carState.options.wheels[1]===""?carState.options.wheels[1]=carState.options.wheels[2][0].color:""}}else{console.error("carState или carState.models не определены.")}};function deepCopy(obj){if(typeof obj!=="object"||obj===null){return obj}const copy=Array.isArray(obj)?[]:{};for(const key in obj){copy[key]=deepCopy(obj[key])}return copy}function isCarStateFresh(){const key=document.title;const serial