1 |
- 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:"<div class='col-md-3 col-xs-4 agregar-container'><a class='agregar cursor-pointer'><img src='/file/general/icon-plus-add-cards-profile.svg' alt='+'><br><span></span></a></div>"},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&&s<t?s:t,n=s&&o-s>n?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<t:!1};if(D[e.id]){var o=P(D[e.id]);typeof t=="function"?t({id:e.id,prices:o}):H(t,o[n],r,s(o,i))}else j.utils.product.getProducts({spinner:!1,additionalParams:{categoryId:e.id},q:"active eq true",fields:"id,listPrices,salePrices",success:function(o){D[e.id]=o.items;var u=P(o.items);typeof t=="function"?t({id:e.id,prices:u}):H(t,u[n],r,s(u,i))},fail:function(e){console.error("error obteniendo productos",e)}})},j={siteInfo:t.observable(),ALL_COLLECTIONS:t.observable(),REFINEMENTS:x,COMPARATOR:N,SEARCH:T,PRICE_GROUPS:S,SUCURSALES:C,PRODUCT_TYPES:E,SERVER_SIDE_EXTENSIONS:w,COTIZAR:k,USADOS:L,CLASE_BF_CORP:b,MODEL_LAYOUT:A,MANTENCIONES:O,user:undefined,site:undefined,pageContext:undefined,product:undefined,dimensionId:undefined,category:undefined,categoryId:undefined,storeConfiguration:a.getInstance(),pricesGropNames:t.observable(S.NAMES),CCConstants:{urlMiddleware:function(){return j.utils.siteSetting("BF_middleware","urlMiddleware")},urlNoImage:"/file/general/noimage.png",TOPICS:{FILE_EXISTS:"FILE_EXISTS",IS_MOBILE:"IS_MOBILE"},SPINNER_SERVICES:["datos_cliente","verifica_patente_reserva","quote","consulta_agenda","sucursales","mantenciones","datos_patente","datos_opt_retoma","horario_disponible_revision"],PRODUCT_TYPES:{AUTO_NUEVO:"Automovil",AUTO_USADO:"automovil-usado"},PRICE_GROUPS:{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"},LAYOUTS_WITH_CONTAINER:["Cotizacion","Cotizacion Mobile","[RESERVA AU] [COMPRA AU] [DESKTOP] 1 - Eleccion","[RESERVA AU] [COMPRA AU] [MOBILE] 1 - Eleccion","[RESERVA AU] [DESKTOP] 3 - Precio","[RESERVA AU] [DESKTOP] 4 - Cobertura","[RESERVA AU] [DESKTOP] 5 - Sucursal","[RESERVA AU] [MOBILE] 3 - Precio","[RESERVA AU] [MOBILE] 4 - Cobertura","[RESERVA AU] [MOBILE] 5 - Sucursal","[RESERVA AU] 6 - Pago","[RESERVA AU] 7.1 - Pago realizado","[RESERVA AU] 7.2 - Pago rechazado","[COMPRA AU] [DESKTOP] 3 - Cobertura","[COMPRA AU] [DESKTOP] 4 - Sucursal","[COMPRA AU] [DESKTOP] 5 - Pago","[COMPRA AU] [MOBILE] 3 - Cobertura","[COMPRA AU] [MOBILE] 4 - Sucursal","[COMPRA AU] [MOBILE] 5 - Pago","[COMPRA AU] [DESKTOP] 6.1 - Subscripcion realizada","[COMPRA AU] [DESKTOP] 6.2 - Subscripcion fallida","[COMPRA AU] [DESKTOP] 7 - Estado compra","x_simulacionCheckout","x_Checkout","Home Autos Usados","Search Results Layout","Collection Autos Usados marcas","Collection Autos Usados marcas - 1 de 2","Collection Autos Usados marcas - 2 de 2","Collection AU marcas - CON banner nuevo 1/2","Collection AU marcas - CON banner nuevo 2/2","Collection AU marcas - SIN banner nuevo 1/2","Collection AU marcas - SIN banner nuevo 2/2","Collection AU custom - 1","Collection AU custom - 2","Collection AU custom - 3","Collection AU custom - 4","Collection AU custom - 5","Collection AU custom - 6","Collection AU custom - 7","Collection AU custom - 8","Agendar servicio - 1 - Datos cliente","Agendar servicio - 2 - Datos vehiculo","Agendar servicio - 3 - Pre confirmacion","Re-Agendar servicio","Agendar Servicio - Datos Cliente","Home Autos Usados Comercial","Financiamiento AU / 1","Financiamiento AU / 1 Mobile","Financiamiento AU / 2","Financiamiento AU / 2 Mobile","Home Autos B2B","Compra AU / 3","Compra AU / 4","Compra - Confirmacion","Compra - Fallida"],LAYOUTS_WITH_BACKGROUND_DARK:["Tasacion Datos Cliente - paso 1","Tasacion Oferta - paso 3","Tasacion Datos Auto - paso 2","Tasacion Agenda - paso 4","Reserva AU / 1","x_simulacionCheckout","x_Checkout","x_Agendar-pre-confirmacion","OCW / Agendar Servicio / 1","Agendar Servicio","BF / Reagendar Servicio / 1"],LAYOUTS_WITH_BACKGROUND_GRAY:["Cotizacion","Cotizacion Mobile","Cotizacion / Confirmacion","[RESERVA AU] [COMPRA AU] [DESKTOP] 1 - Eleccion","[RESERVA AU] [COMPRA AU] [MOBILE] 1 - Eleccion","[RESERVA AU] [DESKTOP] 3 - Precio","[RESERVA AU] [DESKTOP] 4 - Cobertura","[RESERVA AU] [DESKTOP] 5 - Sucursal","[RESERVA AU] [MOBILE] 3 - Precio","[RESERVA AU] [MOBILE] 4 - Cobertura","[RESERVA AU] [MOBILE] 5 - Sucursal","[RESERVA AU] 6 - Pago","[RESERVA AU] 7.1 - Pago realizado","[RESERVA AU] 7.2 - Pago rechazado","[COMPRA AU] [DESKTOP] 3 - Cobertura","[COMPRA AU] [DESKTOP] 4 - Sucursal","[COMPRA AU] [DESKTOP] 5 - Pago","[COMPRA AU] [MOBILE] 3 - Cobertura","[COMPRA AU] [MOBILE] 4 - Sucursal","[COMPRA AU] [MOBILE] 5 - Pago","[COMPRA AU] [DESKTOP] 6.1 - Subscripcion realizada","[COMPRA AU] [DESKTOP] 6.2 - Subscripcion fallida","[COMPRA AU] [DESKTOP] 7 - Estado compra","Agendar servicio - 1 - Datos cliente","Agendar servicio - 2 - Datos vehiculo","Agendar servicio - 3 - Pre confirmacion","Re-Agendar servicio","Agendar Servicio - Datos Cliente","Order Confirmation Bruno Fritsch","Financiamiento AU / 1","Financiamiento AU / 1 Mobile","Financiamiento AU / 2","Financiamiento AU / 2 Mobile","x_Sucursales","Financiamiento AU / Confirmacion credito aprobado","Layout Venta Empresas","x_Seguros","Compra AU / 3","Compra AU / 4","Compra - Confirmacion","Compra - Fallida","Accesorios y repuestos","Landing SOAP"],LAYOUTS_WITH_PAYMENT:["[RESERVA AU] 6 - Pago","[COMPRA AU] [DESKTOP] 5 - Pago"],SUCURSALES:{TIPO_TALLER:"TALLER",TIPO_SUCURSAL:"SUCURSAL"},SHIPPING_TYPES:{OFF:"OFF",BRANCH_OFFICE:"BRANCH_OFFICE",HOME:"HOME",ON:"ON",STEP_TEXT:{BRANCH_OFFICE:"Retiro",HOME:"Envío",ON:"Envío/Retiro",WARRANTY:"Precio/Cobertura"}}},CONTACT_INFO:null,ENDPOINTS:{DATOS_CLIENTE:"/autosystem/v2/datos_cliente",COTIZACION_USADOS:"/v3/gateway/quote",COTIZACION_NUEVOS:"/v3/gateway/quotenuevos",COTIZACION_EMPRESAS:"/quotes/v1/empresas",SUCURSALES:"/sucursales",SUCURSALES_BY_MARCA:"/sucursales",SUCURSALES_ALL_MARCAS:"/sucursales/marcas/all",SCHEMA_VIDEO:"/v2/bf/youtube_schema",DATOS_PATENTE:"/v3/bf/datos_patente",VERIFICA_PATENTE:"/autosystem/v2/verifica_patente_reserva",TASACION:{DATOS_PATENTE:"/v3/bf/datos_patente",OP_RETOMA:"/v3/bf/datos_opt_retoma",ANOS:"/v3/bf/anos",MARCAS:"/v3/bf/marcas",MODELOS:"/v3/bf/modelos",VERSIONES:"/v3/bf/versiones",SAVE_TASACION:"/v2/gateway/quote/tasacion_preview",SUCURSALES:"/autosystem/v2/sucursal_disponible_usados",HORARIOS:"/autosystem/v2/horario_disponible_revision"},RE_SCHEDULE:{FIND_APPOINTMENT:"/autosystem/v3/consultar_cita",DELETE_APPOINTMENT:"/autosystem/v2/eliminar_cita",RE_SCHEDULE_APPOINTMENT:"/autosystem/v2/reagendar_cita",FIND_DATES:"/autosystem/v2/consulta_agenda"},UTILS:{FILE_EXIST:"/v2/bf/fileExists"},AGENDAMIENTO:{YEARS:"/v1/mantenciones/year_range",BRANDS:"/v1/mantenciones/marcas",MODELS:"/v1/mantenciones/modelos",VERSIONS:"/v1/mantenciones/versiones",SERVICES:"/v1/mantenciones/mantenciones"},FORUM:{DEFAULT_FINAN:"/forum/v1/createDefaultSimulation"}},isMobile:t.observable(!1),validateUserB2B:function(){if(window.location.href.indexOf("b2b")!=-1){var t=j.utils.cache("B2B_TOKEN");t&&e.ajax({url:"https://ssebftest.herokuapp.com/b2b/v1/refresh",async:!1,method:"POST",data:{token:t}}).done(function(e){t=j.utils.cache("B2B_TOKEN",e.token)}).fail(function(){t=sessionStorage.removeItem("B2B_TOKEN")});if(!t){var n=prompt("Ingrese Token B2B");if(!n)throw window.document.write("Error, no ingreso Token."),"Error";e.ajax({url:"https://ssebftest.herokuapp.com/b2b/v1/login",async:!1,data:{token:n}}).done(function(e){t=j.utils.cache("B2B_TOKEN",e.token)}).fail(function(e){throw t=sessionStorage.removeItem("B2B_TOKEN"),e&&e.responseJSON&&e.responseJSON.messageError?window.document.write(e.responseJSON.messageError):window.document.write("Error"),!1})}}},onLoad:function(){y=this,window.enableRating=!0,y.validateUserB2B(),y.ALL_COLLECTIONS.subscribe(function(t){e.Topic("ALL_COLLECTIONS.memory").publish(t)}),e("head").append('<link rel="stylesheet" href="/file/thirdparty/libraries/swiper-bundle.min.css"/>'),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;s<j.CCConstants.LAYOUTS_WITH_CONTAINER.length;s++){var o=j.CCConstants.LAYOUTS_WITH_CONTAINER[s];if(o===i){r.$data.containMain(!0);break}r.$data.containMain(!1)}}),e.Topic(i.topicNames.PAGE_CHANGED).subscribe(function(n){var r=t.contextFor(e("#page")[0]),i=r.$data.data.global.pageContext.page.displayName;for(var s=0;s<j.CCConstants.LAYOUTS_WITH_BACKGROUND_DARK.length;s++){var o=j.CCConstants.LAYOUTS_WITH_BACKGROUND_DARK[s];if(o===i){e("#page").addClass("background-dark");break}e("#page").removeClass("background-dark")}}),e.Topic(i.topicNames.PAGE_CHANGED).subscribe(function(n){var r=t.contextFor(e("#page")[0]),i=r.$data.data.global.pageContext.page.displayName;for(var s=0;s<j.CCConstants.LAYOUTS_WITH_PAYMENT.length;s++){var o=j.CCConstants.LAYOUTS_WITH_PAYMENT[s];if(o===i){e("#page").addClass("layout-checkout");break}e("#page").removeClass("layout-checkout")}}),e.Topic(i.topicNames.PAGE_CHANGED).subscribe(function(n){var r=t.contextFor(e("#page")[0]),i=r.$data.data.global.pageContext.page.displayName;for(var s=0;s<j.CCConstants.LAYOUTS_WITH_BACKGROUND_GRAY.length;s++){var o=j.CCConstants.LAYOUTS_WITH_BACKGROUND_GRAY[s];if(o===i){e("main").addClass("background-gray");break}e("main").removeClass("background-gray")}});var s=function(e,t){return e.filter(function(e){return t.indexOf(e)<0})};e.fn.removeClassesExceptThese=function(t){var n=e(this);if(n.length>0){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;r<M.length;r++){var i=M[r];switch(i.type){case"string":for(var s=0;s<i.values.length;s++){var o=i.values[s];n=="searchResult"?(e.hasOwnProperty("product."+i.field)&&e["product."+i.field]()[0]&&o.diccionary.indexOf(e["product."+i.field]()[0].toLowerCase())!=-1||e.hasOwnProperty("automovil-usado."+i.field)&&e["automovil-usado."+i.field]()[0]&&o.diccionary.indexOf(e["automovil-usado."+i.field]()[0].toLowerCase())!=-1)&&e.highlightProperties.push(o):e[i.field]()&&o.diccionary.indexOf(e[i.field]().toLowerCase())!=-1&&e.highlightProperties.push(o)}break;case"boolean":n=="searchResult"?e.hasOwnProperty("product."+i.field)?e["product."+i.field]()[0]!=="0"&&e["product."+i.field]()[0]!==""&&e.highlightProperties.push(i):e.hasOwnProperty("automovil-usado."+i.field)&&e["automovil-usado."+i.field]()[0]!=="0"&&e["automovil-usado."+i.field]()[0]!==""&&e.highlightProperties.push(i):e[i.field]()&&e.highlightProperties.push(i);break;case"formula":n=="searchResult"?i.formula(e,"searchResult")&&e.highlightProperties.push(i):i.formula(e,"productListing")&&e.highlightProperties.push(i);break;default:}}return e.highlightProperties()},goToLocations:function(e){e?f.goTo("/sucursales?brand="+e):f.goTo("/sucursales")},obtainVariantOptions:function(e,t){var n=[],r=[];if(e&&e.length>0&&t)for(var i=0;i<e.length;i++)if(e[i].actualOptionId==t){r=e[i].optionValues().map(function(e){return e.label=e.key.toUpperCase().replace(/ *\([^)]*\) */g,"").replaceAll(")","").replaceAll("(",""),e.keyNormalized=e.label.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replaceAll(" ",""),e}),n=r.filter(function(e,t,n){return t===n.findIndex(function(t){return t.keyNormalized===e.keyNormalized&&e.visible()})});break}return n},addCustomBindings:function(){t.bindingHandlers.goTo={init:function(t,n,r){var i=n(),s=typeof i=="string"?i:i.url;i?(e(t).css("cursor","pointer"),t.nodeName==="A"&&(e(t).attr("href",s),i.blank&&e(t).attr("target","_blank")),e(t).click(function(t){return i.blank||t.preventDefault(),s.indexOf("comprar-seminuevo-precio-promocion-chile")!==-1||s.indexOf("comprar-promocion-bono-precio-chile")!==-1?window.location.href=s:f.goTo(s),e(".navbar-collapse.in").collapse("hide"),!1})):d.error("[Data-bind -> 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<i.length;s++){var o=i[s].trim();if(o===r.tag){e(t).show();break}}}}catch(u){d.error("[OCC error - Tag not found]",u)}}},t.bindingHandlers.maskedValue={init:function(n,r,i){var s=r(),o=s;t.isObservable(o)&&(o.subscribe(function(t){console.log(i),e(n).val(t),e(n).trigger("input")}),e(n).on("focusout change",function(){o(e(n).cleanVal())}),i().valueUpdate&&e(n).on(i().valueUpdate,function(){o(e(n).cleanVal())}))},update:function(t,n,r){var i=n();i()||e(t).val("")}},t.bindingHandlers.textCapitalizeFirst={init:function(t,n,r){var i=n();if(i){var s=i.split(" ");for(var o=0;o<s.length;o++)s[o]=s[o].charAt(0).toUpperCase()+s[o].slice(1).toLowerCase();e(t).text(s.join(" "))}}};var n=function(e){var t=[];return!Array.isArray(e.target)&&typeof e.target!="string"?t.push(e.target):Array.isArray(e.target)?e.target.forEach(function(e){t.push(e.charAt(0)=="#"?e:"#"+e)}):t.push(e.target.charAt(0)=="#"?e.target:"#"+e.target),t},r=function(e){var t=e.filePath,n=!t.endsWith("pdf")&&!t.endsWith("csv");return n&&e.imgSize.w&&e.imgSize.h&&(t="/ccstore/v1/images/?source="+t+"&height="+e.imgSize.h+"&width="+e.imgSize.w),t};t.bindingHandlers.ifFileExists={update:function(i,s){e(i).hide();var o=s(),u={filePath:"",target:i,attr:"href",replace:!1,imgSize:{w:null,h:null}};typeof t.unwrap(o)=="string"&&(o={filePath:t.unwrap(o)}),o=e.extend(u,t.toJS(o)),o.filePath&&j.ajax({url:"https://ssebftest.herokuapp.com"+j.ENDPOINTS.UTILS.FILE_EXIST,data:{file:o.filePath},spinner:!1,success:function(t){if(t.fileExist||!t.fileExist&&o.replace){e(i).show(),t.fileExist||(o.filePath=j.CCConstants.urlNoImage);var s=n(o);s.forEach(function(t){e(t).attr(o.attr,r(o))})}e.Topic(j.CCConstants.TOPICS.FILE_EXISTS).publish({fileExists:t.fileExist,file:o.filePath})}})}},t.bindingHandlers.fadeVisible={init:function(n,r){var i=r();e(n).toggle(t.utils.unwrapObservable(i))},update:function(n,r,i){var s=r(),o=i();s&&o.customShow?e(n)[o.customShow]():!s&&o.customHide?e(n)[o.customHide]():t.utils.unwrapObservable(s)?e(n).fadeIn():e(n).fadeOut()}};var i=[];t.bindingHandlers.ytVideo={update:function(n,r){var s=t.toJS(r());s&&(typeof s=="string"&&(s={id:s}),i.indexOf(s.id)==-1&&j.ajax({url:j.CCConstants.urlMiddleware()+j.ENDPOINTS.SCHEMA_VIDEO,data:{id:s.id},success:function(t){if(t.success){var r=document.createElement("script");r.type="application/ld+json",r.append(JSON.stringify(t.data));var o='<iframe frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" title="'+t.data.name+'" src="'+t.data.embedUrl+'"></iframe>';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:'<i class="fa fa-long-arrow-left"></i>',rightArrow:'<i class="fa fa-long-arrow-right"></i>'}}).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;n<y.collectionTree().length;n++){t=y.collectionTree()[n];if(t.id===e){y.completeCollection(t);break}t=undefined}};y.collectionTreeLoaded?n():(y.collectionTreeLoadedCallbacks.push(n),y.collectionTreeLoading||y.loadCollectionTree())}},collectionImagesCache:[],getCollectionsImages:function(e,t,i){if(e&&(Array.isArray(e)&&e.length>0||!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,p<u?u=p:undefined),h=l[S.NAMES.financiadoConvencional],h&&(m[S.NAMES.financiadoConvencional]=h,h<u&&(u=h,a=!0)),c=l[S.NAMES.financiadoInteligente],c&&(m[S.NAMES.financiadoInteligente]=c,c<u&&(u=c,a=!0)),v=l[S.NAMES.precioReservaWeb],v&&(m[S.NAMES.precioReservaWeb]=j.utils.siteSetting("x_SiteSetting_GeneralSettings","reserevAmount")),m[S.DISCOUNT_AMOUNT]=undefined,m[S.DISCOUNT_PERCENT]=undefined,m[S.HAS_FUNDING]=a,u&&(m[S.LOWER_PRICE]=u,m[S.DISCOUNT_PERCENT]=Math.floor((d-u)*100/d),m[S.DISCOUNT_AMOUNT]=Math.floor(d-u)),t.isObservable(e[i])?e[i](m):e[i]=t.observable(m),s&&s(m)};e&&(f=e.id?e.id:e.productId?e.productId:undefined,f||(f=e["product.repositoryId"]&&Array.isArray(e["product.repositoryId"])&&e["product.repositoryId"].length>0?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,f<i?i=f:undefined),a=o[S.NAMES.financiadoConvencional],a&&(h[S.NAMES.financiadoConvencional]=a,a<i&&(i=a,s=!0)),u=o[S.NAMES.financiadoInteligente],u&&(h[S.NAMES.financiadoInteligente]=u,u<i&&(i=u,s=!0)),c=o[S.NAMES.precioReservaWeb],c&&(h[S.NAMES.precioReservaWeb]=j.utils.siteSetting("x_SiteSetting_GeneralSettings","reserevAmount")),h[S.DISCOUNT_AMOUNT]=undefined,h[S.DISCOUNT_PERCENT]=undefined,h[S.HAS_FUNDING]=s,i&&(h[S.LOWER_PRICE]=i,h[S.DISCOUNT_PERCENT]=Math.floor((l-i)*100/l),h[S.DISCOUNT_AMOUNT]=Math.floor(l-i)),t.isObservable(e)?e()[n?n:"allPrices"]=h:e[n?n:"allPrices"]=h},handleAddToCartAndRedirectToCheckout:function(t){function b(){t.isAddToCartClicked(!1)}o.clearError(t.WIDGET_ID);var n=t.variantOptionsArray();o.clearSuccess(t.WIDGET_ID);var u=t.getSelectedSkuOptions(n),a={selectedOptions:u},l={availabilityDate:t.availabilityDate()},c={stockState:t.stockState()},h=e.extend(!0,{},t.product().product,a,l,c);t.selectedSku()&&!t.selectedSku().primaryThumbImageURL&&t.assignSkuIMage(h,t.selectedSku()),t.variantOptionsArray().length>0&&(h.childSKUs=[t.selectedSku()]),h.orderQuantity=parseInt(t.itemQuantity(),10);var p=t.itemQuantityInCart(h),d=h.orderLimit&&h.orderLimit<t.stockAvailable()?h.orderLimit:t.stockAvailable();if(p+parseInt(t.itemQuantity(),10)>d){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;u<t.length;u++){n=t[u].split("||");for(var a=0;a<n.length;a++)i=n[a].split("|"),o=i[0],s=i[1].replace("BTWN ","").split(" "),e.push({dimensionName:o,bounds:s}),o=undefined,s=undefined,i=undefined}return e},checkIfExistNfParameter:function(e){var t;if(e){var n=y.getUrlParameter(r.SEARCH_RANGE_FILTER),i=x.RANGE_FILTERS_DATA[e].urlParamValue,s,o;for(var u=0;u<n.length;u++){s=n[u].split("||");for(var a=0;a<s.length;a++){o=s[a].split("|");if(o[0]===i){var f=o[1].replace("BTWN ","").split(" ");t={dimensionName:e,bounds:f,urlValue:i};break}o=undefined}s=undefined}}return t},initSlider:function(t,n,r){var i=t.dimensionName,s=y.checkIfExistNfParameter(i);if(!s){var o=y.getBounds(t),u=o.lowerBound,a=o.upperBound,f=r,l=document.getElementById(f);if(u<a){var c={start:[u,a],range:{min:u,max:a}},p=x.RANGE_FILTERS_DATA[i].format,d=x.RANGE_FILTERS_DATA[i].step,v=x.RANGE_FILTERS_DATA[i].connect,m=x.RANGE_FILTERS_DATA[i].decimals;p?c.format=p:undefined,d?c.step=d:undefined,v?c.connect=v:undefined,m?c.decimals=m:undefined,l&&h.create(l,c).on("change",function(e,t,r){var i=y.getFirstLevelCategoryId(n);y.SEARCH.CATEGORY_ID=i,y.saveCookie(y.REFINEMENTS.RANGE_COLLECTION_COOKIE,i),y.handleOnChangeSlider(this,e,t,r)});var g=[document.getElementById(f+"-lower"),document.getElementById(f+"-upper")];l.noUiSlider.on("update",function(e,t){g[t].innerHTML=e[t]}),e(".noUi-handle").addClass("ocs-brand-background-color")}}else{var b="#ocs-"+t.dimensionName.replace(".","\\.");e(b).remove()}},rangeFiltersApplied:t.observable({}),loadRangeFiltersApplied:function(){var e=window.location.search,t=new URLSearchParams(e),n=t.get(r.SEARCH_RANGE_FILTER);if(n){var i=n.split("||"),s=i.reduce(function(e,t){var n=t.split("|")[0],r=[];t.split("|")[1].replace("BTWN ","").split(" ").forEach(function(e){r.push(Number(e))});var i;for(var s in x.RANGE_FILTERS_DATA)if(x.RANGE_FILTERS_DATA[s].urlParamValue===n){i=x.RANGE_FILTERS_DATA[s].elementId,e[i]={dimensionName:n,bounds:r};break}return e},{});y.rangeFiltersApplied(s)}},handleOnChangeSlider:function(e,t,n,r){var i=e.target.attributes.id.nodeValue;y.loadRangeFiltersApplied(),y.rangeFiltersApplied()[i]={dimensionName:x.DIMENSION_NAMES[i].dimensionName,bounds:r};var s=function(){x.timeOutInstance=undefined,y.rangeRefinementTriggered(i)};x.timeOutInstance&&(clearTimeout(x.timeOutInstance),x.timeOutInstance=undefined),x.timeOutInstance=setTimeout(s,x.RANGE_FILTERS_TIMEOUT)},getBounds:function(e){var t={lowerBound:undefined,upperBound:undefined};if(e&&e.refinements&&e.refinements()&&e.refinements().length&&e.refinements().length>0){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):(i<u?u=i:undefined,s>o?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+1<u.length?e+="||":undefined,e},""),y.rangeFiltersApplied({}),s.set(r.SEARCH_RANGE_FILTER,u)}}if(!e.isRangeRefinement&&s.has(r.SEARCH_NAV_RECORD_FILTER_KEY)){var a=s.get(r.SEARCH_NAV_RECORD_FILTER_KEY);if(!a.includes(","))s.delete(r.SEARCH_NAV_RECORD_FILTER_KEY);else{var l=a.replace("AND(","").replace(")","").split(",");l=l.filter(function(e){return!e.includes(n)}),l=l.reduce(function(e,t,n){return e+=t,n+1<l.length?e+=",":undefined,n+1===l.length?e+=")":undefined,e},"AND("),s.set(r.SEARCH_NAV_RECORD_FILTER_KEY,l)}}f.goTo(t+"?"+s.toString())},getStringToUrl:function(e){var t="",n,i;return e&&y.rangeFiltersApplied()&&(y.dimensionId&&y.dimensionId()&&!window.location.search.includes(r.SEARCH_NAV_DESCRIPTORS_KEY+"=")&&(t+="&"+r.SEARCH_NAV_DESCRIPTORS_KEY+"="+y.dimensionId()),Object.keys(y.rangeFiltersApplied()).forEach(function(e,s){n=y.rangeFiltersApplied()[e],s===0?t+="&"+r.SEARCH_RANGE_FILTER+"=":t+="||",t+=n.dimensionName+"|BTWN",i=n.bounds,i.forEach(function(e){t+="+"+e}),i=undefined,n=undefined})),t},saveCookie:function(e,t){e&&t&&l.getInstance().setItem(e,t)},loadCookie:function(e){var t;return t=l.getInstance().getItem(e),t},deleteCookie:function(e){l.getInstance().removeItem(e)},xmlToString:function(e){var t;return window.ActiveXObject?t=e.xml:t=(new XMLSerializer).serializeToString(e),t},getOportunitiesProducts:function(e,t,i){var s=r.ENDPOINT_PRODUCTS_LIST_PRODUCTS,o={categoryId:e,includeChildren:!0,q:'x_productoDestacado co "1"'};n.request(s,o,t,i)},siteName:t.observable(),getSpaces:function(e){var n=function(n){var r=[],i=[];if(n.response.code.indexOf("200")===0){y.siteName(n.siteName);var s=n.items;s.forEach(function(e,n){var s={spaceid:e.spaceId,spaceNameFull:t.observable(e.spaceName),spaceNameAbbr:e.spaceName.substr(0,41),spaceNameFormatted:t.computed(function(){return e.creatorId==c.apiuserid?e.spaceName:e.spaceName+" ("+e.creatorFirstName+" "+e.creatorLastName+")"},y),creatorid:e.creatorId,accessLevel:e.accessLevel,spaceOwnerFirstName:e.creatorFirstName,spaceOwnerLastName:e.creatorLastName};e.creatorId==c.apiuserid?(s.spaceNameFull.length>42&&(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<e.dynamicProperties().length;r++)e.dynamicProperties()[r].id()===t&&(n=e.dynamicProperties()[r].value());return n},initSWMRestClient:function(e,t,n){c.init(e,t,n)},createDefaulFinancing:function(e,t,n){try{var r=j.utils.product.lowerPrice(t),i=j.utils.product.getModelVersion(t);j.ajax({type:"POST",url:j.CCConstants.urlMiddleware()+j.ENDPOINTS.FORUM.DEFAULT_FINAN+"?flowId="+localStorage.getItem("flow_id")+"&zendeskId="+j.utils.cache("ZENDESK_ID"),data:{data:{rut:e.rut,firstName:e.firstName,lastName:e.lastName,email:e.email,phone:e.phone},carData:{price:r,brand:t.brand,model:i.model,version:i.version,year:t.x_agno,kms:t.x_kilometraje,transmision:t.x_transmision,combustible:t.x_combustible,branchName:t.x_Ubicacion_Fisica}},success:function(e){e.success&&n()}})}catch(s){return logger.error("Error generando financiamiento por defecto",s),!1}},utils:{siteSetting:function(e,t){if(!t)return j.siteInfo()&&j.siteInfo().siteSettings&&j.siteInfo().siteSettings[e]?j.siteInfo().siteSettings[e]:undefined;var n=j.utils.siteSetting(e);if(n&&n.hasOwnProperty("__siteSettingsEnabled__")&&n.__siteSettingsEnabled__===!1)return d.warn("[GlobalFN -> 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<t?r:t}),t},checkIfAppliesNissanDevice:function(e,t){return e.toUpperCase()=="NISSAN"&&t>=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;r<n.length;r++){var i=n[r];while(i.charAt(0)==" ")i=i.substring(1);if(i.indexOf(t)==0)return i.substring(t.length,i.length)}return""},parsePrice:function(e){var t=j.siteInfo().currencyObj,n=t.symbol,r="",i=i,s=s,o=0,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:"")},sortJsonByField:function(e,t){return e.sort(function(e,n){return e=typeof e[t]=="string"?e[t].toLowerCase():e[t],n=typeof n[t]=="string"?n[t].toLowerCase():n[t],e<n?-1:e>n?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 i<s?-1*r:i>s?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='<div id="'+s+'" class="modal fade" role="dialog"> <div class="modal-dialog '+o+'"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">'+u+'</h4> </div> <div class="modal-body"> <p>'+a+'</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button> </div> </div> </div> </div>';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})
|