function venddSetCookie(cname,cvalue,exdays){var d=new Date;d.setTime(d.getTime()+24*exdays*60*60*1e3);var expires="expires="+d.toUTCString();document.cookie=cname+"="+cvalue+"; "+expires+"; path=/"}function venddGetCookie(cname){for(var name=cname+"=",ca=document.cookie.split(";"),i=0;i<ca.length;i++){for(var c=ca[i];" "==c.charAt(0);)c=c.substring(1);if(0==c.indexOf(name))return c.substring(name.length,c.length)}return""}function toArrayBuffer(buf){for(var ab=new ArrayBuffer(buf.length),view=new Uint8Array(ab),i=0;i<buf.length;++i)view[i]=buf[i];return ab}var decodeEntities=function(){var element=document.createElement("div");return function(str){return str&&"string"==typeof str&&(str=(str=str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gim,"")).replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gim,""),element.innerHTML=str,str=element.textContent,element.textContent=""),str}}();function allowOnlyNumbersInput($container){(!$container||$container.length<0)&&($container=$("html")),$('*[data-only-numbers="true"]',$container).keyup(function(){var value=this.value.replace(/[^0-9\.,]/g,"");this.value!=value&&(this.value=value)})}function stringToNumber(value){var returnValue,currency,decimal,val=""+value;return currency=LhApp.Context.Currency.Symbol,decimal=LhApp.Context.Currency.DecimalSeparator,returnValue=val.replace(currency,"").replace(decimal,".").trim(),parseFloat(returnValue).toFixed(2)}function numberToString(value,addCurrency,clearZeros){var returnValue,currency,decimal,fractional,val=""+value;return currency=LhApp.Context.Currency.Symbol,decimal=LhApp.Context.Currency.DecimalSeparator,returnValue=val.replace(currency,"").replace(".",decimal).trim(),clearZeros&&(fractional=returnValue.split(decimal)).length>1&&new RegExp("^[0\0]+$").test(fractional[1])&&(returnValue=fractional[0]),addCurrency&&(returnValue+=" "+currency),returnValue}var PostMessages=function(){var intervalId,lastHash,attachedCallback,window=this;return{receiveMessage:function(callback,sourceOrigin){window.postMessage?(callback&&(attachedCallback=function(e){if("string"==typeof sourceOrigin&&e.origin!==sourceOrigin||"[object Function]"===Object.prototype.toString.call(sourceOrigin)&&!1===sourceOrigin(e.origin))return!1;callback(e)}),window.addEventListener?window[callback?"addEventListener":"removeEventListener"]("message",attachedCallback,!1):window[callback?"attachEvent":"detachEvent"]("onmessage",attachedCallback)):(intervalId&&clearInterval(intervalId),intervalId=null,callback&&(intervalId=setInterval(function(){var hash=document.location.hash,re=/^#?\d+&/;hash!==lastHash&&re.test(hash)&&(lastHash=hash,callback({data:hash.replace(re,"")}))},100)))}}}();PostMessages.receiveMessage(function(message){"SetUser"===message.data.Action&&Vendd.MessageBus.publishAsync(Vendd.UserSelect,new Vendd.UserSelect.Messages.SubmitSetInterfaceUserInlineAdmin({LoginName:message.data.UserEmail.trim(),RedirectToAccount:message.data.RedirectToAccount})),"SetOrder"===message.data.Action&&Vendd.MessageBus.publishAsync(Vendd.UserSelect,new Vendd.UserSelect.Messages.SubmitSetInterfaceUserInlineAdmin({LoginName:message.data.UserEmail.trim(),RedirectToAccount:message.data.RedirectToAccount,OrderId:message.data.OrderId}))},LhApp.Context.InLineAdminEndpoint),LhApp=LhApp||{},LhApp.Function={},LhApp.Function.Url={},LhApp.Function.QueryString={},LhApp.Function.String={},LhApp.Function.Tracking={},LhApp.Function.Actions={},LhApp.Function.Actions.ActionsType={ORDER_COMPLETION:0},LhApp.Function.Actions.StorageType={SESSION:0,PERSISTENT:1,CROSS_TABS_SESSION:2},LhApp.Function.Actions.Counter=function(actionsType,storageType,actionIdentifier){var storekey="Vendd:Actions.Counter",storage=storageType==LhApp.Function.Actions.ActionsType.PERSISTENT?localStorage:sessionStorage,action=actionsType+(actionIdentifier?":"+actionIdentifier:actionIdentifier);this.getCount=function(){var store=JSON.parse(storage.getItem(storekey))||{};return parseInt(store[action]||0)},this.increment=function(){var store=JSON.parse(storage.getItem(storekey))||{};store[action]=(parseInt(store[action])||0)+1,storage.setItem(storekey,JSON.stringify(store))},this.reset=function(){var store=JSON.parse(storage.getItem(storekey))||{};store[action]=void 0,storage.setItem(storekey,JSON.stringify(store))}},LhApp.Function.Tracking.updateTrackingData=function(updateData){window.TrackingData=$.extend(!0,{},window.TrackingData,updateData)},LhApp.Function.Tracking.ga=function(){return!!LhApp.Function.Tracking.canTrack("statisticCookies")&&(!!LhApp.Function.Tracking.InitGoogleAnalytics()&&("undefined"!=typeof ga&&(ga.apply(null,arguments),!0)))},LhApp.Function.Tracking.canTrack=function(cookieType){var Consents="undefined"!=typeof ConsentsManager&&ConsentsManager||"undefined"!=typeof CheckoutConsentsManager&&CheckoutConsentsManager;return!!Consents&&(cookieType||(cookieType="marketingCookies"),void 0!==Consents.cookiesStatus[cookieType]&&(!LhApp.Context.IsConsentsEnabled||Consents.cookiesStatus[cookieType]))},LhApp.Function.Tracking.getTrackingModel=function(){var trackingModel=window.TrackingData;return trackingModel&&trackingModel.IsTrackingEnabled?JSON.parse(JSON.stringify(trackingModel)):null},LhApp.Function.Tracking.getTracker=function(trackerCode,trackingModel){if(!trackingModel||!trackingModel.IsTrackingEnabled)return null;var tracker=trackingModel.Trackers[trackerCode.toLowerCase()];return tracker&&tracker.Properties?tracker:null},LhApp.Function.Tracking.getFeedItemId=function(product,datasource,tracker){if(product.FeedCodes&&product.FeedCodes[tracker.FeedCodeField])return product.FeedCodes[tracker.FeedCodeField];var productId,colorId,sizeId,dim3Id,dim4Id,dim5Id,dim6Id,merchantId;if("ProductChanged"==datasource){productId=product.ParentProductId;var colors=product.Dimensions.find(function(i){return i.IsColor}),sizes=product.Dimensions.find(function(i){return i.IsSize}),dim3s=product.Dimensions.find(function(i){return i.IsDim3}),dim4s=product.Dimensions.find(function(i){return i.IsDim4}),dim5s=product.Dimensions.find(function(i){return i.IsDim5}),dim6s=product.Dimensions.find(function(i){return i.IsDim6}),merchants=product.Dimensions.find(function(i){return i.IsMerchant}),color=colors&&colors.Versions.find(function(i){return i.ProductId==product.SelectedProductId}),size=sizes&&sizes.Versions.find(function(i){return i.ProductId==product.SelectedProductId}),dim3=dim3s&&dim3s.Versions.find(function(i){return i.ProductId==product.SelectedProductId}),dim4=dim4s&&dim4s.Versions.find(function(i){return i.ProductId==product.SelectedProductId}),dim5=dim5s&&dim5s.Versions.find(function(i){return i.ProductId==product.SelectedProductId}),dim6=dim6s&&dim6s.Versions.find(function(i){return i.ProductId==product.SelectedProductId}),merchant=merchants&&merchants.Versions.find(function(i){return i.ProductId==product.SelectedProductId});colorId=color&&color.VersionId,sizeId=size&&size.VersionId,dim3Id=dim3&&dim3.VersionId,dim4Id=dim4&&dim4.VersionId,dim5Id=dim5&&dim5.VersionId,dim6Id=dim6&&dim6.VersionId,merchantId=merchant&&merchant.VersionId}else productId=product.ProductId,colorId=product.ColorId,sizeId=product.SizeId,dim3Id=product.Dim3Id,dim4Id=product.Dim4Id,dim5Id=product.Dim5Id,dim6Id=product.Dim6Id,merchantId=product.MerchantId;return colorId&&parseInt(colorId)>0&&(productId+="-"+colorId),tracker.SplitFeedBySize&&sizeId&&parseInt(sizeId)>0&&(productId+="-"+sizeId),tracker.SplitFeedByDim3&&dim3Id&&parseInt(dim3Id)>0&&(productId+="-"+dim3Id),tracker.SplitFeedByDim4&&dim4Id&&parseInt(dim4Id)>0&&(productId+="-"+dim4Id),tracker.SplitFeedByDim5&&dim5Id&&parseInt(dim5Id)>0&&(productId+="-"+dim5Id),tracker.SplitFeedByDim6&&dim6Id&&parseInt(dim6Id)>0&&(productId+="-"+dim6Id),tracker.SplitFeedByMerchant&&merchantId&&parseInt(merchantId)>0&&(productId+="-M"+merchantId),productId},LhApp.Function.Tracking.gtag=function(){window.dataLayer=window.dataLayer||[],dataLayer.push(arguments)},LhApp.Function.Tracking.InitGoogleTagManager=function(tagManagerCode){var trackingModel=LhApp.Function.Tracking.getTrackingModel();if(void 0===tagManagerCode){if(!trackingModel||!trackingModel.GoogleTagManagerCode)return!1;tagManagerCode=trackingModel.GoogleTagManagerCode}if(!tagManagerCode)return!1;if(window.googleTagManagerInitialized)return!0;var consentsManager=window.ConsentsManager||window.CheckoutConsentsManager,cookiesStatus=consentsManager&&consentsManager.cookiesStatus;if(trackingModel.LoadTagManagerWhenConsentsGranted&&!(cookiesStatus&&cookiesStatus.marketingCookies&&cookiesStatus.statisticCookies&&cookiesStatus.functionalityCookies))return!1;trackingModel.EnableGoogleTagManagerConsents&&LhApp.Function.Tracking.gtag("consent","default",{ad_storage:cookiesStatus&&cookiesStatus.marketingCookies?"granted":"denied",analytics_storage:cookiesStatus&&cookiesStatus.statisticCookies?"granted":"denied",functionality_storage:cookiesStatus&&cookiesStatus.functionalityCookies?"granted":"denied"}),function(w,d,s,l,i){w[l]=w[l]||[],w[l].push({"gtm.start":(new Date).getTime(),event:"gtm.js"});var f=d.getElementsByTagName(s)[0],j=d.createElement(s);j.async=!0,j.src="https://www.googletagmanager.com/gtm.js?id="+i,f.parentNode.insertBefore(j,f)}(window,document,"script","dataLayer",tagManagerCode),window.googleTagManagerInitialized=!0;var consentsCookie=Cookies.getJSON("ConsentChecked");return consentsCookie&&window.dataLayer.push({functionalityCookiesEnabled:consentsCookie.functionalityCookies,marketingCookiesEnabled:consentsCookie.marketingCookies,statisticCookiesEnabled:consentsCookie.statisticCookies}),cookiesStatus&&(consentsManager.cookiesStatus.userHasSetCookies||LhApp.Context.CookiesDefaultActive)&&dataLayer.push({event:"vendd_consents_ready"}),!0},LhApp.Function.Tracking.InitGoogleAnalytics=function(analyticsCode){if(void 0===analyticsCode){var trackingModel=LhApp.Function.Tracking.getTrackingModel();if(!trackingModel||!trackingModel.GoogleAnalyticsCode)return!1;analyticsCode=trackingModel.GoogleAnalyticsCode}return!!analyticsCode&&(!!window.googleAnalyticsInitialized||(window.googleAnalyticsInitialized=!0,i=window,s=document,o="script",r="ga",i.GoogleAnalyticsObject=r,i.ga=i.ga||function(){(i.ga.q=i.ga.q||[]).push(arguments)},i.ga.l=1*new Date,a=s.createElement(o),m=s.getElementsByTagName(o)[0],a.async=1,a.src="https://www.google-analytics.com/analytics.js",m.parentNode.insertBefore(a,m),ga("create",analyticsCode,"auto"),!0));var i,s,o,r,a,m},LhApp.Function.Url.getServiceEndpoint=function(url){var rewritedUrl=LhApp.Context.Request.BaseUrl+"/services/";if(rewritedUrl+=url,-1!=unescape(LhApp.Context.Request.FriendlyUrl).indexOf("?")){var queryString="",initialQueryString=unescape(LhApp.Context.Request.FriendlyUrl).substring(unescape(LhApp.Context.Request.FriendlyUrl).indexOf("?")+1),iid=LhApp.Function.QueryString.getValueOf("iid",unescape(LhApp.Context.Request.RawUrl));""!=iid?queryString="iid="+iid:LhApp.Context.Item&&LhApp.Context.Item.Id&&(queryString="iid="+LhApp.Context.Item.Id),-1==rewritedUrl.indexOf(initialQueryString)&&(initialQueryString.length>0&&(queryString+="&"+initialQueryString),queryString=-1==rewritedUrl.indexOf("?")?"?"+queryString:"&"+queryString),rewritedUrl+=queryString}var domainUrl=(rewritedUrl=rewritedUrl.replace("?&","?")).split("?"),qsrt="";if(domainUrl.length>1){var qArray=domainUrl[1].split("&");for(i=0;i<qArray.length;i++)""!=qArray[i]&&""!=qArray[i]&&-1==qsrt.indexOf(qArray[i])&&(qsrt+=(0==i?"?":"&")+qArray[i])}return domainUrl[0]+qsrt},LhApp.Function.QueryString.parse=function(url){var qparts,qpart,qparams={},parts=(url||"").split("?"),i=0;if(parts.length<=1)return qparams;for(i in qparts=parts[1].split("&")){qpart=qparts[i].split("=");var pName=decodeURIComponent(qpart[0]).toLowerCase(),pValue=decodeURIComponent(qpart[1]||"");qparams[pName]=pValue}return qparams},LhApp.Function.QueryString.getValueOf=function(parameterKey,url){var parameterValue="",queryString="";(url=url||window.location.href).indexOf("?")>-1&&(queryString=url.substring(url.indexOf("?")+1));var parameters=queryString.split("&");if(queryString.indexOf(parameterKey)>=0)for(var i=0;i<parameters.length;i++){var pair=parameters[i].split("=");pair[0]==parameterKey&&(parameterValue=pair[1])}return parameterValue},LhApp.Function.Url.setParameterValue=function(parameterKey,parameterValue){var url=window.location.href;return this.setParameterValueOnUrl(url,parameterKey,parameterValue)},LhApp.Function.Url.setParameterValueOnUrl=function(url,parameterKey,parameterValue){var queryString="",hasQueryString=url.indexOf("?")>-1;hasQueryString&&(queryString=url.substring(url.indexOf("?")+1));var parameters=queryString.split("&");if(queryString.indexOf(parameterKey)>=0){for(var i=0;i<parameters.length;i++){var pair=parameters[i].split("=");pair[0]==parameterKey&&(parameters[i]=pair[0]+"="+parameterValue)}queryString=parameters.join("&")}else queryString+=hasQueryString?"&"+parameterKey+"="+parameterValue:"?"+parameterKey+"="+parameterValue;return hasQueryString?url.substring(0,url.indexOf("?")+1)+queryString:url+queryString},LhApp.Function.Url.removeParameter=function(parameterKey){var url=window.location.href,parameterKeys=[parameterKey];return this.removeParametersFromUrl(url,parameterKeys)},LhApp.Function.Url.removeParameterFromUrl=function(url,parameterKey){var parameterKeys=[parameterKey];return this.removeParametersFromUrl(url,parameterKeys)},LhApp.Function.Url.removeParameters=function(parameterKeys){var url=window.location.href;return this.removeParametersFromUrl(url,parameterKeys)},LhApp.Function.Url.removeParametersFromUrl=function(url,parameterKeys){var newUrl=url;return $.each(parameterKeys,function(index,parameterKey){var queryString="";if(newUrl.indexOf("?")>-1){var parameters=(queryString=newUrl.substring(newUrl.indexOf("?")+1)).split("&");if(queryString.indexOf(parameterKey)>=0){for(var i=0;i<parameters.length;i++){parameters[i].split("=")[0]==parameterKey&&parameters.splice(i,1)}queryString=parameters.join("&"),newUrl=""!=queryString?newUrl.substring(0,newUrl.indexOf("?")+1)+queryString:newUrl.substring(0,newUrl.indexOf("?"))+queryString}}}),newUrl},LhApp.Function.getText=function(key){if(void 0===LhApp.Text)return"";var match=LhApp.Text[key];if(void 0===match){var resource=LhApp.Function.getTranslatableTextFromServer(key);LhApp.Text[key]=resource,match=resource}return match||""},LhApp.Function.getTranslatableTextFromServer=function(key){var result=key;return $.ajax({async:!1,type:"POST",dataType:"json",contentType:"application/json; charset=UTF-8",ContentType:"application/json; charset=UTF-8",url:LhApp.Function.Url.getServiceEndpoint("commonservice.svc/GetTranslatableResource"),data:JSON.stringify({key:key}),success:function(response){result=response.d}}),result},LhApp.Function.String.isEmail=function(text){return/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,20}|^$/i.test(text)},LhApp.Function.String.isAlphaNumeric=function(text){return text.match(/^[0-9a-zA-Z]+$/)||!1},LhApp.Function.initVisitorState=function(){var cookieValue=Cookies.get("VisitorState");cookieValue?LhApp.Function.checkAndUpdateVisitorState(cookieValue):Vendd.Service.call({url:"CmsService.svc/InitVisitorState",data:null,onSuccess:function(res){cookieValue=Cookies.get("VisitorState"),res.success&&cookieValue&&LhApp.Function.checkAndUpdateVisitorState(cookieValue)}})},LhApp.Function.checkAndUpdateVisitorState=function(cookieValue){if(cookieValue){var oldUrl=window.location.href,cookieValueAsUrl="?"+cookieValue;$("body").removeClass("x-checking-visitor-state").removeAttr("x-checking-visitor-state");var oldLanguageCode=LhApp.Function.QueryString.getValueOf("languageCode",cookieValueAsUrl).toLowerCase(),newLanguageCode=LhApp.Function.QueryString.getValueOf("lang",oldUrl).toLowerCase();""!=newLanguageCode&&newLanguageCode!=oldLanguageCode&&(cookieValue=LhApp.Function.Url.setParameterValueOnUrl(cookieValueAsUrl,"languageCode",newLanguageCode).replace("?",""),Cookies.set("VisitorState",cookieValue,{secure:LhApp.Context.Request.IsSecure,samesite:"Lax"}),cookieValueAsUrl="?"+cookieValue);var oldCountryCode=LhApp.Function.QueryString.getValueOf("countryCode",cookieValueAsUrl).toLowerCase(),newCountryCode=LhApp.Function.QueryString.getValueOf("country",oldUrl).toLowerCase();""!=newCountryCode&&newCountryCode!=oldCountryCode&&(cookieValue=LhApp.Function.Url.setParameterValueOnUrl(cookieValueAsUrl,"countryCode",newCountryCode).replace("?",""),Cookies.set("VisitorState",cookieValue,{secure:LhApp.Context.Request.IsSecure,samesite:"Lax"}),cookieValueAsUrl="?"+cookieValue);var oldCurrencyCode=LhApp.Function.QueryString.getValueOf("currencyCode",cookieValueAsUrl).toLowerCase(),newCurrencyCode=LhApp.Function.QueryString.getValueOf("currency",oldUrl).toLowerCase();""!=newCurrencyCode&&newCurrencyCode!=oldCurrencyCode&&(cookieValue=LhApp.Function.Url.setParameterValueOnUrl(cookieValueAsUrl,"currencyCode",newCurrencyCode).replace("?",""),Cookies.set("VisitorState",cookieValue,{secure:LhApp.Context.Request.IsSecure,samesite:"Lax"}),cookieValueAsUrl="?"+cookieValue)}},LhApp.Function.hideExpandables=function(wrapper){$("*[data-expandablecontainer].x-expanded:not(.x-loading)",$(wrapper)).each(function(i,item){var $expandable=$(item);$expandable.removeClass("x-expanded"),$('*[data-expandabletrigger="'+$expandable.data("expandablecontainer")+'"].x-open',$(wrapper)).removeClass("x-open")})},LhApp.Function.bindUndropables=function(wrapper){var $wrapper=$(wrapper);$("*[data-undropable]",$wrapper).on("drop",function(e){"function"==typeof e.preventDefault&&e.preventDefault()})},LhApp.Function.bindExpandables=function(wrapper){var $wrapper=$(wrapper);$("*[data-expandablecontainer]",$wrapper).click(function(e){e.stopPropagation()}),$("*[data-expandabletrigger]",$wrapper).each(function(i,item){var triggerValue=$(item).data("expandabletrigger"),$expandableContainer=$('*[data-expandablecontainer="'+triggerValue+'"]',$wrapper),$triggers=$('*[data-expandabletrigger="'+triggerValue+'"]',$wrapper);$expandableContainer.length>0&&($triggers.unbind("click"),$triggers.click(function(e){e.preventDefault(),e.stopPropagation(),$("*[data-expandablecontainer].x-expanded").each(function(w,wItem){var wItemContainer=$(wItem).data("expandablecontainer");wItemContainer!=triggerValue&&($(wItem).removeClass("x-expanded"),$('*[data-expandabletrigger="'+wItemContainer+'"].x-open').removeClass("x-open"))}),$expandableContainer.hasClass("x-expanded")?($expandableContainer.removeClass("x-expanded"),$triggers.removeClass("x-open")):($expandableContainer.addClass("x-expanded"),$triggers.addClass("x-open"),EventManager.trigger("lazyload"))}))})},LhApp.Function.isButtonDisabled=function(buttonWrapper){var isDisabled=!1;if("input"==$(buttonWrapper).get(0).tagName.toLowerCase())$(buttonWrapper).is(":disabled")&&(isDisabled=!0);else{var $internalButton=$(buttonWrapper).find("input:button");$internalButton.length>0?$internalButton.is(":disabled")&&(isDisabled=!0):$(buttonWrapper).hasClass("x-disabled")&&(isDisabled=!0)}return isDisabled},LhApp.Function.bindHrefButtons=function(wrapper){$("*[data-href]",$(wrapper)).click(function(e){void 0!==e&&"function"==typeof e.preventDefault&&e.preventDefault(),LhApp.Function.isButtonDisabled(this)?e.preventDefault():document.location=$(this).data("href")})},LhApp.Function.bindScrollable=function(wrapper){$("*[data-scroll-to]",$(wrapper)).click(function(){var $this=$(this),element=$this.data("scroll-to"),time=void 0===(time=$this.data("scroll-time"))||""==time?600:time,offset=void 0===(offset=$this.data("scroll-offset"))||""==offset?-10:offset;""!=element&&("top"==element&&$("html, body").animate({scrollTop:0},time),"bottom"==element&&$("html, body").animate({scrollTop:$("body").height()},time),$(element).length>0&&$("html, body").animate({scrollTop:$(element).offset().top+offset},time))})},LhApp.Function.bindLazyLoadableImages=function(wrapper){($(wrapper).data("lazy-load-init")?$(wrapper):$("*[data-lazy-load-init]",$(wrapper))).each(function(i,innerWrapper){var $innerWrapper=$(innerWrapper),$lazyLoadOptions=$('*[data-input="lazy-load-options"]',$innerWrapper);if($innerWrapper.data("lazy-load-init")){var opts={},defOptions={effect:"fadeIn"};1==$lazyLoadOptions.length?$.extend(!0,opts,defOptions,JSON.parse($lazyLoadOptions.val())):$.extend(!0,opts,defOptions);var $images=$("img[data-lazyload]",$innerWrapper);$images.length>0&&"function"==typeof $.fn.lazyload&&$($images,$innerWrapper).lazyload(opts)}$lazyLoadOptions.length>0&&$lazyLoadOptions.remove()}),-1==$.inArray("lazyload",EventManager.events)&&EventManager.bind("lazyload",function(){$(window).trigger("lazyload")})},LhApp.Function.PageTrackingRequest=function(){var url=decodeURIComponent(LhApp.Context.Request.RawUrl),dataItem={querystring:url.substring(url.indexOf("?")+1),cookie:document.cookie};Vendd.Service.call({url:"MarkService.svc/PageTracking",data:{query:dataItem},onSuccess:function(res){for(var cookies=res,i=0;i<cookies.length;i++)document.cookie=cookies[i].Name+"="+cookies[i].Value+"; expires="+new Date(cookies[i].Expires).toUTCString()+"; path="+cookies[i].Path}})},LhApp.Function.MailChimpEcommerce360Tracking=function(oId,cId,eId){Vendd.Service.call({url:"MarkService.svc/MailChimpEcommerce360Tracking",data:{orderId:oId,campaignId:cId,emailId:eId}})},LhApp.Function.applyExchangeRate=function(price){return LhApp.Function.applyExchangeRateExtended(price,LhApp.Context.Currency.ExchangeRate)},LhApp.Function.applyExchangeRateExtended=function(price,rate){return price*rate},LhApp.Function.showProductWishlists=function($wrapper,product){if(LhApp.Context.MultipleWishlistsEnabled&&0!=$wrapper.length){$wrapper.addClass("x-loading");var $wishlistsWrapper=$(".js-wishlist-lists",$wrapper),model=Vendd.UserWishlist.GetClientModel();model=$.extend({},model,{Product:product});var html=Vendd.Handlebars.parse("productWishlists",model);$wishlistsWrapper.html(html),LhApp.Function.bindProductWishlists($wrapper),$wishlistsWrapper.show(),$wrapper.removeClass("x-loading")}},LhApp.Function.bindProductWishlists=function($wrapper){LhApp.Context.MultipleWishlistsEnabled&&($(".js-list-select",$wrapper).on("click",function(){var $this=$(this),$wishlistsWrapper=$this.closest(".js-product-wishlists"),$wrper=$this.closest(".product-wishlist"),qs=LhApp.Function.QueryString.getValueOf("list"),id=$wishlistsWrapper.data("id"),skuId=$wishlistsWrapper.data("skuid"),path=$wishlistsWrapper.data("path"),qty=$wishlistsWrapper.data("qty"),listId=$wrper.data("list-id"),currentListId=qs&&parseInt(qs)||0;Vendd.MessageBus.publishAsync($wrapper.get(0),new Vendd.Wishlist.Messages.Add(id,skuId,path,qty,[],[],listId,currentListId)),Vendd.MessageBus.publishAsync($wrapper.get(0),new Vendd.Widget.Messages.OpenWidget(Vendd.Widget.WishlistWidget,!1)),LhApp.Function.hideAllProductWishlists()}),$wrapper.on("click",".js-close-product-wishlists",function(e){e.preventDefault(),LhApp.Function.hideAllProductWishlists()}))},LhApp.Function.hideAllProductWishlists=function(){LhApp.Context.MultipleWishlistsEnabled&&$.each($(".js-wishlist-lists"),function(i,el){$(el).html(""),$(el).hide()})};var RenderPrice=function(price){return LhApp.Function.renderPriceExtended(price,!1," ","","")},RenderPriceExtended=function(price,isShopDefaultCurrency,separatorSymbol,prefixSymbol,suffixSymbol){return LhApp.Function.renderPriceExtended(price,isShopDefaultCurrency,separatorSymbol,prefixSymbol,suffixSymbol)};LhApp.Function.renderPrice=function(price){return LhApp.Function.renderPriceExtended(price,!1," ","","")},LhApp.Function.renderPriceExtended=function(price,isShopDefaultCurrency,separatorSymbol,prefixSymbol,suffixSymbol){var symbol=LhApp.Context.Currency.Symbol,numberOfDigits=LhApp.Context.Currency.NumberOfDigits,symbolShownFirst=LhApp.Context.Currency.SymbolShownFirst,doShowSymbol=LhApp.Context.Currency.DoShowSymbol;isShopDefaultCurrency&&(symbol=LhApp.Context.ShopDefaultCurrency.Symbol,numberOfDigits=LhApp.Context.ShopDefaultCurrency.NumberOfDigits,symbolShownFirst=LhApp.Context.ShopDefaultCurrency.SymbolShownFirst,doShowSymbol=LhApp.Context.ShopDefaultCurrency.DoShowSymbol);var formatedPrice=price.toFixed(numberOfDigits).replace(".",",");return doShowSymbol&&(formatedPrice=symbolShownFirst?symbol+separatorSymbol+formatedPrice:formatedPrice+separatorSymbol+symbol),""!=prefixSymbol&&(formatedPrice=prefixSymbol+separatorSymbol+formatedPrice),""!=suffixSymbol&&(formatedPrice=formatedPrice+separatorSymbol+suffixSymbol),formatedPrice};var RenderPointsPrice=function(pointsPrice){return LhApp.Function.renderPointsPriceExtended(pointsPrice,","," ","","")},RenderPointsPriceExtended=function(pointsPrice,commaSymbol,separatorSymbol,prefixSymbol,suffixSymbol){return LhApp.Function.renderPointsPriceExtended(pointsPrice,commaSymbol,prefixSymbol,suffixSymbol)};LhApp.Function.renderPointsPriceExtended=function(pointsPrice,commaSymbol,separatorSymbol,prefixSymbol,suffixSymbol){""==suffixSymbol&&(suffixSymbol=1===pointsPrice?"point":"points");var innerSuffixSymbol=suffixSymbol.length>1?" "+LhApp.Function.getText("Common:PointsPriceSymbol_"+suffixSymbol):suffixSymbol,formatedPrice=pointsPrice.toFixed(2).replace(".00","").replace(".",commaSymbol);return""!=prefixSymbol&&(formatedPrice=prefixSymbol+separatorSymbol+formatedPrice),""!=innerSuffixSymbol&&(formatedPrice=formatedPrice+separatorSymbol+innerSuffixSymbol),formatedPrice},LhApp.Function.validateClientModel=function(model){return!!model&&!(!model.LangCode||model.LangCode!=LhApp.Context.Language)};var ReplacePrices=function(obj){$(".x-product-box[data-productid]").each(function(i,el){var itemId=parseInt($(el).attr("data-productid")),itemData=obj.filter(function(a){return a.Id===itemId})[0],DeletedPrice=parseFloat(itemData.DeletedPrice),Price=parseFloat(itemData.Price),TotalPointsPrice=parseFloat(itemData.TotalPointsPrice),TotalPointsGain=parseFloat(itemData.TotalPointsGain),PointsPrice=parseFloat(itemData.PointsPrice),PointsGain=parseFloat(itemData.PointsGain);$(".prices",el).addClass("hide"),$(".deleted-price-container",el).addClass("hide"),$(".current-price-container",el).addClass("hide"),$(".current-point-price-container.1",el).addClass("hide"),$(".current-point-price-container.2",el).addClass("hide"),$(".current-point-price-container.3",el).addClass("hide"),$(".current-point-price-container.4",el).addClass("hide"),(DeletedPrice>0||Price>0||TotalPointsPrice>0||TotalPointsGain>0||PointsPrice>0||PointsGain>0)&&($(".prices",el).removeClass("hide"),DeletedPrice>0&&DeletedPrice>Price&&($(".deleted-price-container",el).removeClass("hide"),$(".deleted-price",el).text(RenderPrice(itemData.DeletedPrice))),Price>0&&($(".current-price-container",el).removeClass("hide"),$(".current-price",el).text(RenderPrice(itemData.Price))),PointsPrice>0&&PointsPrice!=TotalPointsPrice&&($(".current-point-price-container.1",el).removeClass("hide"),$(".current-point-price-container.1 .points-price",el).text(RenderPointsPrice(PointsPrice))),TotalPointsGain>0&&($(".current-point-price-container.2",el).removeClass("hide"),$(".current-point-price-container.2 .points-gain",el).text(RenderPointsPrice(TotalPointsGain))),PointsGain>0&&0===TotalPointsGain&&($(".current-point-price-container.3",el).removeClass("hide"),$(".current-point-price-container.3 .points-gain",el).text(RenderPointsPrice(PointsGain))),TotalPointsPrice>0&&($(".current-point-price-container.4",el).removeClass("hide"),$(".current-point-price-container.4 .points-price",el).text(RenderPointsPrice(TotalPointsPrice))))})},ReplaceAvailabilities=function(obj){$(".x-product-box[data-productid]").each(function(i,el){var itemId=parseInt($(el).attr("data-productid")),itemData=obj.filter(function(a){return a.Id===itemId})[0],cartEnabled=!0===itemData.CanBuy||!0===itemData.CanBuyWithPoints;itemData.CanAddToList;$(".buttons .add-to-cart").length>0&&$(".buttons .add-to-cart input").length>0&&($(".buttons .add-to-cart").addClass("x-disabled"),$(".buttons .add-to-cart input").attr("disabled","disabled"),!0===cartEnabled&&($(".buttons .add-to-cart").removeClass("x-disabled"),$(".buttons .add-to-cart input").removeAttr("disabled","disabled")))})};LhApp.Function.validateTaxIdentifier=function(isInvoice,countryCode,taxIdentifier){if(!0===isInvoice&&taxIdentifier.length>0){if("GR"!==countryCode)return!0;if(!isNaN(parseInt(taxIdentifier))&&9===taxIdentifier.length){for(var result=0,arrTaxId=taxIdentifier.split("").map(function(item){return parseInt(item)}),i=arrTaxId.length-2;i>=0;i--)result+=arrTaxId[i]*Math.pow(2,8-i);return result%11%10===arrTaxId[8]}}return!1},LhApp.pauseScroll=!1,LhApp.init=function(){LhApp.Function.bindScrollable($("body").get(0)),LhApp.Function.bindExpandables($("body").get(0)),LhApp.Function.bindHrefButtons($("body").get(0)),LhApp.Function.bindUndropables($("body").get(0)),$("body").click(function(e){LhApp.Function.hideExpandables(this)}),$(document).scroll(function(e){LhApp.pauseScroll||LhApp.Function.hideExpandables($("body").get(0))})};var disqus_config=function(){LhApp.Context.Item.Id&&LhApp.Context.Request.FriendlyUrl&&(this.page.url=LhApp.Context.Request.BaseUrl+LhApp.Context.Request.FriendlyUrl,this.page.identifier=LhApp.Context.Item.Id)},replaceIframe=function(idFrame,url){var originalFrame=document.getElementById(idFrame),newFrame=document.createElement("iframe");newFrame.id=originalFrame.getAttribute("id"),newFrame.width=originalFrame.getAttribute("width"),newFrame.height=originalFrame.getAttribute("height"),newFrame.style.display="none",newFrame.src=url,originalFrame.parentNode.replaceChild(newFrame,originalFrame)},convertToGreek=function(){$("input[type='text'].js-convert-to-greek").keyup(function(){if(!$(this).closest(".form-row").find(".js-disable-conversion").is(":checked")){for(var str=$(this).val().toUpperCase(),newstr=[],i=0,len=str.length;i<len;i++)newstr[i]=convertCharacters(str[i]);$(this).val(newstr.join("")),$(this).trigger("input")}})},convertToUppercase=function(){$("input[type='text'].js-convert-to-uppercase").keyup(function(){if(!$(this).closest(".form-row").find(".js-disable-conversion").is(":checked")){var str=$(this).val().toUpperCase();str=str.replace(/Ά/g,"Α").replace(/Έ/g,"Ε").replace(/Ή/g,"Η").replace(/Ί/g,"Ι").replace(/Ό/g,"Ο").replace(/Ύ/g,"Υ").replace(/Ώ/g,"Ω"),$(this).val(str),$(this).trigger("input")}})},convertCharacters=function(character){switch(character){case"A":character="Α";break;case"B":character="Β";break;case"C":character="Ψ";break;case"D":character="Δ";break;case"E":character="Ε";break;case"F":character="Φ";break;case"G":character="Γ";break;case"H":character="Η";break;case"I":character="Ι";break;case"J":character="Ξ";break;case"K":character="Κ";break;case"L":character="Λ";break;case"M":character="Μ";break;case"N":character="Ν";break;case"O":character="Ο";break;case"P":character="Π";break;case"Q":character="Κ";break;case"R":character="Ρ";break;case"S":character="Σ";break;case"T":character="Τ";break;case"U":character="Θ";break;case"V":character="Ω";break;case"W":character="Σ";break;case"X":character="Χ";break;case"Y":character="Υ";break;case"Z":character="Ζ"}return character};if("object"==typeof localStorage)try{localStorage.setItem("localStorage",1),localStorage.removeItem("localStorage")}catch(e){Storage.prototype._setItem=Storage.prototype.setItem,Storage.prototype.setItem=function(){}}$(document).ready(function(){window.ScriptsActivator.funcLoaded=!1,window.ScriptsActivator.markLoaded=!1,window.ScriptsActivator.statLoaded=!1,window.ScriptsActivator.loadScripts=function(scripts){if(0!==Object.keys(scripts).length)for(var key in scripts){var s=scripts[key];if("function"==typeof s)s.call();else for(var skey in s){var ss=s[skey];"function"==typeof ss&&ss.call()}}},window.ScriptsActivator.loadFunctionalityScripts=function(){this.loadScripts(window.ScriptsActivator.funcFn),this.funcLoaded=!0},window.ScriptsActivator.loadMarketingScripts=function(){this.loadScripts(window.ScriptsActivator.markFn),this.markLoaded=!0},window.ScriptsActivator.loadStatisticsScripts=function(){this.loadScripts(window.ScriptsActivator.statFn),this.statLoaded=!0},window.ScriptsActivator.loadAllScripts=function(func,mark,stat){func&&!this.funcLoaded&&this.loadFunctionalityScripts(),mark&&!this.markLoaded&&this.loadMarketingScripts(),stat&&!this.statLoaded&&this.loadStatisticsScripts()},window.ScriptsActivator.removeScriptsElements=function(){$("script[data-script]").each(function(a,script){script&&$(script).remove()})},window.ScriptsActivator.removeScriptsElements()});var Vendd=function(Vendd){"use strict";var _recipes={},returnResponse=function(recipeId,statusCode,errorCode,data){return{success:200===statusCode,data:data||{},status:{statusCode:statusCode,recipeId:recipeId,ErrorCode:errorCode||0}}},getRecipe=function(model,recipeId){var recipeModel=model||testModel,recipe=_.isArray(recipeModel)?_.first(_.filter(recipeModel,function(x){return x.RecipeId===recipeId&&x.TotalCount>0})):recipeModel;return $.extend(!0,{},recipe)},getTotalQuantity=function(model,ingredientId){var items=_.filter(model.RecipeItems,function(item){return item.IngredientId!==ingredientId});return _.reduce(items,function(memo,item){return memo+(item.Quantity||0)},0)},getGroupQuantity=function(model,group,ingredientId){var items=_.filter(model.RecipeItems,function(item){return item.GroupId===group.Id&&item.IngredientId!==ingredientId});return _.reduce(items,function(memo,item){return memo+(item.Quantity||0)},0)};Vendd.RecipeLibrary=Vendd.RecipeLibrary||{},Vendd.RecipeLibrary.DeclareState=function(model,recipeId){if(!_recipes[recipeId])return returnResponse(recipeId,500,1e3);_recipes[recipeId]=model;var data={};return data.recipe=$.extend(!0,{},model),data.isValid=!0,returnResponse(recipeId,200,0,data)},Vendd.RecipeLibrary.GetModel=function(recipeId){return _recipes[recipeId]?returnResponse(recipeId,200,0,_recipes[recipeId]):returnResponse(recipeId,500,1e3)},Vendd.RecipeLibrary.InitRecipe=function(model,recipeId,force){if(force=force||!1,_recipes[recipeId]&&!force)return returnResponse(recipeId,500,1e3);var recipe=getRecipe(model,recipeId);return recipe?(_recipes[recipeId]=recipe,_recipes[recipeId].AFirstInclusion=1,_recipes[recipeId].Ingredients=[],_recipes[recipeId].Groups=[],_recipes[recipeId].RecipeItems=[],$.each(recipe.Categories,function(indexCategory,category){$.each(category.Groups,function(indexGroup,group){$.each(group.VisualGroups,function(indexGroup,visualgroup){var groupItems=_.reduce(visualgroup,function(vg,sum){return vg.length+sum});if(group.IsMultiSelect=!(group.MinQuantity<=1&&1===group.MaxQuantity&&groupItems>1),group.DefaultQuantities=0,!group.IsMultiSelect&&0===group.MinQuantity){var sampleOptionItemNone={CanRemove:!0,Category:category.Category,DefaultQuantity:0,DeletedPrice:0,DeletedPriceText:"",Price:0,PriceText:"",PriceWithoutVat:0,PriceWithoutVatText:"",MinQuantity:0,MaxQuantity:1,Weight:0,Name:"None of below",OrderNumber:0,Quanta:1,QuantaText:"",RecipeGroupId:group.Id,RecipeGroupName:group.Name,IngredientId:0,Stock:1,TaxClassId:0,VariantId:0,IsNullable:!0};visualgroup.Items.unshift(sampleOptionItemNone)}($.each(visualgroup.Items,function(indexItem,item){group.DefaultQuantities+=item.DefaultQuantity,item.HasValidDefaultValues=item.MinQuantity<=item.DefaultQuantity&&item.MaxQuantity>=item.DefaultQuantity,item.DefaultQuantity=item.MinQuantity>item.DefaultQuantity?item.MinQuantity:item.MaxQuantity<item.DefaultQuantity?item.MaxQuantity:item.DefaultQuantity,item.IsMandatory=item.MinQuantity===item.DefaultQuantity||!item.CanRemove,item.Disabled=item.MinQuantity===item.DefaultQuantity&&item.MaxQuantity===item.DefaultQuantity&&item.DefaultQuantity>0||!item.CanRemove,item.Checked=item.IsDefault;var ingredient=item;ingredient.GroupId=group.Id,_recipes[recipeId].Ingredients.push(ingredient),item.Price<=0&&(item.Price=0,item.PriceText=""),ingredient.DefaultQuantity>0&&_recipes[recipeId].RecipeItems.push({RecipeId:recipeId,Category:ingredient.Category,CategoryCode:ingredient.CategoryCode,ManufacturerProductCode:ingredient.ManufacturerProductCode,GroupId:group.Id,IngredientId:ingredient.IngredientId,ProductItemCode:ingredient.RecipeItemCode,ProductItemId:ingredient.RecipeItemId,VariantId:ingredient.VariantId,Name:ingredient.Name||"",Quantity:ingredient.DefaultQuantity,Price:0,PriceWithoutVat:0,TotalPrice:0,TotalPriceWithoutVat:0,Weight:ingredient.Weight||0,IsStandard:ingredient.DefaultQuantity>0,SubRecipeId:ingredient.SubRecipeId,SubRecipeCode:ingredient.SubRecipeCode})}),group.HasValidDefaultValues=group.MinQuantity<=group.DefaultQuantities&&group.MaxQuantity>=group.DefaultQuantities,group.IsMultiSelect||0!==group.DefaultQuantities||0!==group.MinQuantity)||(visualgroup.Items[0].Checked=!0);_recipes[recipeId].Groups.push(group)})})}),$.each(_.filter(recipe.Ingredients,function(i){return i.SubRecipeId&&i.SubRecipe})||[],function(i,s){Vendd.RecipeLibrary.InitRecipe(s.SubRecipe,s.RecipeItemId,force)}),_recipes[recipeId].HashCode=getRecipeItemsHashCode(recipeId),null!==localStorage.getItem("globalId_"+recipeId)&&localStorage.removeItem("globalId_"+recipeId),Vendd.RecipeLibrary.DeclareState(recipe,recipeId)):returnResponse(recipeId,500,1001)},Vendd.RecipeLibrary.ResetRecipe=function(model,recipeId){if(!_recipes[recipeId])return returnResponse(recipeId,500,1e3);var recipe=getRecipe(model,recipeId);return recipe?(delete _recipes[recipeId],_recipes[recipeId]=recipe,null!==localStorage.getItem("globalId_"+recipeId)&&localStorage.removeItem("globalId_"+recipeId),Vendd.RecipeLibrary.DeclareState(model,recipeId)):returnResponse(recipeId,500,1001)},Vendd.RecipeLibrary.AddIngredient=function(model,recipeId,ingredientId,quantity,isTotal){var recipe=_recipes[recipeId];if(!_recipes[recipeId])return returnResponse(recipeId,500,1e3);if(!recipe)return returnResponse(recipeId,500,1001);var group=null,ingredient=_.find(model.Ingredients,function(i){return i.IngredientId===ingredientId});if(ingredient&&(group=_.find(model.Groups,function(g){return g.Id===ingredient.GroupId})),!ingredient||!group)return returnResponse(recipeId,500,1003);var isCompatible=Vendd.RecipeLibrary.CheckIncompatibles(recipeId,ingredientId).success,responsePrerequisites=Vendd.RecipeLibrary.CheckPrerequisites(recipeId,ingredientId),successPrerequisites=responsePrerequisites.success||!responsePrerequisites.success&&responsePrerequisites.data.BothPrerequisite,recipeIngredient=_.first(_.filter(model.RecipeItems,function(x){return x.IngredientId===ingredientId&&x.RecipeId===recipeId}));if(!isCompatible||!successPrerequisites)return returnResponse(recipeId,500,isCompatible||successPrerequisites?isCompatible?1031:1030:1032);if(!Vendd.RecipeLibrary.CheckPrerequisitesAnyOfSet(recipeId,ingredientId).success)return returnResponse(recipeId,500,1033);var totalIngredientQuantity=isTotal?quantity:((recipeIngredient||{}).Quantity||0)+quantity;if(totalIngredientQuantity=totalIngredientQuantity>0?totalIngredientQuantity:0,ingredient.MinQuantity&&totalIngredientQuantity<ingredient.MinQuantity)return returnResponse(recipeId,500,1010);if(ingredient.MaxQuantity&&totalIngredientQuantity>ingredient.MaxQuantity)return returnResponse(recipeId,500,1011);if((group.MaxQuantity||0)<getGroupQuantity(model,group,ingredientId)+totalIngredientQuantity)return returnResponse(recipeId,500,1021);if((recipe.MaxQuantity||0)<getTotalQuantity(model,ingredientId)+totalIngredientQuantity)return returnResponse(recipeId,500,1041);var price=Math.round(100*ingredient.Price)/100,priceWithoutVat=Math.round(100*ingredient.PriceWithoutVat)/100;if(model.ParentRecipeId>0){var parentModel=Vendd.RecipeLibrary.GetModel(model.ParentRecipeItemId)||{},parentIngredient=_.find(parentModel.Ingredients,function(i){return i.VariantId===ingredient.VariantId})||{};if((parentIngredient.IngredientId||0)>0)if(!Vendd.RecipeLibrary.AddIngredient(parentModel,model.ParentRecipeItemId,parentIngredient.IngredientId,ingredient.Quantity,!0).success)return returnResponse(recipeId,500,1034)}return recipeIngredient?(recipeIngredient.Quantity=totalIngredientQuantity,recipeIngredient.Price=price,recipeIngredient.PriceWithoutVat=priceWithoutVat):model.RecipeItems.push({RecipeId:recipeId,Category:ingredient.Category,CategoryCode:ingredient.CategoryCode,ManufacturerProductCode:ingredient.ManufacturerProductCode,GroupId:group.Id,IngredientId:ingredient.IngredientId,ProductItemCode:ingredient.RecipeItemCode,ProductItemId:ingredient.RecipeItemId,VariantId:ingredient.VariantId,Name:ingredient.Name||"",Quantity:quantity,Price:price,PriceWithoutVat:priceWithoutVat,TotalPrice:Math.max(totalIngredientQuantity-ingredient.DefaultQuantity,0)*price,TotalPriceWithoutVat:Math.max(totalIngredientQuantity-ingredient.DefaultQuantity,0)*priceWithoutVat,Weight:ingredient.Weight,IsStandard:ingredient.DefaultQuantity>0,SubRecipeId:ingredient.SubRecipeId,SubRecipeCode:ingredient.SubRecipeCode}),model.HashCode=getRecipeItemsHashCode(recipeId),Vendd.RecipeLibrary.DeclareState(model,recipeId)},Vendd.RecipeLibrary.RemoveIngredient=function(model,recipeId,ingredientId,quantity,recursive,force){force=void 0===force||force;var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1001);var group=null,ingredient=_.find(model.Ingredients,function(i){return i.IngredientId===ingredientId});if(ingredient&&(group=_.find(model.Groups,function(g){return g.Id===ingredient.GroupId})),!ingredient||!group)return returnResponse(recipeId,500,1003);var recipeIngredient=_.first(_.filter(model.RecipeItems,function(x){return x.IngredientId===ingredientId&&x.RecipeId===recipeId})),totalIngredientQuantity=recursive?0:((recipeIngredient||{}).Quantity||0)-quantity;if(totalIngredientQuantity=totalIngredientQuantity>0?totalIngredientQuantity:0,ingredient.MinQuantity&&totalIngredientQuantity<ingredient.MinQuantity)return returnResponse(recipeId,500,1010);if((group.MinQuantity||0)>getGroupQuantity(model,group,ingredientId)+totalIngredientQuantity&&!force)return returnResponse(recipeId,500,1020);if((recipe.MinQuantity||0)>getTotalQuantity(model,ingredientId)+totalIngredientQuantity&&!force)return returnResponse(recipeId,500,1040);recipeIngredient&&totalIngredientQuantity>0?(recipeIngredient.Quantity=totalIngredientQuantity,recipeIngredient.Price=price):model.RecipeItems=_.filter(model.RecipeItems,function(x){return x.IngredientId!==ingredientId});for(var ingredientsToBeRemoved=_.filter(model.Ingredients,function(i){return i.Prerequisites&&i.Prerequisites.indexOf(ingredientId)>-1&&model.RecipeItems.some(function(item){return item.IngredientId===i.IngredientId})}),i=0;i<ingredientsToBeRemoved.length;i++)Vendd.RecipeLibrary.RemoveIngredient(model,recipeId,ingredientsToBeRemoved[i].IngredientId,null,!0,!0);return model.HashCode=getRecipeItemsHashCode(recipeId),Vendd.RecipeLibrary.DeclareState(model,recipeId)},Vendd.RecipeLibrary.ChangeIngredient=function(model,recipeId,ingredientIdFrom,ingredientIdTo){if(!_recipes[recipeId])return returnResponse(recipeId,500,1001);var groupFrom=null,ingredientFrom=_.find(model.Ingredients,function(i){return i.IngredientId===ingredientIdFrom});if(ingredientFrom&&(groupFrom=_.find(model.Groups,function(g){return g.Id===ingredientFrom.GroupId})),!ingredientFrom||!groupFrom)return returnResponse(recipeId,500,1003);if(!_.first(_.filter(model.RecipeItems,function(x){return x.IngredientId===ingredientIdFrom&&x.RecipeId===recipeId})))return returnResponse(recipeId,500,1002);model.RecipeItems=_.filter(model.RecipeItems,function(x){return x.IngredientId!==ingredientIdFrom});for(var ingredientsToBeRemoved=_.filter(model.Ingredients,function(i){return i.Prerequisites&&i.Prerequisites.indexOf(ingredientIdFrom)>-1&&model.RecipeItems.some(function(item){return item.IngredientId===i.IngredientId})}),i=0;i<ingredientsToBeRemoved.length;i++)Vendd.RecipeLibrary.RemoveIngredient(model,recipeId,ingredientsToBeRemoved[i].IngredientId,null,!0,!0);var result=Vendd.RecipeLibrary.AddIngredient(model,recipeId,ingredientIdTo,1,!0);return model.HashCode=getRecipeItemsHashCode(recipeId),result.success?result:Vendd.RecipeLibrary.DeclareState(model,recipeId)},Vendd.RecipeLibrary.GetFullRecipeItems=function(recipeId){var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1e3);var recipeItems=recipe.RecipeItems||[];_.each(_.filter(recipe.Ingredients,function(item){return item.SubRecipeId&&void 0!==_.find(recipeItems,function(i){return i.IngredientId===item.IngredientId})}),function(item){item.IsStandard||_.each(_recipes[item.RecipeItemId].RecipeItems,function(ingredient){ingredient.IsStandard=!1}),recipeItems=recipeItems.concat(_recipes[item.RecipeItemId].RecipeItems)});var data={};return data.RecipeItems=recipeItems||[],returnResponse(recipeId,200,0,data)},Vendd.RecipeLibrary.GetRecipeItems=function(recipeId){var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1e3);var data={};return data.RecipeItems=recipe.RecipeItems||[],returnResponse(recipeId,200,0,data)},Vendd.RecipeLibrary.GetOneDealerData=function(recipeId){var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1e3);var data={};data.ManufacturerName=recipe.ManufacturerName||"",data.ProductCode=recipe.ManufacturerProductCode||"",data.ManufacturerCode=recipe.ManufacturerCode||"",data.Series=recipe.CategoryCode||"",data.Name=recipe.Name||"",data.Guid=localStorage.getItem("globalId_"+recipeId),data.Prices={},data.Prices.OptionalTotalPrice=FixJSFloatBug(recipe.Prices.OptionalTotalPriceWithoutVat),data.Prices.StandardTotalPrice=FixJSFloatBug(recipe.Prices.StandardTotalPriceWithoutVat),data.Prices.InitialPrice=FixJSFloatBug(recipe.Prices.InitialPriceWithoutVat),data.Prices.TotalPrice=FixJSFloatBug(recipe.Prices.TotalPriceWithoutVat),data.ModelImageAbsoluteUrl=recipe.ProductImageUrl;var cartTypeCode=_.find(recipe.Attributes,function(i){return"CarTypeCode"===i.Code})||{};data.CarTypeCode=cartTypeCode.Value||"Car";var fuelTypeCode=_.find(recipe.Attributes,function(i){return"FuelTypeCode"===i.Code})||{};data.FuelTypeCode=fuelTypeCode.Value||"";var attributes=_.filter(recipe.Attributes,function(i){return"CarTypeCode"!==i.Code&&"FuelTypeCode"!==i.Code})||[];data.Attributes=_.map(attributes,function(i){var item={};return item.AttributeCode=i.Code,item.Value=i.Value,item.Type=i.ValueType,item});var recipeItems=recipe.RecipeItems||[];return _.each(_.filter(recipe.Ingredients,function(item){return item.SubRecipeId&&void 0!==_.find(recipeItems,function(i){return i.IngredientId===item.IngredientId})}),function(item){item.IsStandard||_.each(_recipes[item.RecipeItemId].RecipeItems,function(ingredient){ingredient.IsStandard=!1,ingredient.SubRecipeCode=item.ManufacturerProductCode}),recipeItems=recipeItems.concat(_recipes[item.RecipeItemId].RecipeItems)}),data.RecipeItems=_.map(recipeItems||[],function(i){var item={};return item.CategoryCode=i.CategoryCode||"",item.Name=i.Name,item.Quantity=i.Quantity,item.Price=i.PriceWithoutVat,item.ItemCode=i.ManufacturerProductCode||"",item.IsPackage=(i.SubRecipeId||0)>0,item.ParentPackageCode=i.SubRecipeCode||"",item.OptionType=i.IsStandard?0:1,item}),returnResponse(recipeId,200,0,data)},Vendd.RecipeLibrary.SetRecipeItems=function(recipeId,recipeItems){var recipe=_recipes[recipeId];return recipe?(recipe.RecipeItems=recipeItems||[],Vendd.RecipeLibrary.DeclareState(recipe,recipeId)):returnResponse(recipeId,500,1e3)},Vendd.RecipeLibrary.GetCheckedRecipeItems=function(recipeId,forceOptional){var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1e3);forceOptional=void 0!==forceOptional&&forceOptional;var checkedRecipeItems=[],optionalTotalPrice=0,optionalTotalItems=0,standardTotalPrice=0,standardTotalItems=0,optionalTotalPriceWithoutVat=0,standardTotalPriceWithoutVat=0;$.each(recipe.Ingredients,function(indexInArray,ingredient){var item=_.find(recipe.RecipeItems,function(i){return i.IngredientId===ingredient.IngredientId&&i.Quantity>0}),groupQuantity=getGroupQuantity(recipe,{Id:ingredient.GroupId},ingredient.IngredientId),isChecked=item;if(!(_.find(recipe.Groups,function(group){return ingredient.GroupId===group.Id})||{}).IsMultiSelect){var selectedItems=_.filter(recipe.RecipeItems,function(i){return i.GroupId===ingredient.GroupId})||[];selectedItems.length>1&&(isChecked=isChecked&&selectedItems[0].IngredientId===ingredient.IngredientId)}var isStandard=!forceOptional&&(!ingredient.IsNullable&&ingredient.DefaultQuantity>0);if(isChecked){var price=Math.round(100*ingredient.Price)/100,totalPrice=ingredient.DefaultQuantity>0?((item.Quantity||0)-(ingredient.DefaultQuantity||0))*price:(item.Quantity||0)*price,priceWithoutVat=Math.round(100*ingredient.PriceWithoutVat)/100,totalPriceWithoutVat=ingredient.DefaultQuantity>0?((item.Quantity||0)-(ingredient.DefaultQuantity||0))*priceWithoutVat:(item.Quantity||0)*priceWithoutVat;checkedRecipeItems.push({RecipeItemId:recipeId,ImageUrl:ingredient.ImageUrl,Category:ingredient.Category,GroupId:ingredient.GroupId,IngredientId:ingredient.IngredientId,ProductItemId:ingredient.RecipeItemId,VariantId:ingredient.VariantId,Name:ingredient.Name||"",Quantity:item.Quantity,Price:price,PriceWithoutVat:priceWithoutVat,TotalPriceWithoutVat:totalPriceWithoutVat,Weight:ingredient.Weight,IsStandard:isStandard}),isStandard?(standardTotalPrice+=totalPrice,standardTotalPriceWithoutVat+=totalPriceWithoutVat,standardTotalItems++):(optionalTotalPrice+=totalPrice,optionalTotalPriceWithoutVat+=totalPriceWithoutVat,optionalTotalItems++)}if(ingredient.IsNullable&&0===groupQuantity&&checkedRecipeItems.push({RecipeItemId:recipeId,ImageUrl:ingredient.ImageUrl,Category:ingredient.Category,GroupId:ingredient.GroupId,IngredientId:ingredient.IngredientId,ProductItemId:ingredient.RecipeItemId,VariantId:ingredient.VariantId,Name:ingredient.Name||"",Quantity:1,Price:0,PriceWithoutVat:0,TotalPrice:0,TotalPriceWithoutVat:0,Weight:0,IsStandard:isStandard}),item&&(item.Quantity||0)>0&&ingredient.SubRecipe){var subCheckedRecipeItems=Vendd.RecipeLibrary.GetCheckedRecipeItems(ingredient.RecipeItemId,!isStandard)||{};subCheckedRecipeItems.success&&(item.TotalPrice=subCheckedRecipeItems.data.Prices.TotalPrice,item.TotalPriceWithoutVat=subCheckedRecipeItems.data.Prices.TotalPriceWithoutVat,checkedRecipeItems=(checkedRecipeItems||[]).concat(subCheckedRecipeItems.data.CheckedRecipeItems||[]))}});var uncheckedRecipeItems=_.reject(recipe.Ingredients,function(item){return _.find(checkedRecipeItems,function(checked){return item.IngredientId===checked.IngredientId})}),data={};return data.CheckedItemsOptionalTotal=optionalTotalItems,data.CheckedItemsStandardTotal=standardTotalItems,data.CheckedRecipeItems=checkedRecipeItems,data.UncheckedRecipeItems=uncheckedRecipeItems,data.Prices={},data.Prices.OptionalTotalPrice=optionalTotalPrice,data.Prices.OptionalTotalPriceWithoutVat=optionalTotalPriceWithoutVat,data.Prices.StandardTotalPrice=standardTotalPrice,data.Prices.StandardTotalPriceWithoutVat=standardTotalPriceWithoutVat,data.Prices.InitialPrice=recipe.UnitPrice,data.Prices.InitialPriceWithoutVat=recipe.UnitPriceWithoutVat,data.Prices.TotalPrice=optionalTotalPrice+standardTotalPrice+recipe.UnitPrice,data.Prices.TotalPriceWithoutVat=optionalTotalPriceWithoutVat+standardTotalPriceWithoutVat+recipe.UnitPriceWithoutVat,recipe.Prices=data.Prices,returnResponse(recipeId,200,0,data)},Vendd.RecipeLibrary.GetPrices=function(recipeId){var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1e3);var prices={OptionalTotalPrice:0,StandardTotalPrice:0,OptionalTotalPriceWithoutVat:0,StandardTotalPriceWithoutVat:0};return _.each(recipe.RecipeItems,function(ri){var ingredient=_.find(recipe.Ingredients,function(i){return i.IngredientId===ri.IngredientId})||{},defaultQuantity=ingredient.DefaultQuantity||0,initialPrice=Math.round(100*(ingredient.Price||0))/100,initialPriceWithoutVat=Math.round(100*(ingredient.PriceWithoutVat||0))/100,optionalQuantity=Math.max(ri.Quantity-defaultQuantity),optionalTotalPrice=initialPrice*optionalQuantity,optionalTotalPriceWithoutVat=initialPriceWithoutVat*optionalQuantity,standardTotalPrice=0,standardTotalPriceWithoutVat=0;if(ingredient.SubRecipe&&ri.Quantity>0){var subPrices=Vendd.RecipeLibrary.GetPrices(ingredient.RecipeItemId)||{};optionalTotalPrice+=subPrices.OptionalTotalPrice||0,optionalTotalPriceWithoutVat+=subPrices.OptionalTotalPriceWithoutVat||0,standardTotalPrice+=subPrices.StandardTotalPrice||0,standardTotalPriceWithoutVat+=subPrices.StandardTotalPriceWithoutVat||0}prices.OptionalTotalPrice+=optionalTotalPrice,prices.StandardTotalPrice+=standardTotalPrice,prices.OptionalTotalPriceWithoutVat+=optionalTotalPriceWithoutVat,prices.StandardTotalPriceWithoutVat+=standardTotalPriceWithoutVat}),prices.InitialPrice=recipe.UnitPrice,prices.InitialPriceWithoutVat=recipe.UnitPriceWithoutVat,prices.TotalPrice=prices.OptionalTotalPrice+prices.StandardTotalPrice+prices.InitialPrice,prices.TotalPriceWithoutVat=prices.OptionalTotalPriceWithoutVat+prices.StandardTotalPriceWithoutVat+prices.InitialPriceWithoutVat,recipe.Prices=prices,prices},Vendd.RecipeLibrary.GetWeight=function(recipeId){var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1e3);var model,ingredientId,items,weightObj={};return weightObj.InitialWeight=recipe.Weight||0,weightObj.OptionalTotalWeight=(model=recipe,ingredientId=recipeId,items=_.filter(model.RecipeItems,function(item){return item.IngredientId!==ingredientId}),_.reduce(items,function(memo,item){return memo+(item.Weight||0)},0)),weightObj},Vendd.RecipeLibrary.GetEnabledItems=function(recipeId){var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1e3);var data={EnabledItems:[],DisableItems:[],GroupErrors:[],Errors:[]},totalQuantity=getTotalQuantity(recipe),extraQuantity=0,errorCode=0;return totalQuantity<recipe.MinQuantity?(errorCode=1042,extraQuantity=recipe.MinQuantity-totalQuantity):totalQuantity>recipe.MaxQuantity&&(errorCode=1043,extraQuantity=totalQuantity-recipe.MaxQuantity),errorCode>0&&data.Errors.push({RecipeId:recipeId,ErrorCode:errorCode,ExtraQuantity:extraQuantity,MinQuantity:recipe.MinQuantity,MaxQuantity:recipe.MaxQuantity,Quantity:totalQuantity}),$.each(recipe.Categories,function(indexCategory,category){$.each(category.Groups,function(indexGroup,group){var groupQuantity=getGroupQuantity(recipe,group),disableAllGroup=_.filter(recipe.Ingredients,function(i){return i.GroupId===group.Id&&!i.CanRemove&&!group.IsMultiSelect}).length>0;$.each(group.VisualGroups,function(indexVisualGroup,visualGroup){$.each(visualGroup.Items,function(indexItem,ingredient){var quantity=(_.first(_.filter(recipe.RecipeItems,function(x){return x.IngredientId===ingredient.IngredientId&&x.RecipeId===recipeId}))||{}).Quantity||0,isDisabled=!ingredient.CanRemove||ingredient.MaxQuantity<=quantity&&ingredient.MinQuantity>quantity||group.MaxQuantity<=groupQuantity&&0===quantity||recipe.MaxQuantity<=totalQuantity&&0===quantity,canAdd=ingredient.MaxQuantity>quantity&&group.MaxQuantity>groupQuantity,canRemove=ingredient.MinQuantity<quantity&&ingredient.CanRemove,isChecked=quantity>0,checkIncompatibles=Vendd.RecipeLibrary.CheckIncompatibles(recipeId,ingredient.IngredientId),isEnabledIncompatible=checkIncompatibles.success||!checkIncompatibles.success&&checkIncompatibles.data.BothSelected,checkPrerequisites=Vendd.RecipeLibrary.CheckPrerequisites(recipeId,ingredient.IngredientId),isEnabledPrerequisites=checkPrerequisites.success||!checkPrerequisites.success&&checkPrerequisites.data.BothPrerequisite,checkPrerequisitesAnyOfSet=Vendd.RecipeLibrary.CheckPrerequisitesAnyOfSet(recipeId,ingredient.IngredientId),errorCode=0;if(disableAllGroup||(group.IsMultiSelect&&isDisabled||!isEnabledIncompatible||!isEnabledPrerequisites||!checkPrerequisitesAnyOfSet.success)&&!ingredient.IsNullable){isDisabled&&ingredient.DefaultQuantity>0&&ingredient.MinQuantity===ingredient.DefaultQuantity?errorCode=1012:group.MaxQuantity<=groupQuantity&&group.IsMultiSelect&&!isChecked?errorCode=1021:disableAllGroup?errorCode=1021:recipe.MaxQuantity<=totalQuantity&&group.IsMultiSelect&&!isChecked?errorCode=1041:ingredient.MinQuantity>quantity&&group.IsMultiSelect&&isChecked?errorCode=1010:ingredient.MaxQuantity<=quantity&&group.IsMultiSelect&&!isChecked?errorCode=1011:checkIncompatibles.success?checkPrerequisites.success?checkPrerequisitesAnyOfSet.success||(errorCode=1033):errorCode=1031:errorCode=1030,errorCode>0&&data.DisableItems.push({RecipeId:recipeId,GroupId:group.Id,IngredientId:ingredient.IngredientId,ProductItemId:ingredient.RecipeItemId,VariantId:ingredient.VariantId,ErrorCode:errorCode,CanAdd:canAdd,canRemove:canRemove,Incompatibles:checkIncompatibles.data.Incompatibles,MissingPrerequisites:checkPrerequisites.data.MissingPrerequisites,MissingAnyOfPrerequisites:checkPrerequisitesAnyOfSet.data.MissingAnyOfPrerequisites})}else isDisabled&&ingredient.DefaultQuantity>0&&ingredient.MinQuantity===ingredient.DefaultQuantity?errorCode=1012:checkIncompatibles.success?checkPrerequisites.success?checkPrerequisitesAnyOfSet.success||(errorCode=checkPrerequisitesAnyOfSet.status.ErrorCode):errorCode=checkPrerequisites.status.ErrorCode:errorCode=checkIncompatibles.status.ErrorCode,data.EnabledItems.push({RecipeId:recipeId,GroupId:group.Id,IngredientId:ingredient.IngredientId,ProductItemId:ingredient.RecipeItemId,VariantId:ingredient.VariantId,ErrorCode:errorCode,CanAdd:canAdd,canRemove:canRemove,Incompatibles:checkIncompatibles.data.Incompatibles,MissingPrerequisites:checkPrerequisites.data.MissingPrerequisites,MissingAnyOfPrerequisites:checkPrerequisitesAnyOfSet.data.MissingAnyOfPrerequisites})})});var groupErrorCode=0,extraQuantity=0;groupQuantity<group.MinQuantity?(groupErrorCode=1022,extraQuantity=group.MinQuantity-groupQuantity):groupQuantity>group.MaxQuantity&&(groupErrorCode=1023,extraQuantity=groupQuantity-group.MaxQuantity),groupErrorCode>0&&data.GroupErrors.push({Id:group.Id,RecipeId:recipeId,ErrorCode:groupErrorCode,ExtraQuantity:extraQuantity,MinQuantity:group.MinQuantity,MaxQuantity:group.MaxQuantity,Quantity:groupQuantity,Name:group.Name,CategoryName:category.Category})})}),returnResponse(recipeId,200,0,data)},Vendd.RecipeLibrary.CheckIncompatibles=function(recipeId,ingredientId){var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1e3);var ingredient=_.find(recipe.Ingredients,function(i){return i.IngredientId===ingredientId}),recipeIngredient=_.first(_.filter(recipe.RecipeItems,function(x){return x.IngredientId===ingredient.IngredientId}))||{};if(!ingredient)return returnResponse(recipeId,500,1002);var data={},incompatibles=_.filter(ingredient.Incompatibles,function(i){return recipe.RecipeItems.some(function(item){return item.IngredientId===i})})||[];return incompatibles.length>0?(data.Incompatibles=_.filter(recipe.Ingredients,function(item){return incompatibles.some(function(i){return item.IngredientId===i})}),data.BothSelected=(recipeIngredient.Quantity||0)>0,returnResponse(recipeId,500,1030,data)):returnResponse(recipeId,200)},Vendd.RecipeLibrary.CheckPrerequisites=function(recipeId,ingredientId){var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1e3);var ingredient=_.find(recipe.Ingredients,function(i){return i.IngredientId===ingredientId});if(!ingredient)return returnResponse(recipeId,500,1002);var data={},missingPrerequisites=_.filter(ingredient.Prerequisites,function(i){return!recipe.RecipeItems.some(function(item){return item.IngredientId===i})})||[];if(missingPrerequisites.length>0){data.MissingPrerequisites=_.filter(recipe.Ingredients,function(item){return missingPrerequisites.some(function(i){return item.IngredientId===i})});var bothPrerequisite=_.filter(data.MissingPrerequisites,function(i){return i.Prerequisites.length>0&&i.Prerequisites.some(function(item){return item===ingredient.IngredientId})})||[];return data.BothPrerequisite=bothPrerequisite.length>0,returnResponse(recipeId,500,1031,data)}return returnResponse(recipeId,200)},Vendd.RecipeLibrary.CheckPrerequisitesAnyOfSet=function(recipeId,ingredientId){var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1e3);var ingredient=_.find(recipe.Ingredients,function(i){return i.IngredientId===ingredientId});if(!ingredient)return returnResponse(recipeId,500,1002);for(var data={MissingAnyOfPrerequisites:[]},hasMissingAnyOfPrerequisites=!1,i=0;i<(ingredient.RequiresAnyOfSet||[]).length;i++){var requiredSetItems=ingredient.RequiresAnyOfSet[i].RequiresAnyOfItems||[];if(0===(_.filter(requiredSetItems,function(i){return recipe.RecipeItems.some(function(item){return item.IngredientId===i})})||[]).length&&requiredSetItems.length>0){hasMissingAnyOfPrerequisites=!0;var missingAnyOfPrerequisites=_.filter(recipe.Ingredients,function(item){return requiredSetItems.some(function(i){return item.IngredientId===i})});data.MissingAnyOfPrerequisites.push(missingAnyOfPrerequisites)}}return hasMissingAnyOfPrerequisites?returnResponse(recipeId,500,1033,data):returnResponse(recipeId,200)},Vendd.RecipeLibrary.IsValid=function(recipeId){var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1e3);var data={Errors:[],GroupErrors:[],IngredientsErrors:[]},totalQuantity=getTotalQuantity(recipe,recipeId),extraQuantity=0,errorCode=0;return totalQuantity<recipe.MinQuantity?(errorCode=1042,extraQuantity=recipe.MinQuantity-totalQuantity):totalQuantity>recipe.MaxQuantity&&(errorCode=1043,extraQuantity=totalQuantity-recipe.MaxQuantity),errorCode>0&&data.Errors.push({ParentProductId:recipeId,ErrorCode:errorCode,ExtraQuantity:extraQuantity,MinQuantity:recipe.MinQuantity,MaxQuantity:recipe.MaxQuantity,Quantity:totalQuantity}),$.each(recipe.Categories,function(indexCategory,category){$.each(category.Groups,function(indexGroup,group){var groupErrorCode=0,extraQuantity=0,groupQuantity=getGroupQuantity(recipe,group);groupQuantity<group.MinQuantity?(groupErrorCode=1022,extraQuantity=group.MinQuantity-groupQuantity):groupQuantity>group.MaxQuantity&&(groupErrorCode=1023,extraQuantity=groupQuantity-group.MaxQuantity),groupErrorCode>0&&data.GroupErrors.push({Id:group.Id,RecipeId:recipeId,ErrorCode:groupErrorCode,ExtraQuantity:extraQuantity,MinQuantity:group.MinQuantity,MaxQuantity:group.MaxQuantity,Quantity:groupQuantity,Name:group.Name,CategoryName:category.Category}),$.each(group.VisualGroups,function(indexVisualGroup,visualGroup){$.each(visualGroup.Items,function(indexItem,ingredient){var quantity=(_.first(_.filter(recipe.RecipeItems,function(x){return x.IngredientId===ingredient.IngredientId}))||_.find(recipe.RecipeItems,function(i){return ingredient.RecipeItemId===i.RecipeItemId})||{}).Quantity||0,checkIncompatibles=Vendd.RecipeLibrary.CheckIncompatibles(recipeId,ingredient.IngredientId),checkPrerequisites=Vendd.RecipeLibrary.CheckPrerequisites(recipeId,ingredient.IngredientId),checkPrerequisitesAnyOfSet=Vendd.RecipeLibrary.CheckPrerequisitesAnyOfSet(recipeId,ingredient.IngredientId),errorCodes=[];ingredient.MinQuantity>quantity?errorCodes.push(1010):ingredient.MaxQuantity<quantity?errorCodes.push(1011):!checkIncompatibles.success&&quantity>0?errorCodes.push(1030):!checkPrerequisites.success&&quantity>0?errorCodes.push(1031):!checkPrerequisitesAnyOfSet.success&&quantity>0&&errorCodes.push(1033),errorCodes.length>0&&data.IngredientsErrors.push({RecipeId:recipeId,GroupId:group.Id,IngredientId:ingredient.IngredientId,ErrorCodes:errorCodes,Incompatibles:checkIncompatibles.data.Incompatibles||[],MissingPrerequisites:checkPrerequisites.data.MissingPrerequisites||[],MissingAnyOfPrerequisites:checkPrerequisitesAnyOfSet.data.MissingAnyOfPrerequisites||[],Name:ingredient.Name||"",Price:ingredient.Price,PriceWithoutVat:ingredient.PriceWithoutVat,PriceText:ingredient.PriceText,PriceWithoutVatText:ingredient.PriceWithoutVatText,TotalPrice:ingredient.TotalPrice,TotalPriceWithoutVat:ingredient.TotalPriceWithoutVat})})})})}),data.IsValid=0===data.Errors.length&&0===data.GroupErrors.length&&0===data.IngredientsErrors.length,data},Vendd.RecipeLibrary.CompareModels=function(recipeId,savedModel){var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1e3);var ingedientsSavedModel=_.sortBy(savedModel.Ingredients,function(i){return i.IngredientId}),ingedientsSavedModelHashCode=_.map(ingedientsSavedModel,function(i){return"{0}_{1}_{2}_{3}_{4}".replace("{0}",i.IngredientId||"").replace("{1}",i.GroupId||"").replace("{2}",i.Price||"").replace("{3}",(i.Incompatibles||[]).join(",")).replace("{4}",(i.Prerequisites||[]).join(","))}).join("|"),ingedientsModel=_.sortBy(recipe.Ingredients,function(i){return i.IngredientId}),ingedientsModelHashCode=_.map(ingedientsModel,function(i){return"{0}_{1}_{2}_{3}_{4}".replace("{0}",i.IngredientId||"").replace("{1}",i.GroupId||"").replace("{2}",i.Price||"").replace("{3}",(i.Incompatibles||[]).join(",")).replace("{4}",(i.Prerequisites||[]).join(","))}).join("|"),groupsSavedModel=_.sortBy(savedModel.Groups,function(i){return i.Id}),savedGroupsModelHashCode=_.map(groupsSavedModel,function(i){return"{0}_{1}".replace("{0}",i.MinQuantity||0).replace("{1}",i.MaxQuantity||0)}).join("|"),groupsModel=_.sortBy(recipe.Groups,function(i){return i.Id}),groupsModelHashCode=_.map(groupsModel,function(i){return"{0}_{1}".replace("{0}",i.MinQuantity||0).replace("{1}",i.MaxQuantity||0)}).join("|"),savedModelHashCode="{0}_{1}_{2}_{3}".replace("{0}",savedModel.MinQuantity||0).replace("{1}",savedModel.MaxQuantity||0).replace("{2}",savedModel.MaxFreeQuantity||0).replace("{3}",savedModel.MaxReplaceQuantity||0),modelHashCode="{0}_{1}_{2}_{3}".replace("{0}",recipe.MinQuantity||0).replace("{1}",recipe.MaxQuantity||0).replace("{2}",recipe.MaxFreeQuantity||0).replace("{3}",recipe.MaxReplaceQuantity||0);if(ingedientsSavedModelHashCode===ingedientsModelHashCode&&groupsModelHashCode===savedGroupsModelHashCode&&savedModelHashCode===modelHashCode)return returnResponse(recipeId,200);var recipeItems=[],IngredientsErrors=[],IngredientsWarnings=[],data={};_.each(savedModel.RecipeItems,function(r){var ingredient=_.find(recipe.Ingredients,function(i){return r.IngredientId===i.IngredientId})||_.find(recipe.Ingredients,function(i){return r.RecipeItemId===i.RecipeItemId}),savedIngredient=_.find(savedModel.Ingredients,function(i){return r.IngredientId===i.IngredientId})||_.find(savedModel.Ingredients,function(i){return r.RecipeItemId===i.RecipeItemId});null!==ingredient?(ingredient.Price!==savedIngredient.Price&&IngredientsWarnings.push({IngredientId:savedIngredient.IngredientId,Name:savedIngredient.Name,Price:savedIngredient.Price,Incompatibles:savedIngredient.Incompatibles,Prerequisites:savedIngredient.Prerequisites,ErrorCodes:[1073]}),recipeItems.push({RecipeId:recipeId,Category:ingredient.Category,CategoryCode:ingredient.CategoryCode,GroupId:ingredient.GroupId,IngredientId:ingredient.IngredientId,ProductItemCode:ingredient.RecipeItemCode,ProductItemId:ingredient.RecipeItemId,VariantId:ingredient.VariantId,Name:ingredient.Name||"",Quantity:savedIngredient.Quantity||1,Price:savedIngredient.Price,TotalPrice:Math.max((savedIngredient.Quantity||1)-ingredient.DefaultQuantity,0)*savedIngredient.Price,Weight:ingredient.Weight,IsStandard:ingredient.DefaultQuantity>0,SubRecipeId:ingredient.SubRecipeId,SubRecipeCode:ingredient.SubRecipeCode})):IngredientsErrors.push({IngredientId:savedIngredient.IngredientId,Name:savedIngredient.Name,Price:savedIngredient.Price,Incompatibles:savedIngredient.Incompatibles,Prerequisites:savedIngredient.Prerequisites,ErrorCodes:[1072]})});$.extend({},recipe);recipe.RecipeItems=_.reject(recipeItems,function(r){return IngredientsErrors.some(function(i){return i.IngredientId===r.IngredientId})});var validatedModel=Vendd.RecipeLibrary.IsValid(recipeId);return data.IngredientsErrors=validatedModel.IngredientsErrors.concat(IngredientsErrors),data.IngredientsWarnings=IngredientsWarnings,!(data=$.extend({},validatedModel,data||{})).IsValid||data.IngredientsErrors.length>0||data.GroupErrors.length>0||data.Errors.length>0?returnResponse(recipeId,500,1004,data):returnResponse(recipeId,200)},Vendd.RecipeLibrary.GenerateGlobalId=function(config){var _def=$.Deferred(),data={},defaultConfiguration={Force:!1,FriendlyName:"",Vin:"",PartnerId:"",serviceurl:"/services/api/Product/SaveRecipeConfiguration",onSuccess:function(response){response.success&&response.data&&response.data.GlobalId?(data.GlobalId=response.data.GlobalId,data.SavedGlobalIdToLocal=Vendd.RecipeLibrary.SaveGlobalIdToLocal(config.RecipeId,data.GlobalId).success,data.SaveRecipeItemsToLocal=Vendd.RecipeLibrary.SaveRecipeItemsToLocal(config.RecipeId,data.GlobalId).success,data.HashCode=getRecipeItemsHashCode(config.RecipeId,recipe.RecipeItems),_recipes[config.RecipeId].HashCode=data.HashCode,_def.resolve(returnResponse(config.RecipeId,200,0,data))):config.onError(response)},onError:function(response){_def.reject(returnResponse(config.RecipeId,500,1060,response))}};if((config=$.extend({},defaultConfiguration,config||{})).RecipeId){var recipe=_recipes[config.RecipeId];if(recipe){var currentHashCode=getRecipeItemsHashCode(config.RecipeId),savedHashCode=Vendd.RecipeLibrary.GetLocalStorageRecipeItemsHashCode(config.RecipeId);if(config.HtmlData.Body="",config.Force||null===localStorage.getItem("globalId_"+config.RecipeId)||currentHashCode!==savedHashCode){var jsonData=(Vendd.RecipeLibrary.ConvertToSavedModel(config.RecipeId)||{}).data||{},requestData=JSON.stringify({FriendlyName:config.FriendlyName,ConfigurationJson:JSON.stringify(jsonData),ProductItemId:config.RecipeId,ProductIdentifier:config.Vin,PartnerId:""!==config.PartnerId?config.PartnerId:null,Url:window.location.href,HtmlData:config.HtmlData,IsShare:!config.Force});$.ajax({type:"POST",dataType:"json",contentType:"application/json; charset=UTF-8",url:config.serviceurl,async:!0,data:requestData,error:config.onError,success:config.onSuccess})}else data.GlobalId=localStorage.getItem("globalId_"+config.RecipeId),data.HashCode=currentHashCode,_recipes[config.RecipeId].HashCode=currentHashCode,_def.resolve(returnResponse(config.RecipeId,200,0,data));return _def.promise()}_def.resolve(returnResponse(config.RecipeId,500,1e3))}else _def.resolve(returnResponse(null,500,1061))},Vendd.RecipeLibrary.AssignConfigurationToUser=function(config){var _def=$.Deferred(),data={},defaultConfiguration={serviceurl:"/services/api/Product/SaveRecipeConfiguration",onSuccess:function(response){response.success?_def.resolve(returnResponse(config.RecipeId,200,0,data)):config.onError(response)},onError:function(response){_def.reject(returnResponse(config.RecipeId,500,1060,response))}};config=$.extend({},defaultConfiguration,config||{});var requestData=JSON.stringify({GlobalId:config.GlobalId||"",FriendlyName:"Update User",ConfigurationJson:JSON.stringify({}),ProductItemId:config.RecipeItemId,Url:window.location.href});return $.ajax({type:"POST",dataType:"json",contentType:"application/json; charset=UTF-8",url:config.serviceurl,async:!0,data:requestData,error:config.onError,success:config.onSuccess}),_def.promise()},Vendd.RecipeLibrary.LoadFromGlobalId=function(config){var _def=$.Deferred(),data={},defaultConfiguration={serviceurl:"/services/api/Product/GetRecipeConfiguration",onSuccess:function(response){if(response.success&&response.data&&response.data.GlobalId){(data=JSON.parse(response.data.ConfigurationJson||"{}")).GlobalId=response.data.GlobalId,data.HtmlData=JSON.parse(response.data.Html||"{}"),data.Pdf=response.data.Pdf||"",data.IsValid=!0,data.Errors=[],data.GroupErrors=[],data.IngredientsErrors=[],data.IngredientsWarnings=[],recipe.RecipeItems=data.RecipeItems;var compareResult=Vendd.RecipeLibrary.CompareModels(config.RecipeId,data),subrecipeCompareResults=_.map(data.SubRecipes||[],function(subrecipeData){return Vendd.RecipeLibrary.SetRecipeItems(subrecipeData.RecipeItemId,subrecipeData.RecipeItems),Vendd.RecipeLibrary.CompareModels(subrecipeData.RecipeItemId,subrecipeData)});if(!compareResult.success||subrecipeCompareResults.some(function(r){return!r.success}))return recipe.IsValid=!1,recipe.IngredientsErrors=compareResult.data.IngredientsErrors,recipe.IngredientsWarnings=compareResult.data.IngredientsWarnings,recipe.Errors=compareResult.data.Errors,recipe.GroupErrors=compareResult.data.GroupErrors,void _def.resolve(returnResponse(config.RecipeId,200,1070,recipe));recipe.GlobalId=data.GlobalId,recipe.Pdf=data.Pdf,recipe.IsValid=data.IsValid,recipe.Errors=data.Errors,recipe.IngredientsErrors=data.IngredientsErrors,recipe.IngredientsWarnings=data.IngredientsWarnings,_def.resolve(returnResponse(config.RecipeId,200,0,recipe))}else config.onError(data)},onError:function(data){_def.reject(returnResponse(config.RecipeId,500,1070,data))}};config=$.extend({},defaultConfiguration,config||{});var recipe=_recipes[config.RecipeId];if(recipe){if(0!==(config.GlobalId||0)){var requestData=JSON.stringify({GlobalId:config.GlobalId});return $.ajax({type:"POST",dataType:"json",contentType:"application/json; charset=UTF-8",url:config.serviceurl,async:!0,data:requestData,error:config.onError,success:config.onSuccess}),_def.promise()}_def.resolve(returnResponse(config.RecipeId,500,1071))}else _def.resolve(returnResponse(config.RecipeId,500,1e3))},Vendd.RecipeLibrary.SaveGlobalIdToLocal=function(recipeId,globalId){return _recipes[recipeId]?(localStorage.setItem("globalId_"+recipeId,globalId),returnResponse(recipeId,200,0)):returnResponse(recipeId,500,1e3)},Vendd.RecipeLibrary.SaveRecipeItemsToLocal=function(recipeId){var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1e3);var recipeItems=Vendd.RecipeLibrary.GetFullRecipeItems(recipeId).RecipeItems,currentHashCode=getRecipeItemsHashCode(recipeId,recipeItems);if(currentHashCode===Vendd.RecipeLibrary.GetLocalStorageRecipeItemsHashCode(recipeId))return returnResponse(recipeId,200);var dataLocalStorage={RecipeItems:recipe.RecipeItems,HashCode:currentHashCode};return localStorage.setItem("configurator_"+recipeId,JSON.stringify(dataLocalStorage,null,2)),returnResponse(recipeId,200)},Vendd.RecipeLibrary.LoadFromLocalRecipeItems=function(recipeId){var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1e3);if(null===localStorage.getItem("configurator_"+recipeId))return returnResponse(recipeId,500,1050);var dataLocalStorage=JSON.parse(localStorage.getItem("configurator_"+recipeId)||"{}");recipe.RecipeItems=dataLocalStorage.RecipeItems,recipe.HashCode=dataLocalStorage.HashCode;var data={};return data.Recipe=recipe,data.GlobalId="",returnResponse(recipeId,200,0,data)};var getRecipeItemsHashCode=function(recipeId,items){if(!_recipes[recipeId])return null;var recipeItems=items||((Vendd.RecipeLibrary.GetFullRecipeItems(recipeId)||{}).data||{}).RecipeItems;return recipeId+(recipeItems.length>0?"_"+(_.map(_.sortBy(recipeItems,"IngredientId"),function(i){return i.IngredientId+"_"+i.Quantity})||[]).join("_"):"")};Vendd.RecipeLibrary.GetLocalStorageRecipeItemsHashCode=function(recipeId){return _recipes[recipeId]?null===localStorage.getItem("configurator_"+recipeId)?null:JSON.parse(localStorage.getItem("configurator_"+recipeId)||"{}").HashCode:null},Vendd.RecipeLibrary.ClearLocalStorage=function(recipeId){return!!_recipes[recipeId]&&(null!==localStorage.getItem("configurator_"+recipeId)&&localStorage.removeItem("configurator_"+recipeId),null!==localStorage.getItem("globalId_"+recipeId)&&localStorage.removeItem("globalId_"+recipeId),!0)},Vendd.RecipeLibrary.ConvertToSavedModel=function(recipeId){var recipe=_recipes[recipeId];if(!recipe)return returnResponse(recipeId,500,1e3);var data={};return(data=converModelToSaveDataModel(recipe)||{}).Groups=converGroupsToSaveDataModel(recipe.Groups)||[],data.Ingredients=converIngedientToSaveDataModel(recipe.Ingredients)||[],data.RecipeItems=Vendd.RecipeLibrary.GetRecipeItems(recipeId).data.RecipeItems||[],data.SubRecipes=_.map(_.filter(recipe.RecipeItems,function(r){return r.SubRecipeId>0&&_recipes[r.ProductItemId]})||[],function(ri){return(Vendd.RecipeLibrary.ConvertToSavedModel(ri.ProductItemId)||{}).data||{}})||[],returnResponse(recipeId,200,0,data)};var converModelToSaveDataModel=function(m){return{RecipeId:m.RecipeId,RecipeItemId:m.RecipeItemId,MinQuantity:m.MinQuantity,MaxQuantity:m.MaxQuantity,MaxFreeQuantity:m.MaxFreeQuantity,MaxReplaceQuantity:m.MaxReplaceQuantity,UnitPrice:m.UnitPrice}},converGroupsToSaveDataModel=function(groups){return _.map(groups,function(g){return{Id:g.Id,MinQuantity:g.MinQuantity,MaxQuantity:g.MaxQuantity}})},converIngedientToSaveDataModel=function(ingredients){return _.map(ingredients,function(i){return{IngredientId:i.IngredientId,Name:i.Name,GroupId:i.GroupId,Price:i.Price,Incompatibles:i.Incompatibles||[],Prerequisites:i.Prerequisites||[]}})};function FixJSFloatBug(price){return parseFloat((price||0).toFixed(2))}return Vendd.RecipeLibrary.Tests={0:function(){return console.log(Vendd.RecipeLibrary.InitRecipe(null,2)),console.log(Vendd.RecipeLibrary.AddIngredient(null,2,88694,2)),console.log(Vendd.RecipeLibrary.AddIngredient(null,2,88691,1)),console.log(Vendd.RecipeLibrary.AddIngredient(null,2,88691,2)),console.log(Vendd.RecipeLibrary.AddIngredient(null,2,88691,2,!0)),console.log(Vendd.RecipeLibrary.RemoveIngredient(null,2,88694)),console.log(Vendd.RecipeLibrary.DeclareState(null,2)),"success"},1:function(){return console.log(Vendd.RecipeLibrary.InitRecipe(null,1)),console.log(Vendd.RecipeLibrary.AddIngredient(null,1,88691,2)),console.log(Vendd.RecipeLibrary.AddIngredient(null,1,88694,1)),console.log(Vendd.RecipeLibrary.AddIngredient(null,1,88694,2)),console.log(Vendd.RecipeLibrary.AddIngredient(null,1,88694,2,!0)),console.log(Vendd.RecipeLibrary.RemoveIngredient(null,1,88691)),console.log(Vendd.RecipeLibrary.DeclareState(null,1)),"success"},2:function(){return console.log(Vendd.RecipeLibrary.InitRecipe(null,1)),console.log(Vendd.RecipeLibrary.AddIngredient(null,1,88694,1)),console.log(Vendd.RecipeLibrary.AddIngredient(null,1,88691,2)),console.log(Vendd.RecipeLibrary.AddIngredient(null,1,88694,2)),console.log(Vendd.RecipeLibrary.AddIngredient(null,1,88694,2,!0)),console.log(Vendd.RecipeLibrary.RemoveIngredient(null,1,88691)),console.log(Vendd.RecipeLibrary.DeclareState(null,1)),"success"}},Vendd}((Vendd=function(Vendd){"use strict";var Service;return Vendd.Service=((Service=Vendd.Service||{}).call=function(options){var defOpts,opts,serviceUrl,onErrorInternal;defOpts={async:!0,method:options.method||"POST",url:"#",data:{},rawdata:!1,servicenamespace:options.servicenamespace||"services",onSuccess:function(response){},onFailure:function(err){throw err},onUnauthenticated:function(url){throw new Error("not implemented: onUnauthenticated(url)")}},opts=_.extend(defOpts,options),serviceUrl=(serviceUrl=/^([^:]+:)?\/\//.test(opts.url)?opts.url:document.location.protocol.toLowerCase()+"//"+document.location.host.toLowerCase()+(opts.servicenamespace?"/"+opts.servicenamespace:"")+"/"+opts.url).split("?")[0];var locationQueryParams=LhApp.Function.QueryString.parse(window.location.href),serviceQueryParams=LhApp.Function.QueryString.parse(opts.url);serviceQueryParams.lang||(serviceQueryParams.lang=(locationQueryParams.lang||LhApp.Context.Language).toLowerCase()),!serviceQueryParams.country&&locationQueryParams.country&&(serviceQueryParams.country=locationQueryParams.country.toLowerCase()),!serviceQueryParams.currency&&locationQueryParams.currency&&(serviceQueryParams.currency=locationQueryParams.currency.toLowerCase());var _query,_data={};"GET"==(options.method||"POST").toUpperCase()?(_.each(opts.data,function(val,key){_data[key.toLowerCase()]=val}),_data=_.extend(serviceQueryParams,opts.data)):(_data=opts.data,_query=$.param(serviceQueryParams).toString()),_query&&(serviceUrl+="?"+_query),onErrorInternal=function(ex){if(ex&&ex.responseJSON&&ex.responseJSON.ExceptionType)if("AuthenticationServiceException"===ex.responseJSON.ExceptionType.split(".").pop()){if("function"!=typeof opts.onUnauthenticated)throw ex;opts.onUnauthenticated(ex.responseJSON.Message)}else{if("function"!=typeof opts.onFailure)throw ex;opts.onFailure(ex)}else{if("function"!=typeof opts.onFailure)throw ex;opts.onFailure(ex)}},$.ajax({async:opts.async||!0,type:opts.method,dataType:opts.rawdata?"text":"json",contentType:opts.rawdata?"":"application/json; charset=UTF-8",ContentType:opts.rawdata?"":"application/json; charset=UTF-8",url:serviceUrl,data:"GET"==opts.method?_data:opts.rawdata?_data:JSON.stringify(_data),success:function(response){var obj=response;response.d&&(obj=response.d),("string"==typeof obj||obj instanceof String)&&(obj=JSON.parse(obj)),"function"==typeof opts.onSuccess&&opts.onSuccess(obj)},failure:function(ex){onErrorInternal(ex)},error:function(ex){onErrorInternal(ex)}})},Service),Vendd}(Vendd||{}))||{}),testModel={},recaptchaLoaded=!1,recaptchaMessagePublished=!1,callback_recaptcha=function(){recaptchaLoaded=!0,checkAsyncLoad()},googleMapsLoaded=!1,googleMapsMessagePublished=!1,callback_googlemaps=function(){googleMapsLoaded=!0,checkAsyncLoad()},venddLoaded=!1,callback_vendd=function(){venddLoaded=!0,checkAsyncLoad()},checkAsyncLoad=function(){venddLoaded&&(recaptchaLoaded&&!recaptchaMessagePublished&&(Vendd.MessageBus.publishAsync("checkAsyncLoad",new Vendd.Plugins.Messages.RecaptcaLoaded),recaptchaMessagePublished=!0),googleMapsLoaded&&!googleMapsMessagePublished&&(Vendd.MessageBus.publishAsync("checkAsyncLoad",new Vendd.Plugins.Messages.GoogleMapsLoaded),googleMapsMessagePublished=!0))};function checkout_callback_googlemaps(){angular.element(".x-checkoutstore").ready(function(){$(".x-checkoutstore").scope()&&$(".x-checkoutstore").scope().Control&&"function"==typeof $(".x-checkoutstore").scope().Control.SetMap&&$(".x-checkoutstore").scope().Control.SetMap(!0)})}$(document).ready(function(){Vendd&&Vendd.Scripts&&"function"==typeof Vendd.Scripts.init&&(Vendd.Scripts.init(),LhApp&&LhApp.init&&"function"==typeof LhApp.init&&LhApp.init())});
//# sourceMappingURL=vendd.global.min.js.map
