define(["jquery","knockout","ccRestClient","ccConstants","pubsub","CCi18n","notifier","spinner","ccStoreConfiguration","navigation","storageApi","swmRestClient","/file/thirdparty/libraries/nouislider.min.js","/file/thirdparty/libraries/wNumb.js","ccLogger","/file/thirdparty/libraries/jquerymask.js","moment","ccNumber"],function(e,t,n,r,i,s,o,u,a,f,l,c,h,p,d,v,m,g){"use strict";var y,b="bf-corporativo",w={GENERAL:{BASE_URL:"/ccstorex/custom"},PAYMENT:{URL:"/v1/khipu/payments"},PAYMENT_STATE:{URL:"/v1/khipu/payments/state"}},E={NAMES:{automovilNuevo:"Automovil",automovilUsado:"automovil-usado",kitSeguridad:"kit-seguridad",mantencion:"Mantenciones"},CODIGO_AUTOSYSTEM:{automovilNuevo:"1",automovilUsado:"2",mantencion:"3"}},S={NAMES:{lista:"pg_precioLista",bonoDeMarca:"pg_bonoDeMarca",financiadoConvencional:"pg_financiadoConvencional",financiadoInteligente:"pg_financiadoInteligenteBF",precioReservaWeb:"pg_reservaWeb"},LOWER_PRICE:"precioMasBajo",HAS_FUNDING:"tieneFinanciamiento",DISCOUNT_PERCENT:"porcentajeDescuento",DISCOUNT_AMOUNT:"montoDescuento"},x={timeOutInstance:undefined,RANGE_COLLECTION_COOKIE:"OCS_refinementsCollectionID",RANGE_FILTERS_TIMEOUT:5e3,RANGE_FILTERS_DATA:{"product.priceRange":{elementId:"ocs-precio",elementIdMobile:"ocs-precio-mobile",format:p({decimals:3,thousand:".",prefix:"$"}),step:1e6,connect:!0,decimals:0,urlParamValue:"product.listPrice"},"product.x_agno":{elementId:"ocs-agno",elementIdMobile:"ocs-agno-mobile",format:{to:function(e){return Math.round(e)},from:function(e){return e}},step:1,connect:!0,urlParamValue:"product.x_agno"}},DIMENSION_NAMES:{"ocs-precio":{dimensionName:"product.listPrice"},"ocs-agno":{dimensionName:"product.x_agno"},"ocs-precio-mobile":{dimensionName:"product.listPrice"},"ocs-agno-mobile":{dimensionName:"product.x_agno"}}},T={CATEGORY_ID:undefined},N={CATEGORY_ID:undefined,CART_PRODUCTS:undefined,CART_PRODUCTS_COOKIE_NAME:"OCS_comparator_cart_products",PRODUCTS_FIELDS:"displayName,listPrice,id,primarySmallImageURL,x_combustible,x_cilindrada,x_modelo,x_potencia,x_transmision,x_traccion,x_radio,x_mandoAlVolante,x_aireAcondicionado,x_llantas,x_alzavidriosElectrico,x_neblineros,x_espejosElectricos,x_aBS,x_airbag,x_controlDeEstabilidad,x_sensorDeRetroceso,x_iSOFIX,x_carreteraKmL,x_ciudadKmL,x_mixtoKmL",ADD_PRODUCT_TEMPLATE:"
+
"},C={CATEGORY_ID:undefined,CATEGORY_ID_COOKIE_NAME:"ocs-sucursales-category-id",CATEGORY_ID_PARAM_NAME:"brand"},k={TOPIC_OPEN_SIDEFORM_NAME:"ocs-cotizar-open-side-form"},L={collectionId:"autos-usados",automovil:{collectionId:"autos-usados-automoviles"},suvYStationWagon:{collectionId:"autos-usados-suv-y-station-wagon"},camionetasYComerciales:{collectionId:"autos-usados-camionetas-y-comerciales"}},A={LOADED_SECTIONS:{galery:t.observable(!1),view360:t.observable(!1),videoReview:t.observable(!1),comparatorTable:t.observable(!0),downloads:t.observable(!1),versionAvailable:t.observable(!0)}},O={ORDER_TO_CHECKOUT:{patente:undefined,sucursal:undefined,sucursal_id:undefined,fecha:undefined,hora:undefined,mensaje:undefined,rut:undefined,motherLastName:undefined,phone:undefined,phone_cod:undefined},COOKIE_NAME:"ocs-fecha-cookie"},M=[{field:"x_highlightTag",type:"boolean",highlightTag:!0},{field:"x_garantia_de_fabrica_vigente",type:"boolean",label:"Garantía de Fábrica",icon:"/file/general/icon_garantia.svg",iconBlack:"/file/general/icon_garantia_black.svg"},{field:"x_combustible",type:"string",values:[{label:"Eléctrico",diccionary:"electrico,eléctrico",icon:"/file/general/hibrid-icon-fullgreen.svg",iconBlack:"/file/general/hibrid-icon-fullgreen.svg"},{label:"Diesel",diccionary:"diesel,diésel",icon:"/file/general/icon_diesel.svg",iconBlack:"/file/general/icon_diesel_black.svg"},{label:"Híbrido",diccionary:"hibrido,híbrido",icon:"/file/general/hibrid-icon-fullgreen.svg",iconBlack:"/file/general/hibrid-icon-fullgreen.svg"}]},{field:"x_kilometraje",type:"formula",label:"Pocos Kilómetros",icon:"/file/general/icon_kilometraje.svg",iconBlack:"/file/general/icon_kilometraje_black.svg",formula:function(e,t){var n=!1,r,i;try{t=="searchResult"?(r=e["product.x_kilometraje"](),i=e["product.x_agno"]()):(r=e.x_kilometraje(),i=e.x_agno());if(parseInt(r)<=5e4){var s=(new Date).getFullYear()-parseInt(i);n=parseInt(r)/(s!==0?s:1)<=1e4}}catch(o){console.log(o)}return n}},{field:"x_unico_dueno",type:"boolean",label:"Único Dueño",icon:"/file/general/icon_unico_dueno.svg",iconBlack:"/file/general/icon_unico_dueno_black.svg"}],_=function(e,t){var n=new URLSearchParams(t);return n.delete(e),n.toString()},D={},P=function(e){var t,n,r;return Array.isArray(e)||(e=[e]),e.forEach(function(e,i){var s=e.salePrices.pg_financiadoInteligenteBF||e.salePrices.pg_financiadoConvencional||e.salePrices.pg_bonoDeMarca||e.listPrices.pg_financiadoInteligenteBF||e.listPrices.pg_financiadoConvencional||e.listPrices.pg_bonoDeMarca||0,o=e.salePrices.pg_precioLista||e.listPrices.pg_precioLista,u=Math.floor((o-s)*100/o);i===0?(t=s?s:o,n=s?o-s:0,r=u):(t=s&&sn?o-s:n,r=u>=r?u:r)}),{lowerPrice:t,maxDiscount:n,maxPercentage:r}},H=function(t,n,r,i){i?e(t).parent().hide():!n&&r?(e(t).parent().hide(),e(t.parentElement.parentElement.parentElement).find(".txt-fin").hide()):e(t).text(j.utils.product.parsePrice(n))},B=function(e,t,n,r,i){var s=function(e,t){return t?e.maxPercentage'),y.addCustomBindings(),y.overrideCommerceFunctions(),y.storeConfiguration.enablePrioritizedLoading=!0,y.createValidationRules(),e.Topic(i.topicNames.PAGE_CHANGED).subscribe(y.executeWhenPageChange),e.Topic(i.topicNames.PRODUCT_VIEWED).subscribe(function(e){if(e&&e.type()===j.CCConstants.PRODUCT_TYPES.AUTO_USADO)if(window.localStorage.getItem("PRODUCTS_VIEWED")){var t=window.localStorage.getItem("PRODUCTS_VIEWED").split(",");t.includes(e.id())||(t.length>=10?(t.shift(),window.localStorage.setItem("PRODUCTS_VIEWED",t.join(",")+","+e.id())):window.localStorage.setItem("PRODUCTS_VIEWED",window.localStorage.getItem("PRODUCTS_VIEWED")+","+e.id()))}else window.localStorage.setItem("PRODUCTS_VIEWED",e.id())}),e.Topic(i.topicNames.PAGE_CHANGED).subscribe(function(n){var r=t.contextFor(e("#main")[0]),i=r.$data.data.global.pageContext.page.displayName;for(var s=0;s0){var r=n.attr("class").split(" "),i=s(r,t);n.removeClass(i.join(" ")).addClass(t.join(" "))}return n},n.request(r.ENDPOINT_SITES_GET_SITE,{},function(e){var t={currencyObj:e.defaultPriceListGroup.currency,siteSettings:{}};for(var n in e.siteSettings)t.siteSettings[n]=e.siteSettings[n];j.siteInfo(t),j.CCConstants.urlNoImage=e.noimage},function(e){d.error("site failed",e)},siteId),n.request(r.ENDPOINT_GET_ITEM_TYPE,{parent:"contactInfo"},function(t){j.utils.cache("CONTACT_INFO",t.specifications),j.CONTACT_INFO=t.specifications,e.Topic("CONTACT_INFO").publish(t.specifications)},function(e){o.sendError("Se produjo un error.")},r.ENDPOINT_CONTACT_INFO_TYPE),j.isMobile(window.innerWidth<768),window.onresize=function(){var t=j.isMobile(),n=window.innerWidth<768;t!=n&&(j.isMobile(n),e.Topic(j.CCConstants.TOPICS.IS_MOBILE).publish(n))},e.ajaxSetup({headers:{flow_id:localStorage.getItem("flow_id")}})},showHighlyViewed:function(e,t){var n=(new Date(e)).getTime(),r=(new Date).getTime(),i=r-n,s=i/864e5,o=parseInt(t)/s;return o>=50&&parseInt(t)>20},populateHighlightProperties:function(e,n){e.highlightProperties=t.observableArray([]);for(var r=0;r0&&t)for(var i=0;i goTo] -> No data")}},t.bindingHandlers.mask={init:function(n,r){var i={mask:"",reverse:!1,placeholder:!1,sufix:null,prefix:null},s=t.toJS(typeof r=="function"?r():r);typeof s=="string"&&(s={mask:s});var o=e.extend(i,t.toJS(s)),u={reverse:o.reverse,translation:{"*":{pattern:/^[\w\d]{1}$/}}};o.prefix&&(u.translation[o.prefix]={pattern:new RegExp(o.prefix),fallback:o.prefix,optional:!1},o.mask=o.mask+o.prefix),o.sufix&&(u.translation[o.sufix]={pattern:new RegExp(o.sufix),fallback:o.sufix,optional:!1},o.mask=o.mask+o.sufix),e(n).mask(o.mask,u),o.placeholder&&e(n).attr("placeholder",o.mask)}},t.bindingHandlers.focusWhen={update:function(e,t){var n=t();n&&(j.isMobile()?setTimeout(function(){e.focus(),e.scrollIntoView({behavior:"smooth",block:"center"})},25):setTimeout(function(){e.focus()},25))}},t.bindingHandlers.showTags={update:function(t,n){var r=n();try{var i=[];if(r.tags){i=r.tags.split("-");if(r.tags.length>0)for(var s=0;s';e("head").append(r),e(n).html(o),i.push(s.id)}},fail:function(e){d.error("[YT_VIDEO] -> Error obteniendo metadata:",e)}}))}},t.bindingHandlers.ocs_calendar={update:function(n,r){var i=r();t.isObservable(i)&&(i=i());if(!i)return;e(n).datepicker("destroy");var s={start:null,end:null,daysDisabled:[],target:null,autoSelectFirstDate:!1,onChange:function(){}};i=e.extend(s,i),i.start&&(i.start=m(i.start).format("DD/MM/YYYY")),i.end&&(i.end=m(i.end).format("DD/MM/YYYY")),e.fn.datepicker.dates.es={days:["Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado"],daysShort:["DOM","LUN","MAR","MIE","JUE","VIE","SAB"],daysMin:["DOM","LUN","MAR","MIE","JUE","VIE","SAB"],months:["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],monthsShort:["Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic"],today:"Hoy",clear:"Borrar",format:"dd/mm/yyyy",titleFormat:"MM yyyy",weekStart:0},e(n).datepicker({format:"dd-mm-yyyy",maxViewMode:2,todayBtn:!1,startDate:i.start,endDate:i.end,language:"es",orientation:"bottom auto",daysOfWeekDisabled:i.daysDisabled,autoclose:!0,todayHighlight:!0,templates:{leftArrow:'',rightArrow:''}}).on("show",function(e){}).on("changeDate",function(){var r=e(n).datepicker("getFormattedDate");i.target&&t.isObservable(i.target)&&i.target(r),i.onChange&&i.onChange(r)}),i.autoSelectFirstDate&&e(n).datepicker("setDate",i.start)}},t.bindingHandlers.ocs_price={update:function(n,r,i){var s=t.toJS(r()),o;i().parseFree&&!s?o="GRATIS":(o=j.utils.product.parsePrice(s),i().prefix&&(o=i().prefix+o)),n.tagName=="INPUT"?e(n).val(o):e(n).text(o)}},t.bindingHandlers.ocs_reserva={update:function(t,n){var r=j.utils.siteSetting("x_SiteSetting_GeneralSettings","reserevAmount");e(t).text(j.utils.product.parsePrice(r))}},t.bindingHandlers.ocs_brandLogo={update:function(t,n){var r=j.utils.siteSetting("x_SiteSetting_GeneralSettings","brandLogos"),i=typeof n=="function"?n():n;if(!r||!r[i.brand.toUpperCase()]){console.error("error obteniendo logo de marca "+i.brand.toUpperCase());return}var s=i.logo?r[i.brand.toUpperCase()].logo:r[i.brand.toUpperCase()].logo_cuadrado;e(t).attr("src",s)}},t.bindingHandlers.ocs_categoryLowerPrice={update:function(e,n){var r=t.toJS(n());B(r,e,"lowerPrice",!1)}},t.bindingHandlers.ocs_categoryHighestDiscount={update:function(e,n,r){var i=t.toJS(n());B(i,e,"maxDiscount",r().hideIfNull,r().ocs_discountValidate)}},t.bindingHandlers.ocs_productLowerPrice={update:function(e,n){var r=t.toJS(n());if(r.listPrices){var i=P([r]);H(e,i.lowerPrice)}}},t.bindingHandlers.ocs_productHighestDiscount={update:function(e,n,r){var i=t.toJS(n());if(i.listPrices){var s=P([i]);H(e,s.maxDiscount)}}}},overrideCommerceFunctions:function(){f.goTo=function(t,s,o){window.scrollTo(0,0);var u=f.getPathWithLocale(t),a=n.profileType==r.PROFILE_TYPE_AGENT?window.applicationContextPath:"";a.length>0&&u.indexOf(a)!=0&&(u=a+u);if(s)e.Topic(i.topicNames.HISTORY_PUSH_STATE).publish(u);else if(window.history&&window.history.pushState)o?window.history.replaceState(null,"",u):window.history.pushState(null,"",u),e.Topic(i.topicNames.HISTORY_PUSH_STATE).publish(u),f.checkLogin&&f.checkLogin(t);else{var l=f.getBaseURL()+(u.charAt(0)==="/"?u:"/"+u);window.location.assign(l)}}},executeWhenPageChange:function(e){y.determineIfIsLayoutWithBrandingStyle(e)},layoutHasBrandingStyle:t.observable(),determineIfIsLayoutWithBrandingStyle:function(e){var t,n=e.pageId;t=n==="category"||n==="product"||n==="searchresults"||n==="noSearchResults"||n==="comparador"||n==="cart"||n==="checkout",y.layoutHasBrandingStyle(t)},collectionTree:t.observableArray(),collectionTreeLoading:!1,collectionTreeLoaded:!1,collectionTreeLoadedCallbacks:[],loadCollectionTree:function(e,n){if(!y.collectionTreeLoaded&&!y.collectionTreeLoading&&e&&n){y.collectionTreeLoading=!0;var i=t.observable("cloudCatalog"),s=t.observable("rootCategory");y.collectionTree.isdata=!0,e.catalog!=undefined&&(i(e.catalogId.repositoryId),e.catalog.rootCategories!=undefined&&e.catalog.rootCategories.length>0&&s(e.catalog.rootCategories[0].id));var o={},u={};u[r.ENDPOINT_KEY]=r.ENDPOINT_COLLECTIONS_GET_COLLECTION,u[r.IDENTIFIER_KEY]="categoryNavigation";var a=y.storeConfiguration.getFilterToUse(u);a&&(o[r.FILTER_KEY]=a),n("categoryList",[s(),i(),r.CATALOG_MAX_LEVEL,""],o,function(e){y.collectionTreeLoading=!1,y.collectionTreeLoaded=!0,y.collectionTree(e),y.collectionTreeLoadedCallbacks.forEach(function(e){e()}),y.collectionTreeLoadedCallbacks=[]},y)}else y.collectionTreeLoaded&&y.collectionTree(y.collectionTree())},completeCollection:t.observable(),getCompleteCollection:function(e){var t;if(e){var n=function(){for(var n=0;n0||!Array.isArray(e))){var s=Array.isArray(e)?e.toString():e,o=function(e){y.collectionImagesCache.push({request:s,response:e})},u=function(e){var t;return y.collectionImagesCache.forEach(function(n){n.request==e&&(t=n.response)}),t},a=u(s);if(a)t(a);else{var f={},l=function(e){o(e),t(e)};f[r.FIELDS_QUERY_PARAM]="categoryImages,id,route",f[r.CATEGORY_IDS]=s,n.request(r.ENDPOINT_LIST_COLLECTIONS,f,l,i)}}},getFirstLevelCategoryId:function(e){var t,n,r,i;return e&&e.categoryIdPaths&&e.categoryIdPaths[0]&&(n=e.categoryIdPaths[0],r=n.split(">"),i=r[1],i&&(t=i)),t},isFirstLevelCategory:function(e){var t,n,r;return e&&e.categoryIdPaths&&e.categoryIdPaths[0]&&(n=e.categoryIdPaths[0],r=n.split(">"),t=r.length==2),t},getProducts:function(e,t,i,s){var o=r.ENDPOINT_PRODUCTS_LIST_PRODUCTS,u={};u[r.PRODUCT_IDS]=e,t&&(u[r.FIELDS_QUERY_PARAM]=t),n.request(o,u,function(e){i(e)},function(e){s(e)})},getProductsFromCategory:function(e,t,i,s,o){if(e&&i&&s){var u=r.ENDPOINT_PRODUCTS_LIST_PRODUCTS,a={};a[r.CATEGORY]=e,t&&(a[r.FIELDS_QUERY_PARAM]=t),o&&(a[r.SORTS]=o),n.request(u,a,i,s)}},getDimensionsIds:function(e,t,i){var s={};s.fields="dimensionId",s[r.CATEGORY_IDS]=e,n.request(r.ENDPOINT_LIST_COLLECTIONS,s,t,i)},getBrandFromProduct:function(e,n){if(e&&e.brand){var r;if(t.isObservable(e.brand)){if(e.brand()&&typeof e.brand()=="string"||e.brand()instanceof String)r=e.brand().toLowerCase()}else if(typeof e.brand=="string"||e.brand instanceof String)r=e.brand.toLowerCase()}n(r)},loadCategoryDataFromProductParent:function(e,t){var n,r,i,s,o=!1,u=e.parentCategories()[0].id(),a=function(e){for(var a=0;e.length>a;a++){n=e[a];if(n.childCategories)for(var f=0;n.childCategories.length>f;f++){r=n.childCategories[f];if(r.childCategories)for(var l=0;r.childCategories.length>l;l++){i=r.childCategories[l];if(!o&&i.id===u){t(n),o=!0;break}}}}o||t(undefined),s&&s.dispose()};y.collectionTree().length>0?a(y.collectionTree()):s=y.collectionTree.subscribe(a)},getCSVFile:function(t,n,r){var i=function(t){e.ajax({type:"GET",url:t,dataType:"text",success:n,error:r})},s=function(e){e!=undefined&&console.error(e.message)};t&&n?y.getThirdPartyFileUrl(t,i,s):r?r({message:"Error to obtain CSV file."}):console.error("Error to obtain CSV file.")},getThirdPartyFileUrl:function(e,t,r){e&&t?n.request("getFileURLs",{filePaths:["/thirdparty/libraries/"+e+".csv"]},function(n){n&&n["/thirdparty/libraries/"+e+".csv"]&&t(n["/thirdparty/libraries/"+e+".csv"])},function(e){r({message:"Error to obtain third party file URL."})}):errorCallback?errorCallback({message:"Error to obtain third party file."}):console.error("Error to obtain third party file.")},getAllPrices:function(e,i,s,o){var u,a=!1,f,l,c,h,p,d,v,m={},g=function(e){e!=undefined&&console.error("Error retrieving prices products: ",e.message)},y=function(n){l=n.listPrices,d=l[S.NAMES.lista],d&&(m[S.NAMES.lista]=d,u=d),p=l[S.NAMES.bonoDeMarca],p&&(m[S.NAMES.bonoDeMarca]=p,p0?e["product.repositoryId"][0]:undefined),f?n.request(r.ENDPOINT_PRODUCTS_GET_PRODUCT,{fields:"listPrices,salePrices"},y,g,t.isObservable(f)?f():f):o?o({message:"Error retrieving prices products, verify parameters."}):g({message:"Error retrieving prices products, verify parameters."}))},buildAllPrices:function(e,n){var r=t.toJS(e),i,s=!1,o,u,a,f,l,c,h={};o=r.listPrices,l=o[S.NAMES.lista],l&&(h[S.NAMES.lista]=l,i=l),f=o[S.NAMES.bonoDeMarca],f&&(h[S.NAMES.bonoDeMarca]=f,f0&&(h.childSKUs=[t.selectedSku()]),h.orderQuantity=parseInt(t.itemQuantity(),10);var p=t.itemQuantityInCart(h),d=h.orderLimit&&h.orderLimitd){var v=s.t("ns.OCS_productDetailsUsedCar:resources.totalItemQuantityExceeded",{stockAvailable:d,itemQuantityInCart:p});o.sendError(t.WIDGET_ID,v,!0);return}var m=function(){var t=e.Topic(i.topicNames.CART_ADD_SUCCESS).subscribe(function(e){f.goTo(r.CHECKOUT),t.unsubscribe()});e.Topic(i.topicNames.CART_ADD).publishWith(h,[{message:"success"}])};if(t.cart().allItems().length>0){var g=function(e){m(),y.unsubscribe(g)},y=e.Topic("OCS_CART_EMPTY_SUCCESS").subscribe(g);t.cart().emptyCart(),t.cart().removeCurrentProfileOrder_OCS()}else m();t.isAddToCartClicked(!0),setTimeout(b,3e3),t.isInDialog()&&e(".modal").modal("hide")},getUrlParameter:function(e){var t=new URLSearchParams(window.location.search);return t.getAll(e)},checkIfExistAnyNfParameter:function(){var e=[],t=y.getUrlParameter(r.SEARCH_RANGE_FILTER),n,i,s,o;for(var u=0;u0){var n,r,i,s,o,u,a=e.refinements();for(var f=0;a.length>f;f++)n=a[f],n&&n.properties&&(r=n.properties,i=r["dimval.prop.lowerBound"]?r["dimval.prop.lowerBound"]:r["DGraph.Spec"],i=Math.abs(i),s=r["dimval.prop.upperBound"]?r["dimval.prop.upperBound"]:r["DGraph.Spec"],s=Math.abs(s),f===0?(u=i,o=s):(io?o=s:undefined)),n=undefined,r=undefined,i=undefined,s=undefined;t.lowerBound=u,t.upperBound=o}return t},rangeRefinementTriggered:function(e){var t=y.pageContext().pageType.id,n=window.location.pathname+window.location.search;switch(t){case"searchResultsPageType":y.applyRangesFromSearch(e);break;case"categoryPageType":y.applyRangesFromCategory(e);break;default:y.applyRangesFromOther(e)}},applyRangesFromSearch:function(e){var t=y.getStringToUrl(e),n="";n+=window.location.pathname,n+="?"+_("Nf",window.location.search),n+=t,f.goTo(n)},applyRangesFromCategory:function(e){var t=y.getStringToUrl(e);f.goTo(r.SEARCH_RESULTS_HASH+"?"+r.SEARCH_TYPE+"="+r.SEARCH_TYPE_GUIDED+"&"+r.PARAMETERS_TYPE+"="+r.PARAMETERS_SEARCH_QUERY+t+"&"+r.SEARCH_SORT_ORDER+"="+"sku.activePrice|1")},applyRangesFromOther:function(e){y.applyRangesFromCategory(e)},removeCustomRefinement:function(e){var t=window.location.pathname,n=e.dimensionName,i=window.location.search,s=new URLSearchParams(i);if(e.isRangeRefinement&&s.has(r.SEARCH_RANGE_FILTER)){var o=s.get(r.SEARCH_RANGE_FILTER);if(!o.includes("||"))s.delete(r.SEARCH_RANGE_FILTER);else{var u=o.split("||");u=u.filter(function(e){return!e.includes(n)}),o=u.reduce(function(e,t,n){return e+=t,n+142&&(s.spaceNameAbbr+="..."),r.push(s)):(s.spaceNameFormatted().length>42?s.spaceNameAbbr+="...":s.spaceNameAbbr=s.spaceNameFormatted,i.push(s))}),y.user().myWishLists(r),y.user().joinedWishLists(i),e&&e()}},r=function(e,t,n){console.error("Error: ",e)};c.request("GET","/swm/rs/v1/sites/{siteid}/spaces","",n,r,{siteId:c.siteid})},activeDigVerificate:t.observable(!1),createValidationRules:function(){t.validation.rules.validationOnlyLetters={validator:function(e,t){var n=/^[A-Za-záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ ]+$/;return n.test(e)?!0:!1},message:"Texto invalido"},t.validation.rules.validationOnlyNormal={validator:function(e,t){var n=/^[a-zA-Z\ñ\Ñ\s]+$/;return n.test(e)?!0:!1},message:"No están permitidos caracteres con tilde."},t.validation.rules.validationOnlyAlphanumeric={validator:function(e,t){var n=/^[a-z0-9]+$/i;return n.test(e)?!0:!1},message:"Texto invalido"},t.validation.rules.validationName={validator:function(e,t){return e?!0:!1},message:"Texto invalido"},t.validation.rules.validationPhoneNumber={validator:function(e,t){var n=e?e.length:undefined;return n===15?!0:!1},message:"Teléfono ingresado inválido"},t.validation.rules.validationEmail={validator:function(e,t){var n=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;return n.test(e)?!0:!1},message:"Email invalido"},t.validation.rules.validationFieldRut={validator:function(e,t){var n="";for(var r=0;r<=e.length-1;r++)e.charAt(r)!="."&&e.charAt(r)!="-"&&e.charAt(r)!=" "&&(n+=e.charAt(r));if(n.length<=7||n.length>9)return!1;if(n.charAt(n.length-1)==="K"||n.charAt(n.length-1)==="k")return y.validateDigitoVerificador(n),y.activeDigVerificate()?!0:!1;var i=parseInt(n.charAt(n.length-1));return isNaN(i)?!1:(y.validateDigitoVerificador(n),y.activeDigVerificate()?!0:!1)},message:"Rut invalido"},t.validation.rules.validationPatente={validator:function(e,t){var n=new RegExp(/\w\w-\w\w-\w\w/);return e&&e.length==8&&n.test(e)},message:"Patente inválida"},t.validation.rules.checked={validator:function(e){return e?!0:!1}},t.validation.registerExtenders()},validateDigitoVerificador:function(e){var t=e.substr(-1),n=0,r=0,i=0,s=0,o=0,u=e.slice(0,-1);for(var a=u.length-1;a>=0;a--)o++,o>6&&(o=1),s=u.charAt(a),s=parseInt(s),n+=s*(o+1);i=n%11,r=11-i,r>0&&r<=9&&(r==t?y.activeDigVerificate(!0):y.activeDigVerificate(!1)),r==10&&(t=="K"||t=="k"?y.activeDigVerificate(!0):y.activeDigVerificate(!1)),r==11&&(t==0?y.activeDigVerificate(!0):y.activeDigVerificate(!1))},getValue:function(e){var n;return e!==undefined&&(t.isObservable(e)?n=e():n=e),n},ajax:function(t){function i(e,n){t.spinner&&u.destroy(),typeof t.success=="function"&&t.success(e,n)}function s(e,n){t.spinner&&u.destroy(),d.error(e),typeof t.fail=="function"&&t.fail(e,n)}t=t||{},j.CCConstants.SPINNER_SERVICES.forEach(function(e){if(t.url.indexOf(e)!=-1&&!t.hasOwnProperty("spinner")){t.spinner=!0;return}});var r={url:"",type:"GET",data:{},spinner:!1,success:function(){},fail:function(){},headers:{flow_id:localStorage.getItem("flow_id")}};return t=e.extend(r,t),t.spinner&&u.create({parent:"#page"}),t.url.indexOf("https")!=-1||t.url.indexOf("ccstorex")!=-1?n.proxy.request(t.url,t.data,i,s,t.type,t.pathParam,t.headers):n.request(t.url,t.data,i,s,t.pathParam,t.type,t.headers)},token:"",adminAjax:function(t){function n(t){function r(e,n,r){typeof t.success=="function"&&t.success(e,n)}function i(e,n){d.error(e),typeof t.fail=="function"&&t.fail(e,n)}function s(e){typeof t.always=="function"&&t.always(e)}t=t||{};var n={url:"",type:"GET",data:null,overrideUrl:!1,headers:{"x-ccasset-language":"es"},contentType:"application/json",token:!1,success:function(){},fail:function(){},always:function(){}};t=e.extend(!0,n,t);var o={url:t.url.indexOf("https")!=-1?t.url:t.overrideUrl?t.url:"/ccadminui/v1"+t.url,data:t.data?typeof t.data=="string"?t.data:JSON.stringify(t.data):undefined,method:t.type,dataType:"json",contentType:t.contentType,headers:e.extend({Authorization:t.token?"Bearer "+t.token:!1,"X-CCVisitId":window.localStorage.getItem("visitId"),"X-CCVisitorId":window.localStorage.getItem("visitorId")},t.headers)};e.ajax(o).done(function(e,t){r(e,t)}).fail(function(e,t){i(e,t)}).always(function(e){s(e)})}function r(){var e,t="; "+document.cookie,n=t.split("; oauth_token_secret-adminUI=");return n.length==2&&(e=n.pop().split(";").shift()),e?decodeURI(e).replace(/"/g,"").replace(/%2F/g,"/").replace(/%2B/g,"+").replace(/%3D/g,"="):null}r()?(t.token=r(),n(t)):e.ajax({url:"/ccadminui/v1/login",method:"POST",data:{grant_type:"client_credentials"},dataType:"json",headers:{Authorization:t.token?"Bearer "+t.token:!1},success:function(e){t.token=r(),n(t)},error:function(e,r){d.error("Failed to login",e),n(t)}})},getUserDynamicPropertyValue:function(e,t){var n;if(e)for(var r=0;r SiteSetting] -> "+e+" is disabled"),undefined;if(n&&n[t])try{return JSON.parse(n[t])}catch(r){return n[t]}},product:{getModelVersion:function(e){var e=t.toJS(e),n,r,i;if(e.type==j.CCConstants.PRODUCT_TYPES.AUTO_NUEVO){var s=e.parentCategories.find(function(e){return e.active});s?(i=s.id,n=s.displayName,r=e.displayName):n=e.displayName}else e.type==j.CCConstants.PRODUCT_TYPES.AUTO_USADO&&(n=e.x_modelo,r=e.x_version);return{id:i,model:n,version:r}},getProducts:function(e){var t="id,displayName,childSKUs,description,sourceImageURLs,listPrice,salePrice,type,parentCategory,parentCategoryIdPath,route",n={fields:e.fields?e.fields:e.additionalFields?t+","+e.additionalFields:t,continueOnMissingProduct:!0};e.q&&(n.q=e.q),e.ids&&(n.productIds=e.ids);if(e.additionalParams)for(var i in e.additionalParams)n[i]=e.additionalParams[i];j.ajax({url:r.ENDPOINT_PRODUCTS_LIST_PRODUCTS,data:n,success:e.success,fail:e.fail,spinner:e.spinner!=undefined?e.spinner:!1})},parsePrice:function(e){var t=j.siteInfo().currencyObj,n=t.symbol,r="0.00",i=i,s=s,o=t.fractionalDigits,u=null;s&&(n=s+" "+n);if((e||e===0)&&!isNaN(parseFloat(e))){n.match(/^[0-9a-zA-Z]+$/)&&(n+=" ");var a=(e+"e").split("e"),f=Math.round(a[0]+"e"+(+a[1]+o));a=(f+"e").split("e"),e=+(a[0]+"e"+(+a[1]-o)),u=g.formatNumber(e,!0,o);var l=u.charAt(0);return l==="-"||l==="+"?l+n+u.slice(1):n+u}return(n&&i?n:"")+(r?r:"")},montoReserva:function(){return j.utils.siteSetting("x_SiteSetting_GeneralSettings","reserevAmount")},lowerPrice:function(e){var t;return Array.isArray(e)||(e=[e]),e.forEach(function(e,n){var r=e.salePrices.pg_financiadoInteligenteBF||e.salePrices.pg_financiadoConvencional||e.salePrices.pg_bonoDeMarca||e.listPrices.pg_financiadoInteligenteBF||e.listPrices.pg_financiadoConvencional||e.listPrices.pg_bonoDeMarca||0,i=e.salePrices.pg_precioLista||e.listPrices.pg_precioLista;n===0?t=r?r:i:t=r&&r=2015}},catalog:{getCollections:function(e){var t={minimalFieldsForNavigation:e.min?!0:!1,categoryIds:Array.isArray(e.ids)?e.ids.join(","):e.ids,continueOnMissingCategory:!0};e.q&&(t.q=e.q),j.ajax({url:r.ENDPOINT_LIST_COLLECTIONS,data:t,success:e.success,fail:e.fail})},getCollection:function(e){var t={ids:e.id};e.fields&&(t.fields=e.fields),e.includeProducts&&(t.includeProducts=!0),j.ajax({url:j.CCConstants.urlMiddleware()+"/occ/v1/getCollection",data:t,success:function(t){t.success&&t.data&&e.success(t.data[0])},fail:function(e){console.error("Error obteniendo coleccion",e)}})},findCategoryMinPrice:function(e,t){var n=B(e,t);return n},findCollection:function(e){var t=j.utils.findValueInNestedArray(j.ALL_COLLECTIONS().childCategories,"id",e,"childCategories");return t}},cache:function(e,t){if(!e)return undefined;if(!!t)return typeof t=="string"?l.getInstance().sessionStorage.setItem(e,t):l.getInstance().sessionStorage.setItem(e,JSON.stringify(t)),t;var n=l.getInstance().sessionStorage.getItem(e);try{return JSON.parse(n)}catch(r){return n==="true"?!0:n==="false"?!1:n}},removeCache:function(e){try{return l.getInstance().sessionStorage.removeItem(e)}catch(t){d.error(t);return}},cookie:function(e){var t=e+"=",n=document.cookie.split(";");for(var r=0;rn?1:0}),e},sortJsonByNestedProperty:function(e,t,n){var r=n&&n==="desc"?-1:1;return e.sort(function(e,n){var i=t.split(".").reduce(function(e,t){return typeof e[t]=="function"?e[t]():e[t]},e),s=t.split(".").reduce(function(e,t){return typeof e[t]=="function"?e[t]():e[t]},n);return is?1*r:0})},spinner:{show:function(){u.create({parent:"#page"})},hide:function(){u.destroy()}},findValueInNestedArray:function(e,t,n,r){for(var i in e){var s=e[i];if(s[t]===n)return s;if(s[r]){var o=j.utils.findValueInNestedArray(s[r],t,n,r);if(o)return o}}return undefined}},modal:{create:function(t,n,r,i){var s=t?t:"myModal",o=n?n:"modal-dialog-centered",u=r?r:"Mensaje",a=i?i:"Mensaje",f='';e("#"+s).length>0?console.warn("BFService","Id ya existente no es posible instaciar el modal"):e("body").append(f)},"delete":function(t){e("#"+t).remove()},show:function(t){e("#"+t).modal("show")},hide:function(t){e("#"+t).modal("hide")}}};return j})