1 |
- define(["jquery","knockout","notifier","navigation","pubsub","swmRestClient","ccConstants","CCi18n","ccResourceLoader!global/OCS_BFService","/file/thirdparty/libraries/jquerymask.js","notifications","ccConstants","viewModels/searchTypeahead"],function(e,t,n,r,i,s,o,u,a,f,l,c,h){"use strict";var p,d,v=null,m=["Autos nuevos","Autos usados"];return{showHeaderSmaller:t.observable(!1),isMobile:t.observable(!1),searchText:t.observable(""),searchTextLabel:t.observable(""),searchResults:t.observableArray([]),noResults:t.observable(!1),showErrorMessage:t.observable(!1),modalMessageType:t.observable(""),modalMessageText:t.observable(""),modalMessageLink:t.observable(""),ignoreBlur:t.observable(!1),userCreated:t.observable(!1),pathLogo:t.observable(),menuImgPathToDisplay:t.observable(),firstLevelCollections:t.observableArray(),firstLevelCategoryId:t.observable(),firstLevelCategoryIds:t.observable(),routeAutosUsados:t.observableArray(),fieldRut:t.observable(),fieldFirstName:t.observable(),codigoPhoneNumber:t.observableArray(),codigoPhoneActive:t.observable(),fieldPhone:t.observable(),mothersLastName:t.observable(),activeDigVerificate:t.observable(!1),onLoadExecution:!1,rotationArrowHeader:function(t,n){var r=e(n.currentTarget.children[0]).hasClass("rotation-1");e(n.currentTarget.children[0]).toggleClass("rotation-2",r),e(n.currentTarget.children[0]).toggleClass("rotation-1",!r)},onLoad:function(n){setTimeout(function(){e("#headerBFExpand").click(function(){e(this).text().trim("")==="expand_more"?e("#headerBFExpand").text("expand_less"):e("#headerBFExpand").text("expand_more")})},300),e(".close-action").on("click",function(e){e.stopPropagation()});var r=this;p=n,p.onLoadExecution=!0,n.showResults=t.computed(function(){return n.searchResults().length>0||n.noResults()?(e("#bg-mobile").remove(),e("body").append("<div id='bg-mobile' class='modal-backdrop fade in' style='opacity: .8;z-index: 15;'></div>"),e("body").css("overflow-y","hidden")):(e("#bg-mobile").remove(),e("body").css("overflow-y","initial")),n.searchResults().length>0},n),n.createValidationRules(),a.layoutHasBrandingStyle.subscribe(function(e){p.showHeaderSmaller(e)}),a.layoutHasBrandingStyle()!==undefined&&p.showHeaderSmaller(a.layoutHasBrandingStyle()),n.firstLevelCollections(a.collectionTree);var s=p.firstLevelCollections().subscribe(function(e){var t;for(var n=0;n<e.length;n++){t=e[n];if(t.id===a.USADOS.collectionId){p.routeAutosUsados.push(t),s.dispose();break}}});n.firstLevelCollections.subscribe(n.loadFirstLevelCategoryIds),n.firstLevelCategoryIds.subscribe(function(e){a.getCollectionsImages(e,n.successCallBackCollectionImages,n.errorCallBackCollectionImages)}),e.Topic("sendLogoPath").subscribe(function(e){p.pathLogo(e)}),e.Topic(i.topicNames.USER_LOGIN_SUCCESSFUL).subscribe(function(e){a.getSpaces(function(){p.checkWishlistStructure()})}),e.Topic(i.topicNames.USER_AUTO_LOGIN_SUCCESSFUL).subscribe(function(e){a.getSpaces(function(){p.checkWishlistStructure()})}),e.Topic("OCS_OPEN_LOGIN_MODAL").subscribe(function(){p.clickLogin(p.user())}),p.initTypeahead()},beforeAppear:function(){p.isMobile(window.innerWidth<992),window.onresize=function(){var e=p.isMobile(),t=window.innerWidth<992;e!=t&&p.isMobile(t)},p.onLoadExecution?p.onLoadExecution=!1:window.ga&&(window.ga("gtm1.set","page",window.location.pathname),window.ga("gtm1.set","title",document.title),window.ga("gtm1.send","pageview")),p.getFirstLevelCategoryData();var t=e("#field-rut");t.mask("0.000.00A-A"),t.on("input",function(){var e=document.getElementById("field-rut").value;return e.length>9?t.mask("00.000.000-A"):t.mask("0.000.00A-A"),!0}),e("#field-phone").mask("+56 0 0000-0000"),p.dontCloseModalOnClick(),p.closeMenuMobile(),p.searchText("")},initTypeahead:function(){var e=this;e.searchText.subscribe(function(t){e.noResults(!1),t.length>3?a.ajax({url:"assemble",data:{language:"es",N:723843639,Nrpp:"5",Ntk:"TypeAhead",Ntt:t,path:"/typeahead",redirects:"yes",searchType:"typeahead",site:"default",visitId:localStorage.getItem("visitId"),visitorId:localStorage.getItem("visitorId")},success:function(n){var r=n.resultsList.records,i=[];if(!r.length){e.searchResults([]),e.searchTextLabel(""),e.noResults(!0);return}i=r.map(function(t){var n={displayName:t.records[0].attributes["product.displayName"][0],brand:t.records[0].attributes["product.x_marca"][0],year:Number(t.records[0].attributes["product.x_agno"][0]),model:t.records[0].attributes["product.x_modelo"][0],kms:t.records[0].attributes["product.x_kilometraje"][0],transmision:t.records[0].attributes["product.x_transmision"][0],image:t.records[0].attributes["product.primaryThumbImageURL"][0]=="/img/no-image.jpg"?"/file/general/noimage.png":t.records[0].attributes["product.primaryThumbImageURL"][0],route:t.records[0].attributes["product.route"][0],price:t.attributes["sku.minActivePrice"][0]};return e.isMobile()&&(n.transmision==="Automática"?n.transmision="Aut.":n.transmision==="Mecánica"&&(n.transmision="Mec.")),n}),e.noResults(!1),e.searchResults(i),e.searchTextLabel('Ver todos los "'+t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()+' Usados"')},fail:function(t){e.searchResults([]),e.searchTextLabel(""),console.error("Error buscando productos en endeca",t)}}):(e.searchResults([]),e.searchTextLabel(""))}),e.closeTypeahead=function(){e.searchText(""),e.noResults(!1),e.searchResults([]),e.searchTextLabel("")}},handleResultList:function(){const e=document.getElementById("container-form-desktop");window.addEventListener("click",function(t){e.contains(t.target)||(p.searchResults([]),p.noResults(!1))})},checkPageType:function(e){var t=p.pageContext().pageType.id;if(a.isMobile())return!1;switch(t){case"articlePageType":return!1;case"searchResultsPageType":return!0;case"categoryPageType":return!0;case"productPageType":return!0;default:return!1}},addRut:function(){},applyPhoneMask:function(){e("#field-phone").mask("+56 0 0000-0000"),e("#field-phone").val("+56")},getFirstLevelCategoryData:function(){p.firstLevelCategoryId(a.getFirstLevelCategoryId(p.category()))},burguerMenuOpen:t.observable(!1),toggleBurguerMenu:function(){var t=p.burguerMenuOpen();p.burguerMenuOpen(!t),t?e(".ocs-burguer-menu-list-login").slideUp():e(".ocs-burguer-menu-list-login").slideDown()},closeBurguer:function(){var t=p.burguerMenuOpen();p.burguerMenuOpen(!t),t&&e(".ocs-burguer-menu-list-login").slideUp()},dontCloseModalOnClick:function(){e("#ocs-modal-content").click(function(e){return!1})},clickMenuMobile:function(){var t=e("div.barramenu nav"),n=e("div.barramenu > a.amenu");n.hasClass("abierto")?(t.slideUp(),n.removeClass("abierto")):(t.slideDown(),n.addClass("abierto"))},closeMenuMobile:function(){var t=e("div.barramenu nav"),n=e("div.barramenu > a.amenu");n.hasClass("abierto")&&(t.slideUp(),n.removeClass("abierto"))},clickSubMenuMarcasMobile:function(){var t=e("div.barramenu > nav > ul > li.dropdown > a");t.hasClass("abierto")?(t.parent().find("ul").slideUp(),t.removeClass("abierto")):(t.parent().find("ul").slideDown(),t.addClass("abierto"))},hideAllSections:function(){e("#CC-loginUserPane").hide(),e("#CC-registerUserPane").hide(),e("#CC-forgotPasswordSectionPane").hide(),e("#CC-updatePasswordPane").hide(),e("#CC-updatePasswordMessagePane").hide(),e("#CC-forgotPasswordMessagePane").hide(),e("#CC-updatePasswordErrorMessagePane").hide()},hideLoginModal:function(){e("#CC-headermodalpane").modal("hide"),e("body").removeClass("modal-open"),e(".modal-backdrop").remove()},showConfirmForgotPWDModal:function(){e("#CC-updatePasswordPane").hide(),e("#CC-updatePasswordMessagePane").modal("show")},showErrorForgotPWDModal:function(){e("#CC-updatePasswordPane").hide(),e("#CC-updatePasswordErrorMessagePane").modal("show")},registerUser:function(t,r){if("click"===r.type||("keydown"===r.type||"keypress"===r.type)&&r.keyCode===13)n.clearError(this.WIDGET_ID),p.user().shippingAddressBook([]),p.user().updateLocalData(!1,!1),p.user().validateUser()&&e.Topic(i.topicNames.USER_REGISTRATION_SUBMIT).publishWith(p.user(),[{message:"success",widgetId:t.WIDGET_ID}]);return!0},showRegistrationSection:function(){e("#alert-modal-change").text(u.t("ns.common:resources.registrationModalOpenedText")),p.hideAllSections(),e("#CC-registerUserPane").show(),e("#CC-userRegistration-rut").focus(),p.user().firstName.isModified(!1),n.clearError(p.WIDGET_ID),n.clearSuccess(p.WIDGET_ID),p.user().reset(),p.showErrorMessage(!1)},handleCancelForgottenPassword:function(e,t){if("click"===t.type||("keydown"===t.type||"keypress"===t.type)&&t.keyCode===13)n.clearError(p.WIDGET_ID),r.doLogin(r.getPath(),p.links().home.route);return!0},cancelLoginModal:function(e){if(e.hasOwnProperty("user")){e.user().handleCancel();if(e.user().pageToRedirect()&&e.user().pageToRedirect()==e.links().checkout.route&&e.cart().items().length>0){var t=e.user().pageToRedirect();e.user().pageToRedirect(null),r.goTo(t)}else r.cancelLogin();e.user().pageToRedirect(null),n.clearError(e.WIDGET_ID),e.user().clearUserData(),e.user().profileRedirect()}else r.cancelLogin()},showForgotPasswordSection:function(t){e("#alert-modal-change").text(u.t("ns.common:resources.forgottenPasswordModalOpenedText")),t.ignoreEmailValidation(!1),this.hideAllSections(),e("#CC-forgotPasswordSectionPane").show(),e("#CC-forgotPwd-input").focus(),t.emailAddressForForgottenPwd(""),t.emailAddressForForgottenPwd.isModified(!1)},resetForgotPassword:function(e,t){if("click"===t.type||("keydown"===t.type||"keypress"===t.type)&&t.keyCode===13)p.user().ignoreEmailValidation(!1),p.user().emailAddressForForgottenPwd.isModified(!0),p.user().emailAddressForForgottenPwd&&p.user().emailAddressForForgottenPwd.isValid()&&p.user().resetForgotPassword();return!0},savePassword:function(e,t){if("click"===t.type||("keydown"===t.type||"keypress"===t.type)&&t.keyCode===13)n.clearError(this.WIDGET_ID),e.user().ignoreConfirmPasswordValidation(!1),e.user().ignoreEmailValidation(!1),e.user().emailAddressForForgottenPwd.isModified(!0),e.user().isPasswordValid(!0)&&e.user().emailAddressForForgottenPwd&&e.user().emailAddressForForgottenPwd.isValid()&&e.user().updateExpiredPasswordUsingToken(e.user().token,e.user().emailAddressForForgottenPwd(),e.user().newPassword(),e.user().confirmPassword(),function(t){e.showConfirmForgotPWDModal()},function(t){e.showErrorForgotPWDModal()});return!0},closeModal:function(e,t){return("click"===t.type||("keydown"===t.type||"keypress"===t.type)&&t.keyCode===13)&&this.hideLoginModal(),!0},clickLogin:function(t){n.clearSuccess(this.WIDGET_ID),n.clearError(this.WIDGET_ID),t.reset(),p.hideAllSections(),e("#CC-loginUserPane").show(),p.showErrorMessage(!1),e("#CC-headermodalpane").on("shown.bs.modal",function(){!t.loggedIn()&&t.login()&&t.login()!==""&&t.isUserSessionExpired()?(t.populateUserFromLocalData(!0),e("#CC-login-password-input").focus(),t.password.isModified(!1)):(e("#CC-login-input").focus(),t.login.isModified(!1)),r.loginHandlerPage=null})},handleLogin:function(t,r){if("click"===r.type||("keydown"===r.type||"keypress"===r.type)&&r.keyCode===13)n.clearError(this.WIDGET_ID),p.user().validateLogin()&&(p.user().updateLocalData(!1,!1),e.Topic(i.topicNames.USER_LOGIN_SUBMIT).publishWith(p.user(),[{message:"success"}]));return!0},handleCancel:function(t,r){r.preventDefault();if("click"===r.type||("keydown"===r.type||"keypress"===r.type)&&r.keyCode===13)n.clearError(this.WIDGET_ID),p.user().isUserSessionExpired()&&(e.Topic(i.topicNames.USER_LOGOUT_SUBMIT).publishWith([{message:"success"}]),this.hideLoginModal());return!0},handleLogout:function(t){if(t.isUserProfileEdited())return!0;n.clearSuccess(this.WIDGET_ID),n.clearError(this.WIDGET_ID),t.updateLocalData(t.loggedinAtCheckout(),!1),e.Topic(i.topicNames.USER_LOGOUT_SUBMIT).publishWith([{message:"success"}]),p.closeBurguer()},cancelRegistration:function(){n.clearSuccess(p.WIDGET_ID),n.clearError(p.WIDGET_ID),p.hideLoginModal(),p.user().reset(),p.showErrorMessage(!1),p.user().pageToRedirect(null)},handleMouseUp:function(){return p.ignoreBlur(!1),p.user().ignoreConfirmPasswordValidation(!1),!0},handleMouseDown:function(){return p.ignoreBlur(!0),p.user().ignoreConfirmPasswordValidation(!0),!0},emailAddressFocused:function(){return p.ignoreBlur&&p.ignoreBlur()?!0:(p.user().ignoreEmailValidation(!0),!0)},emailAddressLostFocus:function(e,t){var n=t.target.value.replace(/[áéíóúàèìòùÁÉÍÓÚÀÈÌÒÙ~^<>`´'*+?^${}()|[\]\\]/g,"").toLowerCase();return t.target.value=n,p.ignoreBlur&&p.ignoreBlur()?!0:(p.user().ignoreEmailValidation(!1),!0)},passwordFieldFocused:function(){return p.ignoreBlur&&p.ignoreBlur()?!0:(p.user().ignorePasswordValidation(!0),!0)},passwordFieldLostFocus:function(){return p.ignoreBlur&&p.ignoreBlur()?!0:(p.user().ignorePasswordValidation(!1),!0)},confirmPwdFieldFocused:function(){return p.ignoreBlur&&p.ignoreBlur()?!0:(p.user().ignoreConfirmPasswordValidation(!0),!0)},confirmPwdFieldLostFocus:function(){return p.ignoreBlur&&p.ignoreBlur()?!0:(p.user().ignoreConfirmPasswordValidation(!1),!0)},loadFirstLevelCategoryIds:function(e){var t="";e().forEach(function(n,r){t+=n.id,r!=e.length-1&&(t+=",")}),p.firstLevelCategoryIds(t)},successCallBackCollectionImages:function(t){var n;t.forEach(function(t,r){for(var i=0;i<t.categoryImages.length;i++){n=t.categoryImages[i];if(n.path.includes(t.id+"-menu.")){r==0&&p.menuImgPathToDisplay("/file"+n.path),e.extend(p.firstLevelCollections()()[r],{menuImagePath:"/file"+n.path});break}n=undefined}})},itemMenuMouseOver:function(){p.menuImgPathToDisplay(this.menuImagePath)},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?p.activeDigVerificate(!0):p.activeDigVerificate(!1)),r==10&&(t=="K"||t=="k"?p.activeDigVerificate(!0):p.activeDigVerificate(!1)),r==11&&(t==0?p.activeDigVerificate(!0):p.activeDigVerificate(!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.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 p.validateDigitoVerificador(n),p.activeDigVerificate()?!0:!1;var i=parseInt(n.charAt(n.length-1));return isNaN(i)?!1:(p.validateDigitoVerificador(n),p.activeDigVerificate()?!0:!1)},message:"Rut invalido"},t.validation.registerExtenders()},checkWishlistStructure:function(){var e=p.user().myWishLists();console.log("Check wishlist structure: ",e);if(e.length===m.length)for(var t=0;t<p.user().myWishLists().length;t++){var n=p.user().myWishLists()[t].spaceid,r=!1,i=m.find(function(e){r=!0});r||p.deleteWishList(n,p.successRequestWishList,p.errorRequestWishList)}else for(var t=0;t<p.user().myWishLists().length;t++){var n=p.user().myWishLists()[t].spaceid;p.deleteWishList(n,p.successRequestWishList,p.errorRequestWishList)}for(var s=0;s<m.length;s++){var o="description "+m[s];p.addWishList(m[s],o,p.successCreateWishList,p.errorCreateWishList)}},successRequestWishList:function(e){console.log("WishList eliminada con exito:",e)},errorRequestWishList:function(e){e!=undefined&&console.error("Error: ",e.message)},successCreateWishList:function(t){console.log("WishList creada:",t),e.Topic(i.topicNames.SOCIAL_REFRESH_SPACES).publish()},errorCreateWishList:function(e){},getAutosUsadosCollectionId:function(){return a.USADOS.collectionId},deleteWishList:function(e,t,n){s.request("DELETE","/swm/rs/v1/spaces/{spaceid}","",t,n,{spaceid:e})},addWishList:function(e,t,n,r){var i={siteId:s.siteid,spaceName:e,spaceDescription:t,accessLevel:0};s.request("POST","/swm/rs/v1/spaces",i,n,r)},textoModalSimple:t.observable(),openSimpleMessageModal:function(t){p.textoModalSimple(t),e("#ocs-modal-message").modal("show")},searchSelected:function(){l.emptyGrowlMessages(),e.Topic(i.topicNames.OVERLAYED_GUIDEDNAVIGATION_HIDE).publish([{message:"success"}])},handleSearch:function(t,n){var s;a.SEARCH.CATEGORY_ID="autos-usados",a.saveCookie(a.REFINEMENTS.RANGE_COLLECTION_COOKIE,"autos-usados"),e.Topic(i.topicNames.SEARCH_TYPEAHEAD_CANCEL).publish([{message:"success"}]);var o=function(){var t=e.trim(p.searchText());t.length!=0&&(r.goTo("/searchresults?"+c.SEARCH_TERM_KEY+"="+encodeURIComponent(p.searchText().trim())+"&"+c.SEARCH_DYM_SPELL_CORRECTION_KEY+"="+encodeURIComponent(c.DYM_ENABLED)+"&"+c.SEARCH_NAV_ERECS_OFFSET+"=0&"+c.SEARCH_REC_PER_PAGE_KEY+"="+c.DEFAULT_SEARCH_RECORDS_PER_PAGE+"&"+c.SEARCH_RANDOM_KEY+"="+Math.floor(Math.random()*1e3)+"&"+c.SEARCH_TYPE+"="+c.SEARCH_TYPE_SIMPLE+"&"+c.SEARCH_SORT_ORDER+"="+"sku.activePrice|1"+"&"+c.PARAMETERS_TYPE+"="+c.PARAMETERS_SEARCH_QUERY+"&"+c.SEARCH_NAV_DESCRIPTORS_KEY+"="+s),p.searchText(""))},u=function(t){t&&Array.isArray(t)&&t.length>0&&t[0]&&t[0].dimensionId&&(e("#container-form-desktop").removeClass("show-form"),e("body").css("overflow-y","initial"),s=t[0].dimensionId,o())};a.getDimensionsIds("autos-usados",u)},openSearchBar:function(){e("#container-form-desktop").addClass("show-form"),document.getElementById("ocs-search-used-cars-text-input").focus(),e("body").css("overflow-y","hidden")},closeSearchBar:function(){e("#container-form-desktop").removeClass("show-form"),e("#bg-mobile").remove(),e("body").css("overflow-y","initial"),this.closeTypeahead()},redirectProduct:function(t){e("#bg-mobile").remove(),e("body").css("overflow-y","initial"),r.goTo(t)}}})
|