// DANE DO WALIDACJI NUMERU TELEFONU const countryPhoneData = [ { alpha2: "AT", alpha3: "AUT", country_code: "43", country_name: "Austria", mobile_begin_with: ["6"], phone_number_lengths: [10, 11, 12, 13, 14], }, { alpha2: "BE", alpha3: "BEL", country_code: "32", country_name: "Belgium", mobile_begin_with: ["4", "3"], phone_number_lengths: [9, 8], }, { alpha2: "BG", alpha3: "BGR", country_code: "359", country_name: "Bulgaria", mobile_begin_with: ["87", "88", "89", "98", "99", "43"], phone_number_lengths: [8, 9], }, { alpha2: "BY", alpha3: "BLR", country_code: "375", country_name: "Belarus", mobile_begin_with: ["25", "29", "33", "44"], phone_number_lengths: [9], }, { alpha2: "CH", alpha3: "CHE", country_code: "41", country_name: "Switzerland", mobile_begin_with: ["74", "75", "76", "77", "78", "79"], phone_number_lengths: [9], }, { alpha2: "CY", alpha3: "CYP", country_code: "357", country_name: "Cyprus", mobile_begin_with: ["9"], phone_number_lengths: [8], }, { alpha2: "CZ", alpha3: "CZE", country_code: "420", country_name: "Czech Republic", mobile_begin_with: ["6", "7"], phone_number_lengths: [9], }, { alpha2: "DE", alpha3: "DEU", country_code: "49", country_name: "Germany", mobile_begin_with: ["15", "16", "17"], phone_number_lengths: [10, 11], }, { alpha2: "DK", alpha3: "DNK", country_code: "45", country_name: "Denmark", mobile_begin_with: [ "2", "30", "31", "40", "41", "42", "50", "51", "52", "53", "60", "61", "71", "81", "91", "92", "93", "342", "344", "345", "346", "347", "348", "349", "356", "357", "359", "362", "365", "366", "389", "398", "431", "441", "462", "466", "468", "472", "474", "476", "478", "485", "486", "488", "489", "493", "494", "495", "496", "498", "499", "542", "543", "545", "551", "552", "556", "571", "572", "573", "574", "577", "579", "584", "586", "587", "589", "597", "598", "627", "629", "641", "649", "658", "662", "663", "664", "665", "667", "692", "693", "694", "697", "771", "772", "782", "783", "785", "786", "788", "789", "826", "827", "829", ], phone_number_lengths: [8], }, { alpha2: "ES", alpha3: "ESP", country_code: "34", country_name: "Spain", mobile_begin_with: ["6", "7"], phone_number_lengths: [9], }, { alpha2: "EE", alpha3: "EST", country_code: "372", country_name: "Estonia", mobile_begin_with: ["5", "81", "82", "83"], phone_number_lengths: [7, 8], }, { alpha2: "FI", alpha3: "FIN", country_code: "358", country_name: "Finland", mobile_begin_with: ["4", "5"], phone_number_lengths: [9, 10], }, { alpha2: "FR", alpha3: "FRA", country_code: "33", country_name: "France", mobile_begin_with: ["6", "7"], phone_number_lengths: [9], }, { alpha2: "GB", alpha3: "GBR", country_code: "44", country_name: "United Kingdom", mobile_begin_with: ["7"], phone_number_lengths: [10], }, { alpha2: "GE", alpha3: "GEO", country_code: "995", country_name: "Georgia", mobile_begin_with: ["5", "7"], phone_number_lengths: [9], }, { alpha2: "GI", alpha3: "GIB", country_code: "350", country_name: "Gibraltar", mobile_begin_with: ["5"], phone_number_lengths: [8], }, { alpha2: "GR", alpha3: "GRC", country_code: "30", country_name: "Greece", mobile_begin_with: ["6"], phone_number_lengths: [10], }, { alpha2: "HR", alpha3: "HRV", country_code: "385", country_name: "Croatia", mobile_begin_with: ["9"], phone_number_lengths: [8, 9], }, { alpha2: "IE", alpha3: "IRL", country_code: "353", country_name: "Ireland", mobile_begin_with: ["82", "83", "84", "85", "86", "87", "88", "89"], phone_number_lengths: [9], }, { alpha2: "IS", alpha3: "ISL", country_code: "354", country_name: "Iceland", mobile_begin_with: ["6", "7", "8"], phone_number_lengths: [7], }, { alpha2: "IT", alpha3: "ITA", country_code: "39", country_name: "Italy", mobile_begin_with: ["3"], phone_number_lengths: [9, 10], }, { alpha2: "LI", alpha3: "LIE", country_code: "423", country_name: "Liechtenstein", mobile_begin_with: ["7"], phone_number_lengths: [7], }, { alpha2: "LT", alpha3: "LTU", country_code: "370", country_name: "Lithuania", mobile_begin_with: ["6"], phone_number_lengths: [8], }, { alpha2: "LU", alpha3: "LUX", country_code: "352", country_name: "Luxembourg", mobile_begin_with: ["6"], phone_number_lengths: [9], }, { alpha2: "LV", alpha3: "LVA", country_code: "371", country_name: "Latvia", mobile_begin_with: ["2"], phone_number_lengths: [8], }, { alpha2: "MC", alpha3: "MCO", country_code: "377", country_name: "Monaco", mobile_begin_with: ["4", "6"], phone_number_lengths: [8, 9], }, { alpha2: "MD", alpha3: "MDA", country_code: "373", country_name: "Moldova, Republic of", mobile_begin_with: ["6", "7"], phone_number_lengths: [8], }, { alpha2: "MK", alpha3: "MKD", country_code: "389", country_name: "Macedonia, the Former Yugoslav Republic Of", mobile_begin_with: ["7"], phone_number_lengths: [8], }, { alpha2: "ME", alpha3: "MNE", country_code: "382", country_name: "Montenegro", mobile_begin_with: ["6"], phone_number_lengths: [8], }, { alpha2: "NL", alpha3: "NLD", country_code: "31", country_name: "Netherlands", mobile_begin_with: ["6"], phone_number_lengths: [9], }, { alpha2: "NO", alpha3: "NOR", country_code: "47", country_name: "Norway", mobile_begin_with: ["4", "9"], phone_number_lengths: [8], }, { alpha2: "PL", alpha3: "POL", country_code: "48", country_name: "Poland", mobile_begin_with: ["4", "5", "6", "7", "8"], phone_number_lengths: [9], }, { alpha2: "PT", alpha3: "PRT", country_code: "351", country_name: "Portugal", mobile_begin_with: ["9"], phone_number_lengths: [9], }, { alpha2: "RO", alpha3: "ROU", country_code: "40", country_name: "Romania", mobile_begin_with: ["7"], phone_number_lengths: [9], }, { alpha2: "RU", alpha3: "RUS", country_code: "7", country_name: "Russian Federation", mobile_begin_with: ["9", "495", "498", "499", "835"], phone_number_lengths: [10], }, { alpha2: "RS", alpha3: "SRB", country_code: "381", country_name: "Serbia", mobile_begin_with: ["6"], phone_number_lengths: [8, 9], }, { alpha2: "SK", alpha3: "SVK", country_code: "421", country_name: "Slovakia", mobile_begin_with: ["9"], phone_number_lengths: [9], }, { alpha2: "SI", alpha3: "SVN", country_code: "386", country_name: "Slovenia", mobile_begin_with: ["3", "4", "5", "6", "7"], phone_number_lengths: [8], }, { alpha2: "SE", alpha3: "SWE", country_code: "46", country_name: "Sweden", mobile_begin_with: ["7"], phone_number_lengths: [9], }, { alpha2: "TR", alpha3: "TUR", country_code: "90", country_name: "Turkey", mobile_begin_with: ["5"], phone_number_lengths: [10], }, { alpha2: "UA", alpha3: "UKR", country_code: "380", country_name: "Ukraine", mobile_begin_with: ["39", "50", "63", "66", "67", "68", "73", "9"], phone_number_lengths: [9], }, ]; // LEAFLET MAP var stocks_list_more_txt=;var stocks_list_choose=;var pickupl_nopoints=;var mapTooltipLink_class="btn-small";var autocompleteData=[];var ajaxGetPickupNoMap=function(){$(".mapContainer_pickup, .pickupl_submit").show();var options={courierId:pickup_sites.courierId,isCod:pickup_sites.isCod};$.ajax({type:"GET",url:"/ajax/getPickups.php",data:options,dataType:"json",success:function(json){if(!json.pickupPoints.length){Alertek.show_alert(pickupl_nopoints);$(".loadingMap").hide();return false}setPickupPointsNoMap(json)},error:function(){orderdetails_payments.ajaxLoadSite(0);$(".no_google_api_key div.asideContainer_pickup").show();Alertek.show_alert(pickupl_error)}})};var setPickupPointsNoMap=function(json){var pickup_clone_tmp=$("#pickup_copy").clone();var pickups="";for(i in json.pickupPoints){var pickup=json.pickupPoints[i];var pickup_street=pickup.address.buildingAndHouseNumber!=""?pickup.address.street+" "+pickup.address.buildingAndHouseNumber:pickup.address.street;pickup_clone=pickup_clone_tmp.clone();pickup_clone.find("input[name=pickup_point], input[name=stock]").attr("id","pickup_point_"+pickup.id).val(pickup.id);pickup_clone.find("label").attr({id:"pp_"+pickup.id,"data-latitude":pickup.coordinates.latitude,"data-longitude":pickup.coordinates.longitude,"data-id":pickup.id,"data-requires_client_number":pickup.requiresClientNumber,for:"pickup_point_"+pickup.id});if(pickup.coordinates.longitude){pickup_clone.find("label .map_dir").attr("href","https://www.google.com/maps/dir/?api=1&destination="+pickup.coordinates.latitude+","+pickup.coordinates.longitude)}else{pickup_clone.find("label .map_dir").attr("href","https://maps.google.com?saddr=Current+Location&daddr="+pickup.address.street+"+"+pickup.address.postcode+"+"+pickup.address.city)}pickup_clone.find("b.headerText").text(pickup.name);pickup_clone.find("span.streetText").text(pickup_street);pickup_clone.find("span.zipcodePickup").html(pickup.address.postcode+' '+pickup.address.city+"");pickup_clone.find("div.moreText").text(pickup.location);pickup_clone.find("a.moreLink").attr("href",pickup.link);if(!pickup.requiresClientNumber){pickup_clone.find("input[name=client_courier_number]").remove()}pickups+=pickup_clone.html();autocompleteData.push({label:pickup.address.city+", "+pickup.address.street+" "+pickup.address.buildingAndHouseNumber+" "+pickup.address.postcode+" "+pickup.id,value:pickup.address.city+", "+pickup.address.street+" "+pickup.address.buildingAndHouseNumber+", "+pickup.id,description:pickup.location,id:pickup.id})}$("#pickup_site .asideContainer_pickup").html(pickups);var accentMap={"ł":"l","ó":"o","ź":"z","ś":"s",",":""," ":" "};var normalize=function(term){var ret="";var term=term.toLowerCase();for(var i=0;i'+pickupl_select_adress+"");$(".loadingMap").hide();return false}else{$(".mapContainer_pickup, .asideContainer_pickup, .pickupl_submit, #pickup_map").show()}pickup_sites.search_lat=place.geometry.location.lat();pickup_sites.search_lng=place.geometry.location.lng();for(var i=0;i'+pickupl_select_adress+"");$(".loadingMap").hide();return false}else{$(".mapContainer_pickup, .asideContainer_pickup, .pickupl_submit, #pickup_map").show()}$("label.pickup_point").hide();$("div.loadingMap").fadeIn("normal",function(){});$("span.loadingMarkers").hide();var options={courierId:pickup_sites.courierId,"location[latitude]":pickup_sites.search_lat,"location[longitude]":pickup_sites.search_lng,isCod:pickup_sites.isCod};if(radius){function getRadius(){var curr_zoom=pickup_sites.mapa.getZoom();if(curr_zoom>=15){return 1}else if(curr_zoom==14){return 2}else if(curr_zoom==13){return 4}else if(curr_zoom==12){return 7}else if(curr_zoom==11){return 10}else if(curr_zoom==10){return 15}else{return 20}}var options={courierId:pickup_sites.courierId,"location[latitude]":pickup_sites.search_lat,"location[longitude]":pickup_sites.search_lng,radius:getRadius(),isCod:pickup_sites.isCod}}$.ajax({type:"GET",url:"/ajax/getPickups.php",data:options,dataType:"json",success:function(json){if(!jQuery.isEmptyObject(selected_pickup_point)){for(i in json.pickupPoints){if(json.pickupPoints[i].id==selected_pickup_point.id){delete json.pickupPoints[i]}}json.pickupPoints.unshift(selected_pickup_point)}if(!json.pickupPoints.length){if(radius){$("div.asideContainer_pickup").prepend('")}else{$("div.asideContainer_pickup").prepend('")}$(".loadingMap").hide();return false}if(!pickup_sites.adress.route){for(i in json.pickupPoints){if($.trim(json.pickupPoints[i].address.city).toLowerCase()==$.trim(pickup_sites.adress.locality).toLowerCase()){options.radius=30;$.ajax({type:"GET",url:"/ajax/getPickups.php",data:options,dataType:"json",success:function(json){setPickupPoints(json,true)},error:function(){}});return false}}}setPickupPoints(json,false)},error:function(){$("div.asideContainer_pickup").prepend('")}})},showSel:function(){pickup_sites.pickupCount=$(".asideContainer_pickup .pickup_point").length;pickup_sites.pickupIteration=0;$("div.loadingMap").fadeIn("normal",function(){});$("span.loadingMap").hide();$("span.loadingMarkers").css("display","block");$("span.loadingMarkersCount").text(pickup_sites.pickupCount);$("span.loadingMarkersComplete").text(pickup_sites.pickupIteration);pickup_sites.markersArray=[];var adresData=[];$(".asideContainer_pickup .pickup_point").each(function(index){$this=$(this);adresData[index]={};adresData[index].idek=$this.data("id");adresData[index].headerText=$.trim($this.find(".headerText").text());adresData[index].streetText=$this.find(".streetText").text();adresData[index].cityText=$.trim($this.find(".cityText").text());adresData[index].moreText=$.trim($this.find(".moreLink").text());adresData[index].moreLink=$.trim($this.find(".moreLink").attr("href"));adresData[index].infoText=$.trim($this.find(".infoText").text());adresData[index].timeText=$.trim($this.find(".timeText").text());adresData[index].latitude=$.trim($this.data("latitude"));adresData[index].longitude=$.trim($this.data("longitude"));adresData[index].icon=$.trim($this.data("icon"))});var adresRow="";while(adresRow=adresData.pop()){if(adresRow.latitude&&adresRow.longitude){pickup_sites.findAdres(adresRow.headerText,adresRow.streetText,adresRow.cityText,adresRow.moreText,adresRow.moreLink,adresRow.infoText,adresRow.timeText,"none","another",false,adresRow.idek,adresRow.latitude,adresRow.longitude,adresRow.icon)}else{(function(adresRow){setTimeout(function(){pickup_sites.findAdres(adresRow.headerText,adresRow.streetText,adresRow.cityText,adresRow.moreText,adresRow.moreLink,adresRow.infoText,adresRow.timeText,"none","another",false,adresRow.idek,adresRow.latitude,adresRow.longitude,adresRow.icon)},pickup_sites.timeout)})(adresRow)}}},printDates:function(stockId){if(!$("#selectPickupDay").size())return false;var postData={stock_id:stockId};$.ajax({type:"GET",url:"/ajax/basket-delivery.php",data:postData,dataType:"json",success:function(json){if(!json){$("#selectPickupDayWrapper").hide();return false}$("#selectPickupDay").html("");$.each(json,function(index,data){$("#selectPickupDay").append('")});$("#selectPickupDayWrapper").show();$(".pickupl_hour_wrapper").show();$('#selectPickupDay [name="calendar_select_date"]').eq(1).prop("checked",true)},error:function(){Alertek.show_alert(pickupl_error)}})},setZoom:function(){var bounds=new google.maps.LatLngBounds;for(var i in pickup_sites.markersArray){bounds.extend(pickup_sites.markersArray[i].getPosition())}pickup_sites.mapa.setCenter(bounds.getCenter());pickup_sites.mapa.fitBounds(bounds);pickup_sites.mapa.setZoom(pickup_sites.mapa.getZoom());if(pickup_sites.mapa.getZoom()>15){pickup_sites.mapa.setZoom(15)}},mapInit:function(){if($("#mymap").length){return false}if($("#autocomplete_location").size()&&!$("#mymap").size()){pickup_sites.autocomplete=new google.maps.places.Autocomplete(document.getElementById("autocomplete_location"));$("label.pickup_point").hide()}pickup_sites.zoom=pickupsZoom;pickup_sites.geokoder=new google.maps.Geocoder;var wspolrzedne=new google.maps.LatLng(parseInt(bCordPickups),parseInt(lCordPickups));if(markersAnimationPickups!="")pickup_sites.markerAnimation=true;else pickup_sites.markerAnimation=false;if(markerPickupsCustomIcon!="")markerPickupsCustomIcon=true;else markerPickupsCustomIcon=false;if(mapTypePickups=="ROADMAP")var mapStyle=google.maps.MapTypeId.ROADMAP;else if(mapTypePickups=="SATELLITE")var mapStyle=google.maps.MapTypeId.SATELLITE;else if(mapTypePickups=="HYBRID")var mapStyle=google.maps.MapTypeId.HYBRID;else if(mapTypePickups=="TERRAIN")var mapStyle=google.maps.MapTypeId.TERRAIN;else var mapStyle=google.maps.MapTypeId.ROADMAP;if(navControlPickups!="")navControlPickups=true;else navControlPickups=false;if(mapTypeControlPickups!="")mapTypeControlPickups=true;else mapTypeControlPickups=false;if(scControlPickups!="")scControlPickups=true;else scControlPickups=false;if(controlTypePickups=="ZOOM_PAN")var controlStyle=google.maps.NavigationControlStyle.ZOOM_PAN;else if(controlTypePickups=="SMALL")var controlStyle=google.maps.NavigationControlStyle.SMALL;else if(controlTypePickups=="ANDROID")var controlStyle=google.maps.NavigationControlStyle.ANDROID;else var controlStyle=google.maps.NavigationControlStyle.ZOOM_PAN;if(mapTypeControlStylePickups=="DROPDOWN_MENU")var TypeControlStyle=google.maps.MapTypeControlStyle.DROPDOWN_MENU;else if(mapTypeControlStylePickups=="HORIZONTAL_BAR")var TypeControltyle=google.maps.MapTypeControlStyle.HORIZONTAL_BAR;else var TypeControlStyle=google.maps.MapTypeControlStyle.DROPDOWN_MENU;if($("img.marker_face").attr("src")!=""&&markerPickupsCustomIcon){var markerIconSize=new google.maps.Size($("img.marker_face").width(),$("img.marker_face").height());var punkt_startowy=new google.maps.Point(0,0);var punkt_zaczepienia=new google.maps.Point(parseInt($("img.marker_face").width()/2),parseInt($("img.marker_face").height()/2));pickup_sites.markerIcon=new google.maps.MarkerImage($("img.marker_face").attr("src"),markerIconSize,punkt_startowy,punkt_zaczepienia)}if(window["google_map_style_array"]){var mapOptions={gestureHandling:"cooperative",zoom:pickup_sites.zoom,center:wspolrzedne,mapTypeId:mapStyle,navigationControl:navControlPickups,mapTypeControl:mapTypeControlPickups,scaleControl:scControlPickups,styles:google_map_style_array,navigationControlOptions:{style:controlStyle},mapTypeControlOptions:{style:TypeControlStyle}}}else{var mapOptions={gestureHandling:"cooperative",zoom:pickup_sites.zoom,center:wspolrzedne,mapTypeId:mapStyle,navigationControl:navControlPickups,mapTypeControl:mapTypeControlPickups,scaleControl:scControlPickups,navigationControlOptions:{style:controlStyle},mapTypeControlOptions:{style:TypeControlStyle}}}if(pickup_sites.google_api_key===""){$(".pickupl_sel").removeAttr("disabled");$("div#ps_other").css("opacity","1.0");$("div#ps_other").css("cursor","pointer")}pickup_sites.mapa=new google.maps.Map(document.getElementById("pickup_map"),mapOptions);pickup_sites.markerInfo=new google.maps.InfoWindow;google.maps.event.addListener(pickup_sites.mapa,"idle",function(){$("span.loadingMap").text($("span.loadingNav").text())});if(pickup_sites.autocomplete){pickup_sites.autocomplete.addListener("place_changed",function(){var place=pickup_sites.autocomplete.getPlace();pickup_sites.fillInAddress(place,false);pickup_sites.getLocation()});pickup_sites.getLocation()}else{pickup_sites.showSel()}},markerClickFunction:function(latlng,content){return function(e){e.cancelBubble=true;e.returnValue=false;if(e.stopPropagation){e.stopPropagation();e.preventDefault()}pickup_sites.infoWindow.setContent(content);pickup_sites.infoWindow.setPosition(latlng);pickup_sites.infoWindow.open(pickup_sites.mapa)}},geokoderPrepare:function(point,status,headerText,streetText,cityText,moreText,moreLink,infoText,timeText,className,other,open,idek,latitude,longitude,icon){if(status==google.maps.GeocoderStatus.OK){pickup_sites.timeout=100;pickup_sites.pickupIteration++;pickup_sites.pickupFind++;var content='
'+headerText+"";content+='
'+streetText+"  "+cityText+"
";if(infoText){content+='
'+infoText+"
"}content+='
'+timeText+"
";if(moreLink){if(mapTooltipLink_class==="")content+='";else content+='"}content+="
";var opcjeMarkera={title:headerText,pickupPointID:idek};opcjeMarkera.position=point;opcjeMarkera.map=pickup_sites.mapa;if(pickup_sites.markerAnimation)opcjeMarkera.animation=google.maps.Animation.DROP;if(icon&&icon!=""){opcjeMarkera.icon=icon}else{if($("img.marker_face").attr("src")!=""&&markerPickupsCustomIcon){opcjeMarkera.icon=pickup_sites.markerIcon}}var marker=new google.maps.Marker(opcjeMarkera);pickup_sites.markersArray.push(marker);google.maps.event.addListener(marker,"click",function(marker,i){return function(e){e.cancelBubble=true;e.returnValue=false;if(e.stopPropagation){e.stopPropagation();e.preventDefault()}pickup_sites.markerInfo.setContent(content);pickup_sites.markerInfo.open(pickup_sites.mapa,marker);$('.asideContainer_pickup [value="'+marker.pickupPointID+'"]').prop("checked",true);$(".asideContainer_pickup").scrollTop(0);$(".asideContainer_pickup").scrollTop($('#pickup_site [name="pickup_point"]:checked + label').position().top)}}(marker,i));var pickupItem=$('.asideContainer_pickup [value="'+marker.pickupPointID+'"]').get(0);$('label[for="pickup_point_'+marker.pickupPointID+'"]').show().fadeTo("slow",1);google.maps.event.addDomListener(pickupItem,"click",function(marker,i){return function(e){$('.asideContainer_pickup [value="'+marker.pickupPointID+'"]').prop("checked",true);pickup_sites.markerInfo.setContent(content);pickup_sites.mapa.setCenter(opcjeMarkera.position);if(pickup_sites.mapa.getZoom()=pickup_sites.pickupCount){setTimeout(function(){$("div.loadingMap").fadeOut("normal",function(){});var _src=$('.markerCluster[src*="m1.png"]').attr("src");var _imagePath=_src.substring(0,_src.indexOf("1.png"));pickup_sites.setZoom();var create_map_selected_point=true;if(pickup_sites.mapa.zoom=pickup_sites.pickupCount){setTimeout(function(){$("div.loadingMap").fadeOut("normal",function(){});var _src=$('.markerCluster[src*="m1.png"]').attr("src");var _imagePath=_src.substring(0,_src.indexOf("1.png")-1);pickup_sites.setZoom();var create_map_selected_point=true;if(pickup_sites.mapa.zoom')}if(pickup.coordinates.longitude){pickup_clone.find("label .map_dir").attr("href","https://www.google.com/maps/dir/?api=1&destination="+pickup.coordinates.latitude+","+pickup.coordinates.longitude)}else{pickup_clone.find("label .map_dir").attr("href","https://maps.google.com?saddr=Current+Location&daddr="+pickup.address.street+"+"+pickup.address.postcode+"+"+pickup.address.city)}pickup_clone.find("b.headerText").text(pickup.name);var pickup_street=pickup.address.buildingAndHouseNumber!=""&&pickup.address.buildingAndHouseNumber!=null?pickup.address.street+" "+pickup.address.buildingAndHouseNumber:pickup.address.street;pickup_clone.find("span.streetText").text(pickup_street);pickup_clone.find("span.zipcodePickup").html(pickup.address.postcode+' '+pickup.address.city+"");pickup_clone.find("div.moreText").text(pickup.location);pickup_clone.find("a.moreLink").attr("href",pickup.link);if(pickup.requiresClientNumber){}else{pickup_clone.find("input[name=client_courier_number]").remove()}$("#pickup_site .asideContainer_pickup").append(pickup_clone.find(" > *"))}pickup_sites.showSel()};function geolocate(){pickup_sites.search_lat="";pickup_sites.search_lng="";if(navigator.geolocation){navigator.geolocation.getCurrentPosition(function(position){var geolocation={lat:position.coords.latitude,lng:position.coords.longitude};var circle=new google.maps.Circle({center:geolocation,radius:position.coords.accuracy});pickup_sites.autocomplete.setBounds(circle.getBounds())})}}$(document).on("click","#locationField .btn",function(){if(!$("#mymap").length){pickup_sites.getLocation()}else{leafletGetTextLocation();$(".leafleat-suggestions").remove()}return false});$(document).on("click","div.morePickup",function(){var activePoints=$("label.pickup_point.moreInfoShow");$(this).parents("label.pickup_point").addClass("moreInfoShow");activePoints.removeClass("moreInfoShow")});$(document).on("click",'#pickup_site [name="pickup_point"], #pickup_site [name="stock"]',function(){$('#pickup_site [name="client_courier_number"]').prop("disabled",true);$(this).find('+ label [name="client_courier_number"]').prop("disabled",false).focus();pickup_sites.printDates($(this).val())});app_shop.run(function(){pickup_sites.country_code=app_shop.vars.country_code;pickup_sites.language=app_shop.vars.language;pickup_sites.isCod=app_shop.vars.isCod;pickup_sites.courierId=app_shop.vars.courierId;init_pickupl_site();var mapLink="https://maps.googleapis.com/maps/api/js?key="+app_shop.vars.apiKey+"&libraries=places&callback=pickup_sites.mapInit";var pickup_src=document.createElement("script");pickup_src.setAttribute("src",mapLink);document.body.appendChild(pickup_src)},"all","#pickup_site");function MarkerClusterer(map,opt_markers,opt_options){this.extend(MarkerClusterer,google.maps.OverlayView);this.map_=map;this.markers_=[];this.clusters_=[];this.sizes=[53,56,66,78,90];this.styles_=[];this.ready_=false;var options=opt_options||{};this.gridSize_=options["gridSize"]||60;this.minClusterSize_=options["minimumClusterSize"]||2;this.maxZoom_=options["maxZoom"]||null;this.styles_=options["styles"]||[];this.imagePath_=options["imagePath"]||this.MARKER_CLUSTER_IMAGE_PATH_;this.imageExtension_=options["imageExtension"]||this.MARKER_CLUSTER_IMAGE_EXTENSION_;this.zoomOnClick_=true;if(options["zoomOnClick"]!=undefined){this.zoomOnClick_=options["zoomOnClick"]}this.averageCenter_=false;if(options["averageCenter"]!=undefined){this.averageCenter_=options["averageCenter"]}this.setupStyles_();this.setMap(map);this.prevZoom_=this.map_.getZoom();var that=this;google.maps.event.addListener(this.map_,"zoom_changed",function(){var zoom=that.map_.getZoom();var minZoom=that.map_.minZoom||0;var maxZoom=Math.min(that.map_.maxZoom||100,that.map_.mapTypes[that.map_.getMapTypeId()].maxZoom);zoom=Math.min(Math.max(zoom,minZoom),maxZoom);if(that.prevZoom_!=zoom){that.prevZoom_=zoom;that.resetViewport()}});google.maps.event.addListener(this.map_,"idle",function(){that.redraw()});if(opt_markers&&(opt_markers.length||Object.keys(opt_markers).length)){this.addMarkers(opt_markers,false)}}MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_PATH_="../images/m";MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_EXTENSION_="png";MarkerClusterer.prototype.extend=function(obj1,obj2){return function(object){for(var property in object.prototype){this.prototype[property]=object.prototype[property]}return this}.apply(obj1,[obj2])};MarkerClusterer.prototype.onAdd=function(){this.setReady_(true)};MarkerClusterer.prototype.draw=function(){};MarkerClusterer.prototype.setupStyles_=function(){if(this.styles_.length){return}for(var i=0,size;size=this.sizes[i];i++){this.styles_.push({url:this.imagePath_+(i+1)+"."+this.imageExtension_,height:size,width:size})}};MarkerClusterer.prototype.fitMapToMarkers=function(){var markers=this.getMarkers();var bounds=new google.maps.LatLngBounds;for(var i=0,marker;marker=markers[i];i++){bounds.extend(marker.getPosition())}this.map_.fitBounds(bounds)};MarkerClusterer.prototype.setStyles=function(styles){this.styles_=styles};MarkerClusterer.prototype.getStyles=function(){return this.styles_};MarkerClusterer.prototype.isZoomOnClick=function(){return this.zoomOnClick_};MarkerClusterer.prototype.isAverageCenter=function(){return this.averageCenter_};MarkerClusterer.prototype.getMarkers=function(){return this.markers_};MarkerClusterer.prototype.getTotalMarkers=function(){return this.markers_.length};MarkerClusterer.prototype.setMaxZoom=function(maxZoom){this.maxZoom_=maxZoom};MarkerClusterer.prototype.getMaxZoom=function(){return this.maxZoom_};MarkerClusterer.prototype.calculator_=function(markers,numStyles){var index=0;var count=markers.length;var dv=count;while(dv!==0){dv=parseInt(dv/10,10);index++}index=Math.min(index,numStyles);return{text:count,index:index}};MarkerClusterer.prototype.setCalculator=function(calculator){this.calculator_=calculator};MarkerClusterer.prototype.getCalculator=function(){return this.calculator_};MarkerClusterer.prototype.addMarkers=function(markers,opt_nodraw){if(markers.length){for(var i=0,marker;marker=markers[i];i++){this.pushMarkerTo_(marker)}}else if(Object.keys(markers).length){for(var marker in markers){this.pushMarkerTo_(markers[marker])}}if(!opt_nodraw){this.redraw()}};MarkerClusterer.prototype.pushMarkerTo_=function(marker){marker.isAdded=false;if(marker["draggable"]){var that=this;google.maps.event.addListener(marker,"dragend",function(){marker.isAdded=false;that.repaint()})}this.markers_.push(marker)};MarkerClusterer.prototype.addMarker=function(marker,opt_nodraw){this.pushMarkerTo_(marker);if(!opt_nodraw){this.redraw()}};MarkerClusterer.prototype.removeMarker_=function(marker){var index=-1;if(this.markers_.indexOf){index=this.markers_.indexOf(marker)}else{for(var i=0,m;m=this.markers_[i];i++){if(m==marker){index=i;break}}}if(index==-1){return false}marker.setMap(null);this.markers_.splice(index,1);return true};MarkerClusterer.prototype.removeMarker=function(marker,opt_nodraw){var removed=this.removeMarker_(marker);if(!opt_nodraw&&removed){this.resetViewport();this.redraw();return true}else{return false}};MarkerClusterer.prototype.removeMarkers=function(markers,opt_nodraw){var removed=false;for(var i=0,marker;marker=markers[i];i++){var r=this.removeMarker_(marker);removed=removed||r}if(!opt_nodraw&&removed){this.resetViewport();this.redraw();return true}};MarkerClusterer.prototype.setReady_=function(ready){if(!this.ready_){this.ready_=ready;this.createClusters_()}};MarkerClusterer.prototype.getTotalClusters=function(){return this.clusters_.length};MarkerClusterer.prototype.getMap=function(){return this.map_};MarkerClusterer.prototype.setMap=function(map){this.map_=map};MarkerClusterer.prototype.getGridSize=function(){return this.gridSize_};MarkerClusterer.prototype.setGridSize=function(size){this.gridSize_=size};MarkerClusterer.prototype.getMinClusterSize=function(){return this.minClusterSize_};MarkerClusterer.prototype.setMinClusterSize=function(size){this.minClusterSize_=size};MarkerClusterer.prototype.getExtendedBounds=function(bounds){var projection=this.getProjection();var tr=new google.maps.LatLng(bounds.getNorthEast().lat(),bounds.getNorthEast().lng());var bl=new google.maps.LatLng(bounds.getSouthWest().lat(),bounds.getSouthWest().lng());var trPix=projection.fromLatLngToDivPixel(tr);trPix.x+=this.gridSize_;trPix.y-=this.gridSize_;var blPix=projection.fromLatLngToDivPixel(bl);blPix.x-=this.gridSize_;blPix.y+=this.gridSize_;var ne=projection.fromDivPixelToLatLng(trPix);var sw=projection.fromDivPixelToLatLng(blPix);bounds.extend(ne);bounds.extend(sw);return bounds};MarkerClusterer.prototype.isMarkerInBounds_=function(marker,bounds){return bounds.contains(marker.getPosition())};MarkerClusterer.prototype.clearMarkers=function(){this.resetViewport(true);this.markers_=[]};MarkerClusterer.prototype.resetViewport=function(opt_hide){for(var i=0,cluster;cluster=this.clusters_[i];i++){cluster.remove()}for(var i=0,marker;marker=this.markers_[i];i++){marker.isAdded=false;if(opt_hide){marker.setMap(null)}}this.clusters_=[]};MarkerClusterer.prototype.repaint=function(){var oldClusters=this.clusters_.slice();this.clusters_.length=0;this.resetViewport();this.redraw();window.setTimeout(function(){for(var i=0,cluster;cluster=oldClusters[i];i++){cluster.remove()}},0)};MarkerClusterer.prototype.redraw=function(){this.createClusters_()};MarkerClusterer.prototype.distanceBetweenPoints_=function(p1,p2){if(!p1||!p2){return 0}var R=6371;var dLat=(p2.lat()-p1.lat())*Math.PI/180;var dLon=(p2.lng()-p1.lng())*Math.PI/180;var a=Math.sin(dLat/2)*Math.sin(dLat/2)+Math.cos(p1.lat()*Math.PI/180)*Math.cos(p2.lat()*Math.PI/180)*Math.sin(dLon/2)*Math.sin(dLon/2);var c=2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));var d=R*c;return d};MarkerClusterer.prototype.addToClosestCluster_=function(marker){var distance=4e4;var clusterToAddTo=null;var pos=marker.getPosition();for(var i=0,cluster;cluster=this.clusters_[i];i++){var center=cluster.getCenter();if(center){var d=this.distanceBetweenPoints_(center,marker.getPosition());if(d=this.minClusterSize_){marker.setMap(null)}this.updateIcon();return true};Cluster.prototype.getMarkerClusterer=function(){return this.markerClusterer_};Cluster.prototype.getBounds=function(){var bounds=new google.maps.LatLngBounds(this.center_,this.center_);var markers=this.getMarkers();for(var i=0,marker;marker=markers[i];i++){bounds.extend(marker.getPosition())}return bounds};Cluster.prototype.remove=function(){this.clusterIcon_.remove();this.markers_.length=0;delete this.markers_};Cluster.prototype.getSize=function(){return this.markers_.length};Cluster.prototype.getMarkers=function(){return this.markers_};Cluster.prototype.getCenter=function(){return this.center_};Cluster.prototype.calculateBounds_=function(){var bounds=new google.maps.LatLngBounds(this.center_,this.center_);this.bounds_=this.markerClusterer_.getExtendedBounds(bounds)};Cluster.prototype.isMarkerInClusterBounds=function(marker){return this.bounds_.contains(marker.getPosition())};Cluster.prototype.getMap=function(){return this.map_};Cluster.prototype.updateIcon=function(){var zoom=this.map_.getZoom();var mz=this.markerClusterer_.getMaxZoom();if(mz&&zoom>mz){for(var i=0,marker;marker=this.markers_[i];i++){marker.setMap(this.map_)}return}if(this.markers_.length0&&this.anchor_[0]0&&this.anchor_[1] .pickup_search_here",function(){pickup_sites.search_lat=pickup_sites.mapa.center.lat();pickup_sites.search_lng=pickup_sites.mapa.center.lng();pickup_sites.ajaxGetPickup(true)});var mymap;var isLoaded=false;var isWaitingEnd=false;var leafletGetPickups=function(lat,long,current_zoom){if(current_zoom>=15){radius=1}else if(current_zoom==14){radius=2}else if(current_zoom==13){radius=4}else if(current_zoom==12){radius=7}else if(current_zoom==11){radius=10}else if(current_zoom==10){radius=15}else{radius=20}if(current_zoom){var options={courierId:pickup_sites.courierId,"location[latitude]":lat,"location[longitude]":long,radius:radius,isCod:pickup_sites.isCod}}else{var options={courierId:pickup_sites.courierId,"location[latitude]":lat,"location[longitude]":long,isCod:pickup_sites.isCod}}$.ajax({type:"GET",url:"/ajax/getPickups.php",data:options,dataType:"json",success:function(json){if(!jQuery.isEmptyObject(selected_pickup_point)){for(i in json.pickupPoints){if(json.pickupPoints[i].id==selected_pickup_point.id){delete json.pickupPoints[i]}}json.pickupPoints.unshift(selected_pickup_point);console.log("pickupPoints unshift")}if(!json.pickupPoints.length){if($("div.asideContainer_pickup .menu_messages_message").length)$("div.asideContainer_pickup .menu_messages_message").remove();if(radius){if($("div.asideContainer_pickup .menu_messages_message").length)$("div.asideContainer_pickup .menu_messages_message").remove();$("div.asideContainer_pickup").prepend('")}else{$("div.asideContainer_pickup").prepend('")}$(".loadingMap").hide();return false}leafletItems=[];for(i in json.pickupPoints){var pickupLat=json.pickupPoints[i].coordinates.latitude;var pickupLon=json.pickupPoints[i].coordinates.longitude;if(pickupLat==""||pickupLon==""){$.ajaxSetup({async:false});$.get(location.protocol+"//nominatim.openstreetmap.org/search?format=json&q="+json.pickupPoints[i].address.street+", "+json.pickupPoints[i].address.city+" "+json.pickupPoints[i].address.city+" "+json.pickupPoints[i].address.country,function(data){if(!jQuery.isEmptyObject(data)){pickupLat=data[0].lat;pickupLon=data[0].lon}else{console.log("nie mogę znaleźć korodynatów adresu!")}})}leafletItems.push({id:json.pickupPoints[i].id,name:json.pickupPoints[i].name,link:json.pickupPoints[i].link,address:json.pickupPoints[i].address,lat:pickupLat,lon:pickupLon})}setPickupPointsNoMap(json,false,true);if(!jQuery.isEmptyObject(leafletItems)){leafletStartMap(leafletItems[0].lat,leafletItems[0].lon,true)}},error:function(){if($("div.asideContainer_pickup .menu_messages_message").length)$("div.asideContainer_pickup .menu_messages_message").remove();$("div.asideContainer_pickup").prepend('");$(".asideContainer_pickup label.pickup_point").each(function(){var aId=$(this).data("id");var aName=$(this).find(".headerText").text();var aLink=$(this).find(".map_dir").attr("href");var aAddress=$(this).find(".streetText").text()+"
"+$(this).find(".zipcodePickup").text();var aLat=$(this).data("latitude");var aLon=$(this).data("longitude");leafletItems.push({id:aId,name:aName,link:aLink,address:aAddress,lat:aLat,lon:aLon})});if(leafletItems[0].lat&&leafletItems[0].lon)leafletStartMap(leafletItems[0].lat,leafletItems[0].lon,true)}})};var leafletMarker=new Array;var leafletItems=[];function leafletDelMarkers(){for(i=0;iOpenStreetMap contributors'}).addTo(mymap);isLoaded=true;isWaitingEnd=true}$(".loadingPoints").remove();for(i=0;i`+stocks_list_more_txt+``+stocks_list_choose+``;let addressTxt="";if(leafletItems[i].address.street!=undefined){addressTxt=`
`+leafletItems[i].address.street+` `+leafletItems[i].address.buildingAndHouseNumber+` `+leafletItems[i].address.city+`
`}else{addressTxt=`
`+leafletItems[i].address+`
`}let button_text=``+leafletItems[i].name+`
`+addressTxt+`
`+href;markersList.push(leafletItems[i].id);markers[leafletItems[i].id]=L.marker([leafletItems[i].lat,leafletItems[i].lon],{icon:newMarkerIcon}).addTo(mymap).on("click",leafletOnClick).bindPopup(button_text)}mymap.setView(new L.LatLng(lat,long));let pointId=$(".asideContainer_pickup label.pickup_point").eq(0).attr("data-id");$('.asideContainer_pickup input[value="'+pointId+'"]').click();$("img.leaflet-marker-icon").each(function(){var href=$(this).attr("src");var href_prev=href.includes("preview/");if(href_prev)href=href.replace("preview/","");var href_2x=href.includes("marker-icon");if(href_2x)href=href.replace("-2x","");$(this).attr("src",href)})};var timeoutLeafLet=null;$(document).on("input","#autocomplete_location.autocomplete_nomap",function(){var that=$(this);clearTimeout(timeoutLeafLet);timeoutLeafLet=setTimeout(function(){if(that.val().length>3){leafletGetLocation(that.val())}},500)});$(document).off("click.suggestions").on("click.suggestions",".leafleat-suggestions div",function(){$("#autocomplete_location").val($(this).text());$(".leafleat-suggestions").remove();const lat=$(this).attr("data-lat");const lon=$(this).attr("data-lon");leafletDelMarkers();selected_pickup_point={};leafletGetPickups(lat,lon)});$(document).on("click",".map_button_search > .pickup_search_here_leaflet",function(){var cords=mymap.getCenter();var zoom=mymap.getZoom();leafletDelMarkers();selected_pickup_point={};leafletGetPickups(cords.lat,cords.lng,zoom)});$(document).on("click",'#pickup_site [name="pickup_point"], #pickup_site [name="stock"]',function(){const id=$(this).val();if(markers[id]){let thatMarkerCoords=markers[id].getLatLng();mymap.setView(new L.LatLng(thatMarkerCoords.lat,thatMarkerCoords.lng));markers[id].openPopup()}});var leafletGetCoords=function(address){let mymapLat="",mymapLong="";if(address){$.get(location.protocol+"//nominatim.openstreetmap.org/search?format=json&q="+address,function(data){if(!jQuery.isEmptyObject(data)){mymapLat=data[0].lat;mymapLong=data[0].lon;leafletGetPickups(mymapLat,mymapLong)}else{if($(".asideContainer_pickup label.pickup_point").length){$(".asideContainer_pickup label.pickup_point").each(function(){var aId=$(this).data("id");var aName=$(this).find(".headerText").text();var aLink=$(this).find(".map_dir").attr("href");var aAddress=$(this).find(".streetText").text()+"
"+$(this).find(".zipcodePickup").text();var aLat=$(this).data("latitude");var aLon=$(this).data("longitude");leafletItems.push({id:aId,name:aName,link:aLink,address:aAddress,lat:aLat,lon:aLon})});leafletStartMap(leafletItems[0].lat,leafletItems[0].lon,true)}if($("div.asideContainer_pickup .menu_messages_message").length)$("div.asideContainer_pickup .menu_messages_message").remove();$("div.asideContainer_pickup").prepend('")}})}else{if($(".asideContainer_pickup label.pickup_point").length){$(".asideContainer_pickup label.pickup_point").each(function(){var aId=$(this).data("id");var aName=$(this).find(".headerText").text();var aLink=$(this).find(".map_dir").attr("href");var aAddress=$(this).find(".streetText").text()+"
"+$(this).find(".zipcodePickup").text();var aLat=$(this).data("latitude");var aLon=$(this).data("longitude");leafletItems.push({id:aId,name:aName,link:aLink,address:aAddress,lat:aLat,lon:aLon})});leafletStartMap(leafletItems[0].lat,leafletItems[0].lon,true)}}};var leafletGetLocation=function(address){$.get(location.protocol+"//nominatim.openstreetmap.org/search?format=json&q="+address,function(data){if(!jQuery.isEmptyObject(data)){$("#locationField").append('
');for(i in data){$(".leafleat-suggestions").append('
'+data[i].display_name+"
")}}else{leafletStartMap(53.428,14.552,true);if($("div.asideContainer_pickup .menu_messages_message").length)$("div.asideContainer_pickup .menu_messages_message").remove();$("div.asideContainer_pickup").prepend('")}})};var leafletGetTextLocation=function(){$("#mymap").prepend(`
${}...
`);var text=$("#autocomplete_location").val();selected_pickup_point={};$.get(location.protocol+"//nominatim.openstreetmap.org/search?format=json&q="+text,function(data){if(!jQuery.isEmptyObject(data)){leafletDelMarkers();leafletGetPickups(data[0].lat,data[0].lon);$("#autocomplete_location").val(data[0].display_name)}else{if(text.search(",")){var srp=text.split(",");var new_address=srp[srp.length-1].trim();leafletGetCoords(new_address)}if($("div.asideContainer_pickup .menu_messages_message").length)$("div.asideContainer_pickup .menu_messages_message").remove();$("div.asideContainer_pickup").prepend('")}})};app_shop.run(function(){if($("#autocomplete_location").length&&$("#autocomplete_location").val()!=""){let leafletAddress=$("#autocomplete_location").val();leafletGetCoords(leafletAddress)}else{leafletGetCoords(false)}},"all","#mymap");app_shop.run(function(){$("#mymap").before($(".map_button_search"))},1,"#mymap");app_shop.run(function(){$("#mymap").prepend($(".map_button_search"))},[2,3,4],"#mymap");!function(t,i){"object"==typeof exports&&"undefined"!=typeof module?i(exports):"function"==typeof define&&define.amd?define(["exports"],i):i(t.L={})}(this,function(t){"use strict";var i=Object.freeze;function h(t){var i,e,n,o;for(e=1,n=arguments.length;e=this.min.x&&e.x<=this.max.x&&i.y>=this.min.y&&e.y<=this.max.y},intersects:function(t){t=R(t);var i=this.min,e=this.max,n=t.min,o=t.max,s=o.x>=i.x&&n.x<=e.x,r=o.y>=i.y&&n.y<=e.y;return s&&r},overlaps:function(t){t=R(t);var i=this.min,e=this.max,n=t.min,o=t.max,s=o.x>i.x&&n.xi.y&&n.y=n.lat&&e.lat<=o.lat&&i.lng>=n.lng&&e.lng<=o.lng},intersects:function(t){t=D(t);var i=this._southWest,e=this._northEast,n=t.getSouthWest(),o=t.getNorthEast(),s=o.lat>=i.lat&&n.lat<=e.lat,r=o.lng>=i.lng&&n.lng<=e.lng;return s&&r},overlaps:function(t){t=D(t);var i=this._southWest,e=this._northEast,n=t.getSouthWest(),o=t.getNorthEast(),s=o.lat>i.lat&&n.lati.lng&&n.lng';var i=t.firstChild;return i.style.behavior="url(#default#VML)",i&&"object"==typeof i.adj}catch(t){return!1}}();function Bt(t){return 0<=navigator.userAgent.toLowerCase().indexOf(t)}var At=(Object.freeze||Object)({ie:it,ielt9:et,edge:nt,webkit:ot,android:st,android23:rt,androidStock:ht,opera:ut,chrome:lt,gecko:ct,safari:_t,phantom:dt,opera12:pt,win:mt,ie3d:ft,webkit3d:gt,gecko3d:vt,any3d:yt,mobile:xt,mobileWebkit:wt,mobileWebkit3d:Pt,msPointer:Lt,pointer:bt,touch:Tt,mobileOpera:zt,mobileGecko:Mt,retina:Ct,passiveEvents:Et,canvas:St,svg:Zt,vml:kt}),It=Lt?"MSPointerDown":"pointerdown",Ot=Lt?"MSPointerMove":"pointermove",Rt=Lt?"MSPointerUp":"pointerup",Nt=Lt?"MSPointerCancel":"pointercancel",Dt=["INPUT","SELECT","OPTION"],jt={},Wt=!1,Ht=0;function Ft(t,i,e,n){return"touchstart"===i?function(t,i,e){var n=a(function(t){if("mouse"!==t.pointerType&&t.MSPOINTER_TYPE_MOUSE&&t.pointerType!==t.MSPOINTER_TYPE_MOUSE){if(!(Dt.indexOf(t.target.tagName)<0))return;ji(t)}Gt(t,i)});t["_leaflet_touchstart"+e]=n,t.addEventListener(It,n,!1),Wt||(document.documentElement.addEventListener(It,Ut,!0),document.documentElement.addEventListener(Ot,Vt,!0),document.documentElement.addEventListener(Rt,qt,!0),document.documentElement.addEventListener(Nt,qt,!0),Wt=!0)}(t,e,n):"touchmove"===i?function(t,i,e){function n(t){(t.pointerType!==t.MSPOINTER_TYPE_MOUSE&&"mouse"!==t.pointerType||0!==t.buttons)&&Gt(t,i)}t["_leaflet_touchmove"+e]=n,t.addEventListener(Ot,n,!1)}(t,e,n):"touchend"===i&&function(t,i,e){function n(t){Gt(t,i)}t["_leaflet_touchend"+e]=n,t.addEventListener(Rt,n,!1),t.addEventListener(Nt,n,!1)}(t,e,n),this}function Ut(t){jt[t.pointerId]=t,Ht++}function Vt(t){jt[t.pointerId]&&(jt[t.pointerId]=t)}function qt(t){delete jt[t.pointerId],Ht--}function Gt(t,i){for(var e in t.touches=[],jt)t.touches.push(jt[e]);t.changedTouches=[t],i(t)}var Kt=Lt?"MSPointerDown":bt?"pointerdown":"touchstart",Yt=Lt?"MSPointerUp":bt?"pointerup":"touchend",Xt="_leaflet_";function Jt(t,o,i){var s,r,a=!1;function e(t){var i;if(bt){if(!nt||"mouse"===t.pointerType)return;i=Ht}else i=t.touches.length;if(!(1this.options.maxZoom)?this.setZoom(t):this},panInsideBounds:function(t,i){this._enforcingBounds=!0;var e=this.getCenter(),n=this._limitCenter(e,this._zoom,D(t));return e.equals(n)||this.panTo(n,i),this._enforcingBounds=!1,this},panInside:function(t,i){var e=I((i=i||{}).paddingTopLeft||i.padding||[0,0]),n=I(i.paddingBottomRight||i.padding||[0,0]),o=this.getCenter(),s=this.project(o),r=this.project(t),a=this.getPixelBounds(),h=a.getSize().divideBy(2),u=R([a.min.add(e),a.max.subtract(n)]);if(!u.contains(r)){this._enforcingBounds=!0;var l=s.subtract(r),c=I(r.x+l.x,r.y+l.y);(r.xu.max.x)&&(c.x=s.x-l.x,0u.max.y)&&(c.y=s.y-l.y,0=this.options.transform3DLimit&&this._resetView(this.getCenter(),this.getZoom())},_findEventTargets:function(t,i){for(var e,n=[],o="mouseout"===i||"mouseover"===i,s=t.target||t.srcElement,r=!1;s;){if((e=this._targets[u(s)])&&("click"===i||"preclick"===i)&&!t._simulated&&this._draggableMoved(e)){r=!0;break}if(e&&e.listens(i,!0)){if(o&&!Yi(s,t))break;if(n.push(e),o)break}if(s===this._container)break;s=s.parentNode}return n.length||r||o||!Yi(s,t)||(n=[this]),n},_handleDOMEvent:function(t){if(this._loaded&&!Ki(t)){var i=t.type;"mousedown"!==i&&"keypress"!==i&&"keyup"!==i&&"keydown"!==i||Mi(t.target||t.srcElement),this._fireDOMEvent(t,i)}},_mouseEvents:["click","dblclick","mouseover","mouseout","contextmenu"],_fireDOMEvent:function(t,i,e){if("click"===t.type){var n=h({},t);n.type="preclick",this._fireDOMEvent(n,n.type,e)}if(!t._stopped&&(e=(e||[]).concat(this._findEventTargets(t,i))).length){var o=e[0];"contextmenu"===i&&o.listens(i,!0)&&ji(t);var s={originalEvent:t};if("keypress"!==t.type&&"keydown"!==t.type&&"keyup"!==t.type){var r=o.getLatLng&&(!o._radius||o._radius<=10);s.containerPoint=r?this.latLngToContainerPoint(o.getLatLng()):this.mouseEventToContainerPoint(t),s.layerPoint=this.containerPointToLayerPoint(s.containerPoint),s.latlng=r?o.getLatLng():this.layerPointToLatLng(s.layerPoint)}for(var a=0;athis.options.zoomAnimationThreshold)return!1;var n=this.getZoomScale(i),o=this._getCenterOffset(t)._divideBy(1-1/n);return!(!0!==e.animate&&!this.getSize().contains(o))&&(M(function(){this._moveStart(!0,!1)._animateZoom(t,i,!0)},this),!0)},_animateZoom:function(t,i,e,n){this._mapPane&&(e&&(this._animatingZoom=!0,this._animateToCenter=t,this._animateToZoom=i,mi(this._mapPane,"leaflet-zoom-anim")),this.fire("zoomanim",{center:t,zoom:i,noUpdate:n}),setTimeout(a(this._onZoomTransitionEnd,this),250))},_onZoomTransitionEnd:function(){this._animatingZoom&&(this._mapPane&&fi(this._mapPane,"leaflet-zoom-anim"),this._animatingZoom=!1,this._move(this._animateToCenter,this._animateToZoom),M(function(){this._moveEnd(!0)},this))}});function Qi(t){return new te(t)}var te=S.extend({options:{position:"topright"},initialize:function(t){p(this,t)},getPosition:function(){return this.options.position},setPosition:function(t){var i=this._map;return i&&i.removeControl(this),this.options.position=t,i&&i.addControl(this),this},getContainer:function(){return this._container},addTo:function(t){this.remove(),this._map=t;var i=this._container=this.onAdd(t),e=this.getPosition(),n=t._controlCorners[e];return mi(i,"leaflet-control"),-1!==e.indexOf("bottom")?n.insertBefore(i,n.firstChild):n.appendChild(i),this._map.on("unload",this.remove,this),this},remove:function(){return this._map&&(li(this._container),this.onRemove&&this.onRemove(this._map),this._map.off("unload",this.remove,this),this._map=null),this},_refocusOnMap:function(t){this._map&&t&&0",n=document.createElement("div");return n.innerHTML=e,n.firstChild},_addItem:function(t){var i,e=document.createElement("label"),n=this._map.hasLayer(t.layer);t.overlay?((i=document.createElement("input")).type="checkbox",i.className="leaflet-control-layers-selector",i.defaultChecked=n):i=this._createRadioElement("leaflet-base-layers_"+u(this),n),this._layerControlInputs.push(i),i.layerId=u(t.layer),ki(i,"click",this._onInputClick,this);var o=document.createElement("span");o.innerHTML=" "+t.name;var s=document.createElement("div");return e.appendChild(s),s.appendChild(i),s.appendChild(o),(t.overlay?this._overlaysList:this._baseLayersList).appendChild(e),this._checkDisabledLayers(),e},_onInputClick:function(){var t,i,e=this._layerControlInputs,n=[],o=[];this._handlingClick=!0;for(var s=e.length-1;0<=s;s--)t=e[s],i=this._getLayer(t.layerId).layer,t.checked?n.push(i):t.checked||o.push(i);for(s=0;si.options.maxZoom},_expandIfNotCollapsed:function(){return this._map&&!this.options.collapsed&&this.expand(),this},_expand:function(){return this.expand()},_collapse:function(){return this.collapse()}}),ee=te.extend({options:{position:"topleft",zoomInText:"+",zoomInTitle:"Zoom in",zoomOutText:"−",zoomOutTitle:"Zoom out"},onAdd:function(t){var i="leaflet-control-zoom",e=ui("div",i+" leaflet-bar"),n=this.options;return this._zoomInButton=this._createButton(n.zoomInText,n.zoomInTitle,i+"-in",e,this._zoomIn),this._zoomOutButton=this._createButton(n.zoomOutText,n.zoomOutTitle,i+"-out",e,this._zoomOut),this._updateDisabled(),t.on("zoomend zoomlevelschange",this._updateDisabled,this),e},onRemove:function(t){t.off("zoomend zoomlevelschange",this._updateDisabled,this)},disable:function(){return this._disabled=!0,this._updateDisabled(),this},enable:function(){return this._disabled=!1,this._updateDisabled(),this},_zoomIn:function(t){!this._disabled&&this._map._zoomthis._map.getMinZoom()&&this._map.zoomOut(this._map.options.zoomDelta*(t.shiftKey?3:1))},_createButton:function(t,i,e,n,o){var s=ui("a",e,n);return s.innerHTML=t,s.href="#",s.title=i,s.setAttribute("role","button"),s.setAttribute("aria-label",i),Di(s),ki(s,"click",Wi),ki(s,"click",o,this),ki(s,"click",this._refocusOnMap,this),s},_updateDisabled:function(){var t=this._map,i="leaflet-disabled";fi(this._zoomInButton,i),fi(this._zoomOutButton,i),!this._disabled&&t._zoom!==t.getMinZoom()||mi(this._zoomOutButton,i),!this._disabled&&t._zoom!==t.getMaxZoom()||mi(this._zoomInButton,i)}});$i.mergeOptions({zoomControl:!0}),$i.addInitHook(function(){this.options.zoomControl&&(this.zoomControl=new ee,this.addControl(this.zoomControl))});var ne=te.extend({options:{position:"bottomleft",maxWidth:100,metric:!0,imperial:!0},onAdd:function(t){var i="leaflet-control-scale",e=ui("div",i),n=this.options;return this._addScales(n,i+"-line",e),t.on(n.updateWhenIdle?"moveend":"move",this._update,this),t.whenReady(this._update,this),e},onRemove:function(t){t.off(this.options.updateWhenIdle?"moveend":"move",this._update,this)},_addScales:function(t,i,e){t.metric&&(this._mScale=ui("div",i,e)),t.imperial&&(this._iScale=ui("div",i,e))},_update:function(){var t=this._map,i=t.getSize().y/2,e=t.distance(t.containerPointToLatLng([0,i]),t.containerPointToLatLng([this.options.maxWidth,i]));this._updateScales(e)},_updateScales:function(t){this.options.metric&&t&&this._updateMetric(t),this.options.imperial&&t&&this._updateImperial(t)},_updateMetric:function(t){var i=this._getRoundNum(t),e=i<1e3?i+" m":i/1e3+" km";this._updateScale(this._mScale,e,i/t)},_updateImperial:function(t){var i,e,n,o=3.2808399*t;5280Leaflet'},initialize:function(t){p(this,t),this._attributions={}},onAdd:function(t){for(var i in(t.attributionControl=this)._container=ui("div","leaflet-control-attribution"),Di(this._container),t._layers)t._layers[i].getAttribution&&this.addAttribution(t._layers[i].getAttribution());return this._update(),this._container},setPrefix:function(t){return this.options.prefix=t,this._update(),this},addAttribution:function(t){return t&&(this._attributions[t]||(this._attributions[t]=0),this._attributions[t]++,this._update()),this},removeAttribution:function(t){return t&&this._attributions[t]&&(this._attributions[t]--,this._update()),this},_update:function(){if(this._map){var t=[];for(var i in this._attributions)this._attributions[i]&&t.push(i);var e=[];this.options.prefix&&e.push(this.options.prefix),t.length&&e.push(t.join(", ")),this._container.innerHTML=e.join(" | ")}}});$i.mergeOptions({attributionControl:!0}),$i.addInitHook(function(){this.options.attributionControl&&(new oe).addTo(this)});te.Layers=ie,te.Zoom=ee,te.Scale=ne,te.Attribution=oe,Qi.layers=function(t,i,e){return new ie(t,i,e)},Qi.zoom=function(t){return new ee(t)},Qi.scale=function(t){return new ne(t)},Qi.attribution=function(t){return new oe(t)};var se=S.extend({initialize:function(t){this._map=t},enable:function(){return this._enabled||(this._enabled=!0,this.addHooks()),this},disable:function(){return this._enabled&&(this._enabled=!1,this.removeHooks()),this},enabled:function(){return!!this._enabled}});se.addTo=function(t,i){return t.addHandler(i,this),this};var re,ae={Events:Z},he=Tt?"touchstart mousedown":"mousedown",ue={mousedown:"mouseup",touchstart:"touchend",pointerdown:"touchend",MSPointerDown:"touchend"},le={mousedown:"mousemove",touchstart:"touchmove",pointerdown:"touchmove",MSPointerDown:"touchmove"},ce=k.extend({options:{clickTolerance:3},initialize:function(t,i,e,n){p(this,n),this._element=t,this._dragStartTarget=i||t,this._preventOutline=e},enable:function(){this._enabled||(ki(this._dragStartTarget,he,this._onDown,this),this._enabled=!0)},disable:function(){this._enabled&&(ce._dragging===this&&this.finishDrag(),Ai(this._dragStartTarget,he,this._onDown,this),this._enabled=!1,this._moved=!1)},_onDown:function(t){if(!t._simulated&&this._enabled&&(this._moved=!1,!pi(this._element,"leaflet-zoom-anim")&&!(ce._dragging||t.shiftKey||1!==t.which&&1!==t.button&&!t.touches||((ce._dragging=this)._preventOutline&&Mi(this._element),Ti(),Qt(),this._moving)))){this.fire("down");var i=t.touches?t.touches[0]:t,e=Ei(this._element);this._startPoint=new B(i.clientX,i.clientY),this._parentScale=Si(e),ki(document,le[t.type],this._onMove,this),ki(document,ue[t.type],this._onUp,this)}},_onMove:function(t){if(!t._simulated&&this._enabled)if(t.touches&&1i.max.x&&(e|=2),t.yi.max.y&&(e|=8),e}function ge(t,i,e,n){var o,s=i.x,r=i.y,a=e.x-s,h=e.y-r,u=a*a+h*h;return 0this._layersMaxZoom&&this.setZoom(this._layersMaxZoom),void 0===this.options.minZoom&&this._layersMinZoom&&this.getZoom()t.y!=n.y>t.y&&t.x<(n.x-e.x)*(t.y-e.y)/(n.y-e.y)+e.x&&(u=!u);return u||je.prototype._containsPoint.call(this,t,!0)}});var He=ke.extend({initialize:function(t,i){p(this,i),this._layers={},t&&this.addData(t)},addData:function(t){var i,e,n,o=v(t)?t:t.features;if(o){for(i=0,e=o.length;iu.x&&(l=s.x+n-u.x+h.x),s.x-l-a.x<0&&(l=s.x-a.x),s.y+e+h.y>u.y&&(c=s.y+e-u.y+h.y),s.y-c-a.y<0&&(c=s.y-a.y),(l||c)&&t.fire("autopanstart").panBy([l,c])}},_onCloseButtonClick:function(t){this._close(),Wi(t)},_getAnchor:function(){return I(this._source&&this._source._getPopupAnchor?this._source._getPopupAnchor():[0,0])}});$i.mergeOptions({closePopupOnClick:!0}),$i.include({openPopup:function(t,i,e){return t instanceof sn||(t=new sn(e).setContent(t)),i&&t.setLatLng(i),this.hasLayer(t)?this:(this._popup&&this._popup.options.autoClose&&this.closePopup(),this._popup=t,this.addLayer(t))},closePopup:function(t){return t&&t!==this._popup||(t=this._popup,this._popup=null),t&&this.removeLayer(t),this}}),Se.include({bindPopup:function(t,i){return t instanceof sn?(p(t,i),(this._popup=t)._source=this):(this._popup&&!i||(this._popup=new sn(i,this)),this._popup.setContent(t)),this._popupHandlersAdded||(this.on({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!0),this},unbindPopup:function(){return this._popup&&(this.off({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!1,this._popup=null),this},openPopup:function(t,i){return this._popup&&this._map&&(i=this._popup._prepareOpen(this,t,i),this._map.openPopup(this._popup,i)),this},closePopup:function(){return this._popup&&this._popup._close(),this},togglePopup:function(t){return this._popup&&(this._popup._map?this.closePopup():this.openPopup(t)),this},isPopupOpen:function(){return!!this._popup&&this._popup.isOpen()},setPopupContent:function(t){return this._popup&&this._popup.setContent(t),this},getPopup:function(){return this._popup},_openPopup:function(t){var i=t.layer||t.target;this._popup&&this._map&&(Wi(t),i instanceof Re?this.openPopup(t.layer||t.target,t.latlng):this._map.hasLayer(this._popup)&&this._popup._source===i?this.closePopup():this.openPopup(i,t.latlng))},_movePopup:function(t){this._popup.setLatLng(t.latlng)},_onKeyPress:function(t){13===t.originalEvent.keyCode&&this._openPopup(t)}});var rn=on.extend({options:{pane:"tooltipPane",offset:[0,0],direction:"auto",permanent:!1,sticky:!1,interactive:!1,opacity:.9},onAdd:function(t){on.prototype.onAdd.call(this,t),this.setOpacity(this.options.opacity),t.fire("tooltipopen",{tooltip:this}),this._source&&this._source.fire("tooltipopen",{tooltip:this},!0)},onRemove:function(t){on.prototype.onRemove.call(this,t),t.fire("tooltipclose",{tooltip:this}),this._source&&this._source.fire("tooltipclose",{tooltip:this},!0)},getEvents:function(){var t=on.prototype.getEvents.call(this);return Tt&&!this.options.permanent&&(t.preclick=this._close),t},_close:function(){this._map&&this._map.closeTooltip(this)},_initLayout:function(){var t="leaflet-tooltip "+(this.options.className||"")+" leaflet-zoom-"+(this._zoomAnimated?"animated":"hide");this._contentNode=this._container=ui("div",t)},_updateLayout:function(){},_adjustPan:function(){},_setPosition:function(t){var i=this._map,e=this._container,n=i.latLngToContainerPoint(i.getCenter()),o=i.layerPointToContainerPoint(t),s=this.options.direction,r=e.offsetWidth,a=e.offsetHeight,h=I(this.options.offset),u=this._getAnchor();t="top"===s?t.add(I(-r/2+h.x,-a+h.y+u.y,!0)):"bottom"===s?t.subtract(I(r/2-h.x,-h.y,!0)):"center"===s?t.subtract(I(r/2+h.x,a/2-u.y+h.y,!0)):"right"===s||"auto"===s&&o.xthis.options.maxZoom||ethis.options.maxZoom||void 0!==this.options.minZoom&&oe.max.x)||!i.wrapLat&&(t.ye.max.y))return!1}if(!this.options.bounds)return!0;var n=this._tileCoordsToBounds(t);return D(this.options.bounds).overlaps(n)},_keyToBounds:function(t){return this._tileCoordsToBounds(this._keyToTileCoords(t))},_tileCoordsToNwSe:function(t){var i=this._map,e=this.getTileSize(),n=t.scaleBy(e),o=n.add(e);return[i.unproject(n,t.z),i.unproject(o,t.z)]},_tileCoordsToBounds:function(t){var i=this._tileCoordsToNwSe(t),e=new N(i[0],i[1]);return this.options.noWrap||(e=this._map.wrapLatLngBounds(e)),e},_tileCoordsToKey:function(t){return t.x+":"+t.y+":"+t.z},_keyToTileCoords:function(t){var i=t.split(":"),e=new B(+i[0],+i[1]);return e.z=+i[2],e},_removeTile:function(t){var i=this._tiles[t];i&&(li(i.el),delete this._tiles[t],this.fire("tileunload",{tile:i.el,coords:this._keyToTileCoords(t)}))},_initTile:function(t){mi(t,"leaflet-tile");var i=this.getTileSize();t.style.width=i.x+"px",t.style.height=i.y+"px",t.onselectstart=l,t.onmousemove=l,et&&this.options.opacity<1&&yi(t,this.options.opacity),st&&!rt&&(t.style.WebkitBackfaceVisibility="hidden")},_addTile:function(t,i){var e=this._getTilePos(t),n=this._tileCoordsToKey(t),o=this.createTile(this._wrapCoords(t),a(this._tileReady,this,t));this._initTile(o),this.createTile.length<2&&M(a(this._tileReady,this,t,null,o)),Pi(o,e),this._tiles[n]={el:o,coords:t,current:!0},i.appendChild(o),this.fire("tileloadstart",{tile:o,coords:t})},_tileReady:function(t,i,e){i&&this.fire("tileerror",{error:i,tile:e,coords:t});var n=this._tileCoordsToKey(t);(e=this._tiles[n])&&(e.loaded=+new Date,this._map._fadeAnimated?(yi(e.el,0),C(this._fadeFrame),this._fadeFrame=M(this._updateOpacity,this)):(e.active=!0,this._pruneTiles()),i||(mi(e.el,"leaflet-tile-loaded"),this.fire("tileload",{tile:e.el,coords:t})),this._noTilesToLoad()&&(this._loading=!1,this.fire("load"),et||!this._map._fadeAnimated?M(this._pruneTiles,this):setTimeout(a(this._pruneTiles,this),250)))},_getTilePos:function(t){return t.scaleBy(this.getTileSize()).subtract(this._level.origin)},_wrapCoords:function(t){var i=new B(this._wrapX?r(t.x,this._wrapX):t.x,this._wrapY?r(t.y,this._wrapY):t.y);return i.z=t.z,i},_pxBoundsToTileRange:function(t){var i=this.getTileSize();return new O(t.min.unscaleBy(i).floor(),t.max.unscaleBy(i).ceil().subtract([1,1]))},_noTilesToLoad:function(){for(var t in this._tiles)if(!this._tiles[t].loaded)return!1;return!0}});var un=hn.extend({options:{minZoom:0,maxZoom:18,subdomains:"abc",errorTileUrl:"",zoomOffset:0,tms:!1,zoomReverse:!1,detectRetina:!1,crossOrigin:!1},initialize:function(t,i){this._url=t,(i=p(this,i)).detectRetina&&Ct&&0')}}catch(t){return function(t){return document.createElement("<"+t+' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')}}}(),fn={_initContainer:function(){this._container=ui("div","leaflet-vml-container")},_update:function(){this._map._animatingZoom||(_n.prototype._update.call(this),this.fire("update"))},_initPath:function(t){var i=t._container=mn("shape");mi(i,"leaflet-vml-shape "+(this.options.className||"")),i.coordsize="1 1",t._path=mn("path"),i.appendChild(t._path),this._updateStyle(t),this._layers[u(t)]=t},_addPath:function(t){var i=t._container;this._container.appendChild(i),t.options.interactive&&t.addInteractiveTarget(i)},_removePath:function(t){var i=t._container;li(i),t.removeInteractiveTarget(i),delete this._layers[u(t)]},_updateStyle:function(t){var i=t._stroke,e=t._fill,n=t.options,o=t._container;o.stroked=!!n.stroke,o.filled=!!n.fill,n.stroke?(i||(i=t._stroke=mn("stroke")),o.appendChild(i),i.weight=n.weight+"px",i.color=n.color,i.opacity=n.opacity,n.dashArray?i.dashStyle=v(n.dashArray)?n.dashArray.join(" "):n.dashArray.replace(/( *, *)/g," "):i.dashStyle="",i.endcap=n.lineCap.replace("butt","flat"),i.joinstyle=n.lineJoin):i&&(o.removeChild(i),t._stroke=null),n.fill?(e||(e=t._fill=mn("fill")),o.appendChild(e),e.color=n.fillColor||n.color,e.opacity=n.fillOpacity):e&&(o.removeChild(e),t._fill=null)},_updateCircle:function(t){var i=t._point.round(),e=Math.round(t._radius),n=Math.round(t._radiusY||e);this._setPath(t,t._empty()?"M0 0":"AL "+i.x+","+i.y+" "+e+","+n+" 0,23592600")},_setPath:function(t,i){t._path.v=i},_bringToFront:function(t){_i(t._container)},_bringToBack:function(t){di(t._container)}},gn=kt?mn:$,vn=_n.extend({getEvents:function(){var t=_n.prototype.getEvents.call(this);return t.zoomstart=this._onZoomStart,t},_initContainer:function(){this._container=gn("svg"),this._container.setAttribute("pointer-events","none"),this._rootGroup=gn("g"),this._container.appendChild(this._rootGroup)},_destroyContainer:function(){li(this._container),Ai(this._container),delete this._container,delete this._rootGroup,delete this._svgSize},_onZoomStart:function(){this._update()},_update:function(){if(!this._map._animatingZoom||!this._bounds){_n.prototype._update.call(this);var t=this._bounds,i=t.getSize(),e=this._container;this._svgSize&&this._svgSize.equals(i)||(this._svgSize=i,e.setAttribute("width",i.x),e.setAttribute("height",i.y)),Pi(e,t.min),e.setAttribute("viewBox",[t.min.x,t.min.y,i.x,i.y].join(" ")),this.fire("update")}},_initPath:function(t){var i=t._path=gn("path");t.options.className&&mi(i,t.options.className),t.options.interactive&&mi(i,"leaflet-interactive"),this._updateStyle(t),this._layers[u(t)]=t},_addPath:function(t){this._rootGroup||this._initContainer(),this._rootGroup.appendChild(t._path),t.addInteractiveTarget(t._path)},_removePath:function(t){li(t._path),t.removeInteractiveTarget(t._path),delete this._layers[u(t)]},_updatePath:function(t){t._project(),t._update()},_updateStyle:function(t){var i=t._path,e=t.options;i&&(e.stroke?(i.setAttribute("stroke",e.color),i.setAttribute("stroke-opacity",e.opacity),i.setAttribute("stroke-width",e.weight),i.setAttribute("stroke-linecap",e.lineCap),i.setAttribute("stroke-linejoin",e.lineJoin),e.dashArray?i.setAttribute("stroke-dasharray",e.dashArray):i.removeAttribute("stroke-dasharray"),e.dashOffset?i.setAttribute("stroke-dashoffset",e.dashOffset):i.removeAttribute("stroke-dashoffset")):i.setAttribute("stroke","none"),e.fill?(i.setAttribute("fill",e.fillColor||e.color),i.setAttribute("fill-opacity",e.fillOpacity),i.setAttribute("fill-rule",e.fillRule||"evenodd")):i.setAttribute("fill","none"))},_updatePoly:function(t,i){this._setPath(t,Q(t._parts,i))},_updateCircle:function(t){var i=t._point,e=Math.max(Math.round(t._radius),1),n="a"+e+","+(Math.max(Math.round(t._radiusY),1)||e)+" 0 1,0 ",o=t._empty()?"M0 0":"M"+(i.x-e)+","+i.y+n+2*e+",0 "+n+2*-e+",0 ";this._setPath(t,o)},_setPath:function(t,i){t._path.setAttribute("d",i)},_bringToFront:function(t){_i(t._path)},_bringToBack:function(t){di(t._path)}});function yn(t){return Zt||kt?new vn(t):null}kt&&vn.include(fn),$i.include({getRenderer:function(t){var i=t.options.renderer||this._getPaneRenderer(t.options.pane)||this.options.renderer||this._renderer;return i||(i=this._renderer=this._createRenderer()),this.hasLayer(i)||this.addLayer(i),i},_getPaneRenderer:function(t){if("overlayPane"===t||void 0===t)return!1;var i=this._paneRenderers[t];return void 0===i&&(i=this._createRenderer({pane:t}),this._paneRenderers[t]=i),i},_createRenderer:function(t){return this.options.preferCanvas&&pn(t)||yn(t)}});var xn=We.extend({initialize:function(t,i){We.prototype.initialize.call(this,this._boundsToLatLngs(t),i)},setBounds:function(t){return this.setLatLngs(this._boundsToLatLngs(t))},_boundsToLatLngs:function(t){return[(t=D(t)).getSouthWest(),t.getNorthWest(),t.getNorthEast(),t.getSouthEast()]}});vn.create=gn,vn.pointsToPath=Q,He.geometryToLayer=Fe,He.coordsToLatLng=Ve,He.coordsToLatLngs=qe,He.latLngToCoords=Ge,He.latLngsToCoords=Ke,He.getFeature=Ye,He.asFeature=Xe,$i.mergeOptions({boxZoom:!0});var wn=se.extend({initialize:function(t){this._map=t,this._container=t._container,this._pane=t._panes.overlayPane,this._resetStateTimeout=0,t.on("unload",this._destroy,this)},addHooks:function(){ki(this._container,"mousedown",this._onMouseDown,this)},removeHooks:function(){Ai(this._container,"mousedown",this._onMouseDown,this)},moved:function(){return this._moved},_destroy:function(){li(this._pane),delete this._pane},_resetState:function(){this._resetStateTimeout=0,this._moved=!1},_clearDeferredResetState:function(){0!==this._resetStateTimeout&&(clearTimeout(this._resetStateTimeout),this._resetStateTimeout=0)},_onMouseDown:function(t){if(!t.shiftKey||1!==t.which&&1!==t.button)return!1;this._clearDeferredResetState(),this._resetState(),Qt(),Ti(),this._startPoint=this._map.mouseEventToContainerPoint(t),ki(document,{contextmenu:Wi,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseMove:function(t){this._moved||(this._moved=!0,this._box=ui("div","leaflet-zoom-box",this._container),mi(this._container,"leaflet-crosshair"),this._map.fire("boxzoomstart")),this._point=this._map.mouseEventToContainerPoint(t);var i=new O(this._point,this._startPoint),e=i.getSize();Pi(this._box,i.min),this._box.style.width=e.x+"px",this._box.style.height=e.y+"px"},_finish:function(){this._moved&&(li(this._box),fi(this._container,"leaflet-crosshair")),ti(),zi(),Ai(document,{contextmenu:Wi,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseUp:function(t){if((1===t.which||1===t.button)&&(this._finish(),this._moved)){this._clearDeferredResetState(),this._resetStateTimeout=setTimeout(a(this._resetState,this),0);var i=new N(this._map.containerPointToLatLng(this._startPoint),this._map.containerPointToLatLng(this._point));this._map.fitBounds(i).fire("boxzoomend",{boxZoomBounds:i})}},_onKeyDown:function(t){27===t.keyCode&&this._finish()}});$i.addInitHook("addHandler","boxZoom",wn),$i.mergeOptions({doubleClickZoom:!0});var Pn=se.extend({addHooks:function(){this._map.on("dblclick",this._onDoubleClick,this)},removeHooks:function(){this._map.off("dblclick",this._onDoubleClick,this)},_onDoubleClick:function(t){var i=this._map,e=i.getZoom(),n=i.options.zoomDelta,o=t.originalEvent.shiftKey?e-n:e+n;"center"===i.options.doubleClickZoom?i.setZoom(o):i.setZoomAround(t.containerPoint,o)}});$i.addInitHook("addHandler","doubleClickZoom",Pn),$i.mergeOptions({dragging:!0,inertia:!rt,inertiaDeceleration:3400,inertiaMaxSpeed:1/0,easeLinearity:.2,worldCopyJump:!1,maxBoundsViscosity:0});var Ln=se.extend({addHooks:function(){if(!this._draggable){var t=this._map;this._draggable=new ce(t._mapPane,t._container),this._draggable.on({dragstart:this._onDragStart,drag:this._onDrag,dragend:this._onDragEnd},this),this._draggable.on("predrag",this._onPreDragLimit,this),t.options.worldCopyJump&&(this._draggable.on("predrag",this._onPreDragWrap,this),t.on("zoomend",this._onZoomEnd,this),t.whenReady(this._onZoomEnd,this))}mi(this._map._container,"leaflet-grab leaflet-touch-drag"),this._draggable.enable(),this._positions=[],this._times=[]},removeHooks:function(){fi(this._map._container,"leaflet-grab"),fi(this._map._container,"leaflet-touch-drag"),this._draggable.disable()},moved:function(){return this._draggable&&this._draggable._moved},moving:function(){return this._draggable&&this._draggable._moving},_onDragStart:function(){var t=this._map;if(t._stop(),this._map.options.maxBounds&&this._map.options.maxBoundsViscosity){var i=D(this._map.options.maxBounds);this._offsetLimit=R(this._map.latLngToContainerPoint(i.getNorthWest()).multiplyBy(-1),this._map.latLngToContainerPoint(i.getSouthEast()).multiplyBy(-1).add(this._map.getSize())),this._viscosity=Math.min(1,Math.max(0,this._map.options.maxBoundsViscosity))}else this._offsetLimit=null;t.fire("movestart").fire("dragstart"),t.options.inertia&&(this._positions=[],this._times=[])},_onDrag:function(t){if(this._map.options.inertia){var i=this._lastTime=+new Date,e=this._lastPos=this._draggable._absPos||this._draggable._newPos;this._positions.push(e),this._times.push(i),this._prunePositions(i)}this._map.fire("move",t).fire("drag",t)},_prunePositions:function(t){for(;1i.max.x&&(t.x=this._viscousLimit(t.x,i.max.x)),t.y>i.max.y&&(t.y=this._viscousLimit(t.y,i.max.y)),this._draggable._newPos=this._draggable._startPos.add(t)}},_onPreDragWrap:function(){var t=this._worldWidth,i=Math.round(t/2),e=this._initialWorldOffset,n=this._draggable._newPos.x,o=(n-i+e)%t+i-e,s=(n+i+e)%t-i-e,r=Math.abs(o+e)i.getMaxZoom()&&1

${}

}" value=""> ${}
`; // Funkcja wyszukująca markery na mapie function runSearchPickup() { if (typeof mymap !== 'undefined') { mymap.eachLayer(function (layer) { if (layer._icon !== undefined) { mymap.removeLayer(layer); } }); leafletGetTextLocation(); } document.querySelector('.asideContainer_pickup').innerHTML = ''; } // Funkcja obsługująca dostawy z mapą function createEventsInpost(ITEM_ID) { const ITEM_FOR_MAP = '#item_' + ITEM_ID; const oscItem = document.querySelector(ITEM_FOR_MAP).closest('.osc_item'); document.querySelector(ITEM_FOR_MAP).addEventListener('click', function (e) { const deliveryValue = ITEM_FOR_MAP.slice(1); // Weź adres klienta do mapy(zalogowany lub niezalogowany: zwykly lub dostawa na inny adres) const clientStreet = getAddressInfo("street"); const clientZipCode = getAddressInfo("zipcode"); const clientCity = getAddressInfo("city"); // Jesli nie ma informacji potrzebnej do mapy, zapisz wiadomosc do errora let errorMessage = ""; if(!clientStreet) errorMessage += addAddressErrorForMap("street"); if(!clientZipCode) errorMessage += addAddressErrorForMap("zipcode"); if(!clientCity) errorMessage += addAddressErrorForMap("city"); // Zablokuj wybranie mapy jak nie ma adresu if(errorMessage !== ""){ Alertek.show_alert(errorMessage); const scrolledToElement = document.getElementById("deliver_to_billingaddr").checked ? document.getElementById("delivery_firstname") : document.getElementById("client_firstname"); scrollToHeight(scrolledToElement); e.target.checked = false; checkPrevShipping(); return false; } app_shop.vars.courierId = ITEM_ID; // Customowe markery dla konkretnych dostawców newMarkerIcon = getMarkerIcon(ITEM_ID.split("-")[0]); if (oscItem.querySelector('.finpost_loading')) oscItem.querySelector('.finpost_loading').style.display = "block"; // Pokaż/Wstaw mapę if (finpostjs){ document.getElementById("fbs_z02_cover").style.display = "block"; disablePageScroll(); } else { document.querySelector('body').insertAdjacentHTML("beforeend",htmlContent); disablePageScroll(); // Naprawienie searchu w leaflet(stackuja sie wyniki bez tego) document.getElementById("autocomplete_location").addEventListener("keyup", (e) => { const suggestions = document.querySelector(".leafleat-suggestions"); if(!suggestions) return; else suggestions.remove(); }); } // Wstaw adres klienta const searchField = document.getElementById("autocomplete_location"); searchField.value = `${clientStreet} ${clientZipCode} ${clientCity}`; // Zamknij popup document.getElementById("fbs_z02_close").addEventListener('click', closeMap); document.getElementById("fbs_z02_cover").addEventListener('click', function (e) { if (e.target.closest('#fbs_z02_wrapper')) return; closeMap(); }); // Zmiana miejsca przycisku "szukaj na tym obszarze" na mobile if (window.innerWidth < 757) document.getElementById("pickup_list_form").insertAdjacentElement("beforebegin",document.querySelector('.map_button_search')); if (!oscItem.querySelector('.fselectedPoint')) oscItem.insertAdjacentHTML("beforeend",``); // Wyszukiwanie punktów odbioru na mapie if (finpostjs) { pickup_sites.courierId = ITEM_ID; runSearchPickup(); } if (!finpostjs) { finpostjs = true; pickup_sites.courierId = ITEM_ID; runSearchPickup(); document.querySelector('#locationField .btn').click(); // Wybranie punktu i wstawienie go koło dostawy document.querySelector('.asideContainer_pickup').addEventListener("change", (e) => { if(e.target.type !== "radio") return; const selectedPoint = document.querySelector('[name="shipping"]:checked').closest('.osc_item').querySelector('.fselectedPoint'); selectedPoint.innerHTML = ""; // Utworzenie informacji o punkcie odbioru const deliveryId = document.querySelector('[name="pickup_point"]:checked').value; const chosenPoint = document.querySelector(`.asideContainer_pickup label[data-id="${deliveryId}"]`); const pickupName = chosenPoint.querySelector(".headerText").innerHTML; const streetName = chosenPoint.querySelector(".streetText").innerHTML; const cityName = chosenPoint.querySelector(".cityText").innerHTML; const zipCodeName = chosenPoint.querySelector(".zipcodePickup").innerHTML.slice(0, chosenPoint.querySelector(".zipcodePickup").innerHTML.search(" { if(!e.target.classList.contains("fbs02_btn")) return; closeMap(); }); } changeCurrentShippingInfo(e.target); }); } deliveryPickupPoints.forEach(point => createEventsInpost(point)); } // Zamknięcie mapy function closeMap(){ document.getElementById("fbs_z02_cover").style.display = "none"; enablePageScroll(); } // Zdobądź wartość adresu, kodu pocztowego i miasta function getAddressInfo(query){ if(document.getElementById("deliver_to_billingaddr").checked){ if(document.getElementById(`delivery_${query}`).value.trim()) return document.getElementById(`delivery_${query}`).value; }; return document.getElementById(`client_${query}`).value; } // Wiadomość errora, gdyby niebyło informacji adresowych przy otwieraniu mapy const addressErrorMessagesForMap = { "street": `${}`, "zipcode": `${}`, "city": `${}`, } function addAddressErrorForMap(query){ addErrorMessage(document.getElementById(`client_${query}`), addressErrorMessagesForMap[query]); return `${addressErrorMessagesForMap[query]}
`; } // Utworzenie informacji o punkcie odbioru function createPickuppointInfo(selectedPoint, deliveryPointId, name, streetText, cityText, zipcodeText, courierId){ // Pokazanie elementu fselectedPoint selectedPoint.style.display = "block"; // Wstawienie danych w punkt odbioru selectedPoint.dataset.courierId = courierId; selectedPoint.dataset.deliveryPointId = deliveryPointId; selectedPoint.dataset.name = name; selectedPoint.dataset.street = streetText; selectedPoint.dataset.city = cityText; selectedPoint.dataset.zipcode = zipcodeText; // Wstawienie danych o punkcie odbioru selectedPoint.insertAdjacentHTML("beforeend", ` `); } // Zmiana widoku listy, mapy na mobilce function toggleMapList(e){ const ifList = e.target.dataset.show === "list"; e.target.innerHTML = ifList ? "Pokaż Mapę" : "Pokaż Listę"; // Schowaj/ Pokaż mapę i listę if(ifList){ document.querySelector(".map_button_search").classList.add("--hide-map-el"); document.getElementById("mymap").classList.add("--hide-map-el"); document.querySelector(".asideContainer_pickup").classList.remove("--hide-map-el"); }else{ document.querySelector(".map_button_search").classList.remove("--hide-map-el"); document.getElementById("mymap").classList.remove("--hide-map-el"); document.querySelector(".asideContainer_pickup").classList.add("--hide-map-el"); } e.target.dataset.show = ifList ? "map" : "list"; } ////////////////////////////////////////////////////////////////////////// // DANE KLIENTA document.getElementById("bm-oscop-section1").addEventListener("click", (e) => { // Pokazanie się okna od logowania if(e.target.classList.contains("get_signin")) showSigninModal(); // Sprawdzenie czy kliknięcie było na "Załóź konto w sklepie Opcjonalnie" if(e.target.id === "register_client_checkbox"){ const registerForm = document.querySelector(".register__form"); if(e.target.checked) registerForm.classList.add("--fade-in"); else registerForm.classList.remove("--fade-in"); return; } // Ukrycie/Pokazanie hasła if(e.target.id === "toggle-password") return togglePassword(e.target); // Sprawdzenie czy kliknięcie było na firmę, czy na osobę prywatną if(e.target.id === "client_type1") return document.querySelectorAll("#bm-oscop-section1 .firm-group").forEach(el => el.classList.add("--fade-in")); if(e.target.id === "client_type2") return document.querySelectorAll("#bm-oscop-section1 .firm-group").forEach(el => el.classList.remove("--fade-in")); // Sprawdzenie czy dostawa na inny adres czy nie if(e.target.id === "deliver_to_billingaddr"){ let ifBillingaddr = false; if(e.target.checked) ifBillingaddr = true; return showDeliveryForm(ifBillingaddr); } // Sprawdzenie czy kliknięcie będzie na guzik "Wybierz z listy adresów" i pokazanie popupa if(e.target.classList.contains("delivery__address-list-button")){ app_shop.fn.addressModal = new Modal({ element: $(".delivery__address-list-container"), classList: "--fade-in-modal", afterShow: () => { disablePageScroll(); document.querySelector(".delivery__address-list").addEventListener("click", handleClickAddressList); }, beforeClose: () => { enablePageScroll(); document.querySelector(".delivery__address-list").removeEventListener("click", handleClickAddressList); }, }); return; } // Kliknięcie na kod kierunkowy numeru telefonu if(e.target.closest(".phone_number__code")){ e.target.closest(".phone_number__code").querySelector(".phone_number__code_list").classList.toggle("show"); } if(e.target.classList.contains("phone_number__code_list_data")){ changePhoneValidationCountry(e.target); return; } }); // Pokaż/schowaj hasło function togglePassword(el){ const passwordInput = document.querySelector(".register__password"); let showPassword = false; if(passwordInput.type === "password") showPassword = true; passwordInput.type = showPassword ? "text" : "password"; el.classList.remove(showPassword ? "register__show-password" : "register__hide-password"); el.classList.add(showPassword ? "register__hide-password" : "register__show-password"); el.innerHTML = showPassword ? `${}` : `${}`; } // Pokaż popup logowania function showSigninModal(){ app_shop.fn.signinModal = new Modal({ element: $("#signin-form"), classList: "--fade-in-modal", afterShow: ()=>{ disablePageScroll(); document.querySelector(".signin-form__login").addEventListener("keydown", logInOnEnter); document.querySelector(".signin-form__pass").addEventListener("keydown", logInOnEnter); }, beforeClose: ()=>{ enablePageScroll(); document.querySelector(".signin-form__login").removeEventListener("keydown", logInOnEnter); document.querySelector(".signin-form__pass").removeEventListener("keydown", logInOnEnter); }, }); } // Pokaż(true)/Schowaj(false) formularz dostawy na inny adres function showDeliveryForm(style){ const deliveryWrapper = document.querySelector(".bm-oscop__container #client_new_additional .delivery_box.cn_wrapper"); if((style && deliveryWrapper.classList.contains("--more")) || (!style && !deliveryWrapper.classList.contains("--more"))) return; // Formularz dostawy na inny adres style ? deliveryWrapper.classList.add("--more") : deliveryWrapper.classList.remove("--more"); // Przycisk od wybierania z listy adresów listBtn = document.querySelector(".delivery__address-list-button"); if(listBtn) style ? listBtn.classList.add("--fade-in") : listBtn.classList.remove("--fade-in"); // Zmiana regionu jeśli region klienta różni się od regionu dostawy const deliveryRegion = document.getElementById("delivery_region").value; const clientRegion = document.getElementById("client_region").value; if(deliveryRegion !== clientRegion) changeRegion(); } // EventListener listy adresów function handleClickAddressList(e){ const addressLi = e.target.closest("li"); if(!addressLi) return; // Uzupełnienie informacji o formularzu const addressForm = document.querySelector(".delivery_box.cn_wrapper"); changeDeliveryValue("#delivery_firstname", addressLi.dataset.firstname); changeDeliveryValue("#delivery_lastname", addressLi.dataset.lastname); const firmName = addressForm.querySelector("#delivery_additional"); if(addressLi.dataset.additional) { firmName.value = addressLi.dataset.additional; firmName.classList.add("focused"); addSuccess(firmName); } else { firmName.value = ""; firmName.classList.remove("focused"); clearValidation(firmName); } changeDeliveryValue("#delivery_street", addressLi.dataset.street); changeDeliveryValue("#delivery_zipcode", addressLi.dataset.zipcode); changeDeliveryValue("#delivery_city", addressLi.dataset.city); // Sprawdzenie numeru Telefonu // Jeśli ma kod kierunkowy if(addressLi.dataset.phone.split(" ").length === 2 && addressLi.dataset.phone.split(" ")[0][0]){ const countryCode = addressLi.dataset.phone.split(" ")[0]; const phoneNumber = addressLi.dataset.phone.split(" ")[1]; // Wstawienie kodu kierunkowego i numeru telefonu const currCountry = countryPhoneData.find(phoneData => phoneData.country_code === countryCode.slice(1)); setPhoneCountryNumber(document.getElementById("delivery_phone").closest(".--phone"), currCountry.country_code, currCountry.alpha2) changeDeliveryValue("#delivery_phone", phoneNumber); }else{//Jeśli nie ma kod kierunkowy changeDeliveryValue("#delivery_phone", addressLi.dataset.phone); } validatePhone(document.getElementById("delivery_phone")); // Zmień państwo i przeładuj metody płatności jeśli jest inny const deliveryRegion = addressForm.querySelector("#delivery_region"); if(deliveryRegion.value !== addressLi.dataset.region_id) { addressForm.querySelector("#delivery_region").value = addressLi.dataset.region_id; changeRegion(); } // Nadanie klasy aktywnemu adresowi e.target.closest("ul").querySelectorAll("li").forEach(el => el.classList.remove("--active-address")); addressLi.classList.add("--active-address"); // Zamkniencie modala setTimeout(() => app_shop.fn.addressModal.closeModal(),100) } // Zmień wartości pól input delivery function changeDeliveryValue(selector, newValue){ const selectedInput = document.querySelector(selector); selectedInput.value = newValue; addSuccess(selectedInput); selectedInput.classList.add("focused") } // OBSŁUGA LOGOWANIA const SIGNIN = (signinInput) => JSON.stringify({ query: `mutation { login(${signinInput}) { status } }`, }); function logInOnEnter(e){ if(e.key === "Enter") logInToAccount(false) } const signinForm = document.querySelector(".signin-form__container form"); if(signinForm) signinForm.addEventListener("submit", logInToAccount); async function logInToAccount(event){ if(event) event.preventDefault(); const login = document.querySelector(".signin-form__login").value; const password = document.querySelector(".signin-form__pass").value; app_shop.fn.ajaxLoadSite(1); const loginStatus = await fetchData({ data: SIGNIN(` login: "${login.replace(/"/g, '\\"')}", password: "${password.replace(/"/g, '\\"')}", `), linkParameter: '?mutation=signin', alert: false, }); app_shop.fn.ajaxLoadSite(0); if (loginStatus.errors) { Alertek.show_alert(`${}`); return; } app_shop.fn.signinModal.closeModal(); getClientNew(); if(document.querySelector(".order2_terms_wrapper_sub.email")) document.querySelector(".order2_terms_wrapper_sub.email").remove(); if(document.querySelector(".order2_terms_wrapper_sub.sms")) document.querySelector(".order2_terms_wrapper_sub.sms").remove(); } // Zalogowanie/inicjacja użytkownika function getClientNew(){ // Przygotowanie jesli użytkownik nie jest zalogowany if(!document.querySelector(".--logged")) document.getElementById("client_form").remove(); document.querySelector(".step1_sub").insertAdjacentHTML("beforeend",''); app_shop.fn.load( "place-order.php", [["#bm-oscop-section1", "#bm-oscop-section1"]], function () { history.go(-1); }, "?set_render=content" ).then(() => { changeRegion(); // Ustaw numer kraju przy telefonie setPhoneCountryNumberAtStart("client"); setPhoneCountryNumberAtStart("delivery"); }) }; function createPhoneCodeList(){ const phoneCodeListEl = document.querySelectorAll(".phone_number__code_list"); let phoneCodeMarkup = ""; countryPhoneData.forEach(phoneData =>{ phoneCodeMarkup += `
  • ${phoneData.alpha2}(+${phoneData.country_code})
  • `; }); phoneCodeListEl.forEach(codeEl => codeEl.innerHTML = phoneCodeMarkup); } function setPhoneCountryNumberAtStart(deliveryType){ const phoneEl = document.getElementById(`${deliveryType}_phone`) const phoneContainerEl = phoneEl.closest(".--phone"); // NIEZALOGOWANY if(!phoneEl.value){ const currCountry = countryPhoneData.find(el=> el.alpha2.toLowerCase() === app_shop.vars.language.symbol.toLowerCase()); setPhoneCountryNumber(phoneContainerEl, currCountry.country_code, currCountry.alpha2); // JEŚLI klient zalogowany i ma w numerze numer kierunkowy }else if(phoneEl.value && phoneEl.value.split(" ").length === 2 && phoneEl.value.split(" ")[0][0] === "+" ){ const countryCode = phoneEl.value.split(" ")[0]; const phoneNumber = phoneEl.value.split(" ")[1]; // Zmiana numeru telefonu phoneEl.value = phoneNumber; // Zmiana kodu kierunkowego państwa const currCountry = countryPhoneData.find(phoneData => phoneData.country_code === countryCode.slice(1)); setPhoneCountryNumber(phoneContainerEl, currCountry.country_code, currCountry.alpha2); // phoneContainerEl.querySelector(".phone_number__code_alpha2").innerHTML = currCountry.alpha2; // phoneContainerEl.querySelector(".phone_number__code_text").innerHTML = currCountry.country_code; // phoneContainerEl.querySelector(".phone_number__code_number").value = currCountry.country_code; // JEŚLI KLIENT zalogowany i brak kodu kierunkowego w numerze }else{ // Sprawdź najpierw dla języka sklepu const currCountry = countryPhoneData.find(el=> el.alpha2.toLowerCase() === app_shop.vars.language.symbol.toLowerCase()); // if(validatePhoneWithoutError(phoneEl, currCountry)) return setPhoneCountryNumber(phoneContainerEl, currCountry.country_code, currCountry.alpha2); // // Sprawdź dla każdego języka po kolei // let stopPhoneDataLooping = false; // countryPhoneData.forEach(phoneData => { // if(stopPhoneDataLooping) return; // if(validatePhoneWithoutError(phoneEl, phoneData)){ // setPhoneCountryNumber(phoneContainerEl, phoneData.country_code, phoneData.alpha2); // stopPhoneDataLooping = true; // } // }); // if(stopPhoneDataLooping) return; // Ustawienie numeru kierunkowego telefonu zgodnie z jezykiem strony setPhoneCountryNumber(phoneContainerEl, currCountry.country_code, currCountry.alpha2); validatePhone(phoneEl); } } function changePhoneValidationCountry(element){ const phoneContainerEl = element.closest(".--phone"); setPhoneCountryNumber(phoneContainerEl, element.dataset.code, element.dataset.alpha2); validatePhone(phoneContainerEl.querySelector("input.form-control.validate.f-control")); } function setPhoneCountryNumber(phoneEl, phoneCode, phoneAlpha2){ const phoneNumberEl = phoneEl.querySelector(".phone_number__code_number"); const phoneTextEl = phoneEl.querySelector(".phone_number__code_text"); const phoneAlpha2El = phoneEl.querySelector(".phone_number__code_alpha2"); phoneNumberEl.value = phoneCode; phoneTextEl.innerHTML = phoneCode; phoneAlpha2El.innerHTML = phoneAlpha2; } // Walidacja numeru telefonu dla ustalenia numeru kierunkowego function validatePhoneWithoutError(phoneEL, phoneValidationInfo){ const chosenCountry = phoneEL.closest(".--phone").querySelector(".phone_number__code_number").value; const phoneNumber = phoneEL.value.replaceAll(" ",""); let phoneNoError = false; phoneValidationInfo.mobile_begin_with.forEach((el, index)=>{ if(phoneNumber.toString().startsWith(el) && phoneValidationInfo.phone_number_lengths.includes(phoneNumber.length)) phoneNoError = true; }); if(!phoneNoError){ return false; } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////// // WALIDACJA // Wyczyść klasy walidacji function clearValidation(input){ const wrapper = input.closest(".has-feedback") wrapper.classList.remove('--success', '--error', 'has-error', 'has-success'); }; // Wyczyść wiadomość błędu function removeErrorMessage(input) { const valMessage = input.closest('.has-feedback').querySelector('.validate_message'); if(valMessage) valMessage.remove(); }; // Dodaj klasy błędu function addError(input){ clearValidation(input); removeErrorMessage(input); const wrapper = input.closest(".has-feedback"); clearValidation(wrapper); wrapper.classList.add('--error', 'has-error'); }; // Dodaj klasy sukcesu function addSuccess(input){ clearValidation(input); removeErrorMessage(input); const wrapper = input.closest(".has-feedback"); clearValidation(wrapper); wrapper.classList.add('--success', 'has-success'); }; // Dodaj error wraz z wiadomością function addErrorMessage(input, message){ addError(input); input.closest('.has-feedback').insertAdjacentHTML("beforeend",`${message}.`); } // Waliduj elementy wymagające wysłania requesta (zipcode, nip) async function validateRequest(target, order=false){ const wrapper = target.closest(".has-feedback"); let reqData = `${target.name}=${target.value}`; if(target.dataset.serialize) { const serializeEl = document.querySelector(target.dataset.serialize); reqData += '&' + `${serializeEl.name}=${encodeURIComponent(serializeEl.value)}`; } if(target.dataset.revalidate) { target.dataset.revalidate.split(",").forEach(elQuery => { validateRequest(document.querySelector(elQuery)); }) } if(target.value === '') { addErrorMessage(target, ); return false; } const resData = await $.ajax({ url: '/ajax/client-new.php?validAjax=true', type: 'POST', timeout: 16000, dataType: 'JSON', data: reqData, }); if(resData.errno) { let error_message = ''; if (resData.message.error_code) { if (resData.message.zipcode_pattern && (resData.message.error_code === 'incorect_zipcode' || resData.message.error_code === 'incorect_delivery_zipcode')) { error_message = clientNewErrorCode[resData.message.error_code] + ' ' + `${}]:` + ' '; error_message += resData.message.zipcode_pattern.join(', '); } else if (clientNewErrorCode[resData.message.error_code]) error_message = clientNewErrorCode[resData.message.error_code]; } addError(target); if (error_message) addErrorMessage(target, error_message); return false }else{ addSuccess(target); if (target.name==="client_email" && !order) { $.ajax({ url: '/ajax/client-new.php?checkClientExists=true', type: 'POST', timeout: 16000, dataType: 'JSON', data: {'client_mail': target.value}, }).then(function succesFn(resData) { if(resData.client_exists === true || resData.login) showEmailPopup(resData); }); } return true; } }; // Pokaż popup jeśli użytkownik wpisał email który posiada już konto function showEmailPopup(resData){ app_shop.fn.emailModal = new Modal({ html: `
    ${} ${}:
    ${resData.mail}

    ${}

    `, classList: "--fade-in-modal", afterShow: disablePageScroll, beforeClose: enablePageScroll, }); return; } function handleShowSigninModalFromEmailModal(e){ e.preventDefault(); app_shop.fn.emailModal.closeModal(); showSigninModal(); } // EventListener zmian w kontenerze bm-oscop-section1 document.getElementById("bm-oscop-section1").addEventListener("input", (e) => { clearTimeout(this.formChangeTimeoutFn); this.formChangeTimeoutFn = setTimeout(()=>{ const validateRequestId = ["client_zipcode", "delivery_zipcode", "client_nip", "client_email"]; const notEmptyFieldsId = ["client_firstname", "client_lastname", "client_city", "delivery_firstname", "delivery_lastname", "delivery_city", "client_firm"]; // Walidacja zipcode, nipu i emaila if(validateRequestId.includes(e.target.id)) return validateRequest(e.target); // Zmiana regionu if(e.target.name === "client_region" || e.target.name === "delivery_region") { const clientType = e.target.name.split("_")[0]; validateRequest(document.getElementById(`${clientType}_zipcode`)); if(clientType === "client" && document.getElementById("client_type1").checked === true) validateRequest(document.getElementById("client_nip")); changeRegion(); return; } // Walidacja ulicy i numeru domu if(e.target.id === "client_street" || e.target.id === "delivery_street") validateStreet(e.target); // Walidacja numeru telefonu if(e.target.id === "client_phone" || e.target.id === "delivery_phone") validatePhone(e.target); // Walidacja loginu i hasła rejestracji if(e.target.classList.contains("register__login")) testLogin(); if(e.target.classList.contains("register__password")) testPassword(); // Walidacja imienia nazwiska miasta i firmy(wymagające po prostu nie bycia pustym) if(notEmptyFieldsId.includes(e.target.id)) validateNotEmpty(e.target); // Sprawdzenie czy firma w dostawie na inny adres została wpisana if(e.target.id === "delivery_additional"){ if(e.target.value.length > 0) addSuccess(e.target); else clearValidation(e.target); }; }, 300) }); // Funkcje walidacji poszczególnych elementów function validateStreet(streetEl){ const streetParts = streetEl.value.split(" "); const addressNumber = Number(streetParts[streetParts.length-1][0]); if(streetEl.value.length === 0 || (streetEl.value.length > 0 && (!addressNumber || streetParts.length < 2))){ addErrorMessage(streetEl, ); return false; }else{ addSuccess(streetEl); return true; } } ////////////////////////////////////////////////////////////////// function validatePhone(phoneEL){ const chosenCountry = phoneEL.closest(".--phone").querySelector(".phone_number__code_number").value; const phoneValidationInfo = countryPhoneData.find(phoneData=>+phoneData.country_code === +chosenCountry); const phoneNumber = phoneEL.value.replaceAll(" ",""); // Sprawdzenie czy cos jest wpisane if(phoneNumber.length===0 || !Number(phoneNumber)){ addErrorMessage(phoneEL, ); return false; }else{ let phoneError = false; let phoneErrorMessage = ""; // Sprawdzenie czy numer telefonu zaczyna sie odpowiednia liczba phoneBeginWithErrorNumbers = ""; phoneBeginWithError = true; phoneValidationInfo.mobile_begin_with.forEach((el, index)=>{ if(phoneNumber.toString().startsWith(el)) phoneBeginWithError = false; phoneBeginWithErrorNumbers += phoneValidationInfo.mobile_begin_with.length === 1 ? el : phoneValidationInfo.mobile_begin_with.length - 1 === index ? `${} ${el}` : `${el}, ` }); if(phoneBeginWithError){ phoneError = true; phoneErrorMessage += `${} ${phoneBeginWithErrorNumbers}`; } // Sprawdzenie czy numer telefonu sklada sie z odpowiedniej ilosci cyfr if(!phoneValidationInfo.phone_number_lengths.includes(phoneNumber.length)){ phoneLengthErrorNumbers = ""; phoneValidationInfo.phone_number_lengths.forEach((el, index)=>{ phoneLengthErrorNumbers += phoneValidationInfo.phone_number_lengths.length === 1 ? el : phoneValidationInfo.phone_number_lengths.length - 1 === index ? `${} ${el}` : `${el}, `; }); if(phoneError === true){ phoneErrorMessage += ` ${} ${} ${phoneLengthErrorNumbers} ${}`; }else{ phoneErrorMessage += `${} ${phoneLengthErrorNumbers} ${}`; phoneError = true; } } if(phoneError){ addErrorMessage(phoneEL, phoneErrorMessage); return false; } } addSuccess(phoneEL); return true; } ////////////////////////////////////////////////////////////////// function validateNotEmpty(checkEl){ if(checkEl.value.length < 1) { addErrorMessage(checkEl, ); return false; } else{ addSuccess(checkEl); return true; } } // Sprawdzenie loginu i hasla function testLogin(){ const login = document.querySelector(".register__login"); if(login.value.trim().length < 1){ addErrorMessage(login, ); return false; } else if(!/^[A-Za-z0-9@._-]*$/.test(login.value.trim()) || Number(login.value.trim()) || login.value.trim().length<3){ addErrorMessage(login, ); return false; }else{ addSuccess(login); return true; } } function testPassword(){ const repeatPassword = document.getElementById("repeat_password"); const password = document.querySelector(".register__password"); repeatPassword.value = password.value; if(password.value.trim().length < 1){ addError(password); password.closest('.has-feedback').insertAdjacentHTML("beforeend", `${}.`); return false; } if(password.value.trim().length < 6){ addError(password); password.closest('.has-feedback').insertAdjacentHTML("beforeend", `${}.`); return false; }else{ addSuccess(password); return true; } } // Obsługa przesuwających się labelek document.querySelector("body").addEventListener("change", (e) => { if(e.target.classList.contains("f-control")){ if(e.target.value.length > 0) e.target.classList.add("focused"); else e.target.classList.remove("focused"); } }) ////////////////////////////////////////////////////////////////////// // DOSTAWA I PŁATNOSĆI const SET_REGION = (setRegionInput) => JSON.stringify({ query: `mutation { setRegion(${setRegionInput}) { status error { code message } } }`, }); // Zmiana regionu dostawy async function changeRegion(payAndDelData = null) { console.log("fn: changeRegion()") // Pobranie informacji o regionie z formularza const clientRegion = document.getElementById("client_region").value; const deliveryRegion = document.getElementById("deliver_to_billingaddr").checked ? document.getElementById("delivery_region").value : clientRegion; // Zmiana regionu const regionStatus = await this.fetchData({ data: SET_REGION(`SetRegionInput: { billingRegionId: ${clientRegion}, deliveryRegionId: ${deliveryRegion}, areForced: true }`), linkParameter: '?mutation=setRegion', }); const { status } = regionStatus?.data?.setRegion || {}; if (status !== 'success') return alert(); // Waliduj numery telefonu dla kraju if(!firstTimeLoadPage){ validatePhone(document.getElementById("client_phone")); validatePhone(document.getElementById("delivery_phone")); } // Pobranie nowych metod płatności i dostaw getNewPaymentsAndDeliveries(payAndDelData); }; const PAYMENTS_AND_DELIVERY_METHODS = () => JSON.stringify({ query: `query{ paymentsMethod { payments { id name icon methodAsGroup paymentChannel { id name icon } paymentSystem { id name } additionalClientCost { costPercent costFixedAmount { value } minAmount { value } } terms { supportsPaymentInitiationService paymentInitiationServiceTerms { id type clause } } } paymentsGroup { id name icon } paymentsGroupTerms { groupId type clausePrefix clause } settings { defaultPaymentMethodId } } shipping(ShippingInput: { mode: basket }) { settings { checked orderDivisionEnabled } shipping { availability calendar calendarOption comment prepaid minworthReached workingDays pointsSelected pointsEnabled pointsCost { value formatted } minworth { formatted } courier { id fullId icon name pickupPoint companyKey companyGroupKey } cost { value formatted } deliveryTime { time { days } weekDay weekAmount today } } shippingTime { shippingTime { time { days hours minutes } workingDays weekDay weekAmount today } unknownTime } shippingTimeLater { shippingTime { time { days hours minutes } workingDays weekDay weekAmount today } unknownTime } nonStandardizedInfo { active isAllowed courierId } } }`, }); // Załadowanie metod dostaw i płatności async function getNewPaymentsAndDeliveries(data = null) { // Wyczyszczenie zapisanych poprzednich metod płatności prevPayment = undefined; prevShipping = undefined; // Wyczyszczenie punktow odbioru deliveryPickupPoints.length = 0; app_shop.fn.ajaxLoadSite(1); // Dane do uzupełnienia przy edycji let paymentValue, deliveryId; if(data){ paymentValue = data.paymentMethodId; deliveryId = `item_${data.deliveryMethodId}-${paymentValue === "cash" ? "0" : "1"}`; } const paymentsAndDeliveryData = await fetchData({data: PAYMENTS_AND_DELIVERY_METHODS()}); // error gdyby nie było produktów if(paymentsAndDeliveryData.errors){ paymentsAndDeliveryError(paymentsAndDeliveryData.errors); } // Dane do zaznaczenia płatności i dostawy jeśli wcześniej na tej przeglądarce(localStorage) było już zamówienie const prevOrderInfo = JSON.parse(localStorage.getItem("prevOrderInfo")); // dostawy za pobraniem let dvpMarkup = ""; // dostawy za przedłatą let prepaidMarkup = ""; let dvpPaymentMethod = false; //Pobranie startowych form dostaw/płatności jeśli nie ma let startingPaymentMethod; if(!deliveryId && paymentsAndDeliveryData?.data?.shipping?.settings?.checked){ deliveryId = `item_${paymentsAndDeliveryData.data.shipping.settings.checked}`; startingPaymentMethod = paymentsAndDeliveryData.data.shipping.settings.checked.split("-")[1] } // DOSTAWY if(paymentsAndDeliveryData.data.shipping.shipping){ paymentsAndDeliveryData.data.shipping.shipping.forEach(deliveryMethod=>{ if(deliveryMethod.prepaid === "dvp"){ dvpMarkup += prepareDeliveryMarkup(deliveryMethod, deliveryId); dvpPaymentMethod = true; }else{ prepaidMarkup += prepareDeliveryMarkup(deliveryMethod, deliveryId); } }); }else{ prepaidMarkup += `"; // PŁATNOŚĆ ZA POBRANIEM if(dvpPaymentMethod) prepaidsMethodMarkup += `
    ${<iai:variable vid=}">
    ${}
    `; // Wstawienie metod płatności na stronę const previousPayments = document.getElementById("osc_prepaids_method"); if(previousPayments) previousPayments.remove(); document.getElementById("bm-oscop-payments").insertAdjacentHTML("beforeend", `
    ${ifPaymentTransfer ? prepaidsTransferMarkup : ""}${ifPaymentCard ? prepaidsCardMarkup : ""}${prepaidsMethodMarkup}
    `); // Przygotowanie informacji o dostawie do obliczenia daty dostawy const deliveryDateInfo = {deliveryVal: null, delivery: null, pickuppoint: null}; const firstInput = document.querySelector("#osc_order1 input"); if(firstInput) changeDeliveryInfoObject(deliveryDateInfo, firstInput); // Wstawienie pickuppoint jeśli edycja i istnieje if(data?.pickupData !== undefined && data?.pickupData !== null){ const selectedShipping = document.querySelector(`#bm-oscop-section2 input#${deliveryId}`); const pointExists = await checkPrevPickupPoint( selectedShipping.parentElement.querySelector(".fselectedPoint"), data.pickupData.id, data.pickupData.name, `${data.pickupData.address.street} ${data.pickupData.address.buildingAndHouseNumber}`, data.pickupData.address.city, data.pickupData.address.postcode, data.deliveryMethodId ) // Odznaczenie punktu jeśli punkt odbioru nie istnieje(Wcześniej był zaznaczony przy edycji) if(!pointExists) selectedShipping.checked = false; else changeDeliveryInfoObject(deliveryDateInfo, selectedShipping); }// Sprawdzenie czy użytkownik ma zapisane poprzednio użyte metody w przeglądarce(tylko przy pierwszym załadowaniu strony) else if(firstTimeLoadPage && prevOrderInfo && prevOrderInfo?.prevCountry === document.getElementById("client_region").value){ // POPRZEDNIA PŁATNOSC const prevPaymentMethod = prevOrderInfo.prevPaymentMethod; // Zaznaczenie metod płatności które nie tworzą popupa if(prevPaymentMethod.id !== "payitem_2" && prevPaymentMethod.group !== "card" && prevPaymentMethod.group !== "transfer"){ document.getElementById(prevPaymentMethod.id).click(); } else if(prevPaymentMethod.group === "card" || prevPaymentMethod.group === "transfer"){ const paymentMethodId = prevPaymentMethod.id.replace("-clone", ""); cloneElement(document.getElementById(paymentMethodId)); } // POPRZEDNIA DOSTAWA const prevDeliveryMethod = prevOrderInfo.prevDeliveryMethod; const prevDeliveryInput = document.querySelector(`input#${prevDeliveryMethod.id}`); // Sprawdzenie czy istnieje metoda dostawy (na wypadek gdyby była usunięta lub klient zamawiał do innego kraju) if(prevDeliveryInput){ // Sprawdzenie czy dostawa miała punkt odbioru if(prevDeliveryMethod.fselectedPoint){ const pointExists = await checkPrevPickupPoint( prevDeliveryInput.parentElement.querySelector(".fselectedPoint"), prevDeliveryMethod.fselectedPoint.deliveryPointId, prevDeliveryMethod.fselectedPoint.name, prevDeliveryMethod.fselectedPoint.street, prevDeliveryMethod.fselectedPoint.city, prevDeliveryMethod.fselectedPoint.zipcode, prevDeliveryMethod.fselectedPoint.courierId ) if(pointExists) prevDeliveryInput.checked = true; }else{ prevDeliveryInput.checked = true; } changeDeliveryInfoObject(deliveryDateInfo, prevDeliveryInput); } } // Zaznaczenie karty/banku w przypadku edycji const checkedPayment = document.querySelector(`#osc_prepaids_method input[name="payform_id"]:checked`) if(paymentValue && checkedPayment && (checkedPayment.dataset.group === "card" || checkedPayment.dataset.group === "transfer")){ cloneElement(checkedPayment); } // Przeładowanie mapy loadMap(); // Zmiana daty dostawy i pokazanych opcji dostawy if(deliveryDateInfo.deliveryVal && deliveryDateInfo.delivery && deliveryDateInfo.pickuppoint) calculateDeliveryDate(deliveryDateInfo.deliveryVal, deliveryDateInfo.delivery, deliveryDateInfo.pickuppoint); // Przeliczenie kosztu dostawy calculateBasketCost(); app_shop.fn.ajaxLoadSite(0); firstTimeLoadPage = false; // Wstawienie kalendarza do wyboru dnia dostawy document.querySelectorAll(".osc_item.--calendar").forEach(el=>{ const calendarContainer = el.querySelector(".delivery_date__calendar_container"); // Miejsce na święta const holidays = []; // Przerobienie wolnych dni z tekstu na tablicę liczb; const workingDaysArr = el.dataset.workingDays.split(",").map(day=>Number(day)); // Wyliczenie ostatniego dnia na dostawę na 2 miesiące od pierwszego dostępnego dnia const maxDeliveryDate = new Date(el.dataset.deliveryDate); maxDeliveryDate.setMonth(maxDeliveryDate.getMonth() + 2); // KALENDARZ const vanillaCal = new VanillaCalendar(el.querySelector(".delivery_date__calendar_container"), { date: { min: el.dataset.deliveryDate, max: maxDeliveryDate.toLocaleDateString('en-CA'), today: new Date(el.dataset.deliveryDate.replace(/-/g, '/')), }, settings: { workingDays: workingDaysArr, selected: { dates: [el.dataset.deliveryDate], holidays: holidays, }, }, actions: { clickDay: (e, dates) => { e.stopPropagation(); const customDateContainer = el.querySelector(".delivery_date__calendar_option.--custom"); //Zmiana aktywnej daty el.querySelector(".delivery_date__calendar_option.active").classList.remove("active"); el.querySelector(".delivery_date__calendar_option.--another").classList.remove("--open"); customDateContainer.classList.add("active"); const chosenDate = new Date(dates[0]); if(el.querySelector(`.delivery_date__calendar_option[data-date='${chosenDate.toLocaleDateString('en-CA')}']`)){ // Wybranie istniejącej daty el.querySelector(`.delivery_date__calendar_option[data-date='${chosenDate.toLocaleDateString('en-CA')}']`).click(); }else{ // Wybranie nieistniejącej daty // uzupełnienie danych o dacie dostawy customDateContainer.querySelector(".delivery_date__calendar_date").innerHTML = `${chosenDate.getDate()}`; customDateContainer.querySelector(".delivery_date__calendar_month").innerHTML = `${app_shop.txt[`month_name${chosenDate.getMonth()+1}`]}`; customDateContainer.querySelector(".delivery_date__calendar_day").innerHTML = `${app_shop.txt[`week_day${chosenDate.getDay()}`]}`; //ustawienie daty customDateContainer.dataset.date = chosenDate.toLocaleDateString('en-CA'); } }, } }); vanillaCal.init(); // date: { // min: firstDate, // today: new Date(firstDate.replace(/-/g, '/')), // }, // settings: { // workingDays, // selected: { // dates: [firstDate], // holidays: formattedHolidays, // }, // }, // actions: { // clickDay: (e, dates) => this.calendarAfterSelectDate(e, dates), // }, }) }; // Error po pobraniu metod płatności i dostaw function paymentsAndDeliveryError(errors){ const notEnoughProduct = errors.find(el => el.message.split(" ")[0] === "order_notenough"); if(notEnoughProduct){ Alertek.Error(`${}`); return setTimeout(()=>{ window.location = "basketedit.php" }, 3000) } const wholeSalerError = errors.find((error) => error?.code === 109); if(wholeSalerError){ Alertek.Error(`${}.`); return setTimeout(()=>{ window.location = "basketedit.php" }, 3000) } Alertek.Error(); } // Stworzenie kontenera na "przelewy online" lub "karta platnicza" function createPaymentContainerMarkup(method){ const operationName = method === "transfer" ? : ; const methodName = method === "transfer" ? "banków" : "kart płatniczych"; return `
    ${operationName}
    ${operationName}

    Lista ${methodName}

    Wybierz z ${methodName}
    `; } app_shop.txt.week_day0 = ; app_shop.txt.week_day1 = ; app_shop.txt.week_day2 = ; app_shop.txt.week_day3 = ; app_shop.txt.week_day4 = ; app_shop.txt.week_day5 = ; app_shop.txt.week_day6 = ; app_shop.txt.week_day7 = ; app_shop.txt.week_day8 = ; app_shop.txt.month_name1 = ; app_shop.txt.month_name2 = ; app_shop.txt.month_name3 = ; app_shop.txt.month_name4 = ; app_shop.txt.month_name5 = ; app_shop.txt.month_name6 = ; app_shop.txt.month_name7 = ; app_shop.txt.month_name8 = ; app_shop.txt.month_name9 = ; app_shop.txt.month_name10 = ; app_shop.txt.month_name11 = ; app_shop.txt.month_name12 = ; // Przygotowanie html dla metod dostaw function prepareDeliveryMarkup(method, deliveryId){ // Zapisanie do listy dostaw z mapą if ((method.courier.pickupPoint === true || method.courier.id === 0) && !deliveryPickupPoints.includes(method.courier.fullId)) deliveryPickupPoints.push(method.courier.fullId); const cost = Number(method.cost.value) === 0 ? : method.cost.formatted; const disabled = method.minworthReached === false ? 'disabled="disabled"' : ""; const avaliableFrom = disabled ? '' + `${}: ` + method.minworth.formatted + "" : ""; const ifChecked = deliveryId === `item_${method.courier.fullId}`; // Obliczenie daty dostawy let date = new Date(); date.setDate(date.getDate() + method.deliveryTime.time.days); const deliveryDate = date.toLocaleDateString("pl-PL"); let defaultDate = date.toLocaleDateString('en-CA'); // Opcje wyboru daty i godzuny dostawy let shippingCalendarAndHours = ""; if(method.calendar && method.calendarOption.includes("days") && method.workingDays.length > 0 && method.courier.id !== 0){ // Zmienne odpowiadające za ograniczenie ilości dat wysyłki const dateSelectionArr = []; let dateSelectionDistance = 0; //Wstawienie 7 najwcześniejszych dat while(dateSelectionArr.length < 7){ const newDeliveryDate = new Date(date) newDeliveryDate.setDate(newDeliveryDate.getDate() + dateSelectionDistance); if(method.workingDays.includes(newDeliveryDate.getDay())){ // Ustawienie pierwszej daty jako aktywną if(dateSelectionArr.length === 0) defaultDate = newDeliveryDate.toLocaleDateString('en-CA'); // Przygotowanie kodu HTML dateSelectionArr.push(`
  • ${newDeliveryDate.getDate()} ${app_shop.txt[`month_name${newDeliveryDate.getMonth()+1}`]} (${app_shop.txt[`week_day${newDeliveryDate.getDay()}`]})
  • `); } dateSelectionDistance++; } const optionMarkup = dateSelectionArr.join(""); // Przygotowanie HTML kalendarza i wyboru czasu dostawy shippingCalendarAndHours += `
      ${optionMarkup}
    • ${}
    ${ method.calendarOption === "days_and_hours" ? `
    ${}:
    ` : "" }
    ` } // Uzupełnienie markupa dla metod dostaw dvp return `
    0 && method.courier.id !== 0 ? "--calendar" : ""}" for="item_${method.courier.fullId}" data-working-days="${method.workingDays.toString()}" data-delivery-date="${defaultDate}">
    ${method.courier.name}
    ${method.courier.name} ${avaliableFrom}
    ? `cost_free` :""}">${cost}
    ${}: ${app_shop.txt[`week_day${parseInt(method.deliveryTime.weekDay)}`]} ${deliveryDate}
    ${method.courier.pickupPoint === true ? `` : ""} ${shippingCalendarAndHours}
    `; } // Sprawdź czy poprzedni punkt odbioru dalej istnieje const SEARCH_PICKUP_POINTS_QUERY = (searchPickupPointsInput) => JSON.stringify({ query: `query { searchPickupPoints(${searchPickupPointsInput}) { data gps { latitude longitude } } }`, }) async function checkPrevPickupPoint(selectedPoint, deliveryPointId, name, street, city, zipcode, courierId){ if(!name || !city || !zipcode) return false; // Pobranie punktów z tym samym id co poprzedni app_shop.fn.ajaxLoadSite(1) const resultData = await fetchData({ data: SEARCH_PICKUP_POINTS_QUERY(` SearchPickupPointsInput: { shippingId: ${courierId}, query: "${deliveryPointId}", cashOnDelivery: false, } `), linkParameter: "?query=searchPickupPoints", }); app_shop.fn.ajaxLoadSite(0); if(resultData?.error?.message) return false; // Sprawdzenie czy poprzedni punkt dalej istnieje let pointExists = false; resultData.data.searchPickupPoints.forEach(point => { if(point.data.includes(deliveryPointId)) pointExists = true; }) // Utworzenie nowego punktu odbioru if(pointExists) createPickuppointInfo(selectedPoint, deliveryPointId, name, street, city, zipcode, courierId); return pointExists; } // Obsługa kliknięć na dostawy i metody płatności let prevPayment; let prevShipping; function checkPrevShipping(){ if(prevShipping){ prevShipping.checked=true; changeCurrentShippingInfo(prevShipping); } } // Przeliczenie kosztu i czasu dostawy i zapisanie nowej metody dostawy function changeCurrentShippingInfo(shippingMethod){ calculateBasketCost(); calculateDeliveryDate(shippingMethod.value, shippingMethod.dataset.delivery, shippingMethod.dataset.pickuppoint); app_shop.vars.checkedShipping = shippingMethod.value; } document.getElementById("bm-oscop-section2").addEventListener("click", e => { // zabezpieczenie przed kliknięciem w kalendarz + wywołanie kliknięcia na input if(e.target.closest(".osc_item") && !e.target.closest(".delivery_date__options") && e.target.type !== "radio") return e.target.closest(".osc_item").querySelector(":scope > input").click(); // Kliknięcie na datę if(e.target.closest(".delivery_date__calendar_option")) return handleChangeDeliveryDate(e.target.closest(".delivery_date__calendar_option")); // Kliknięcie na dostawe if(e.target.name === "shipping"){ // Wyczyszczenie wszystkich zaznaczonych punktów odbioru clearSelectedPoints(); // Nie robienie niczego jeśli kliknąłeś na ten sam element if(app_shop.vars.checkedShipping === e.target.value) return; if(e.target.dataset.working_days) e.target.dataset.working_days.split("#").map(function (e) {return parseInt(e, 10);}); // Zapisanie jako poprzednia metoda płatności jeśli nie wymaga wyboru punktu odbioru if(e.target.dataset.pickuppoint === "false"){ prevShipping=e.target; // Przeliczenie kosztu dostawy i czasu dostawy changeCurrentShippingInfo(e.target); } return; } // Kliknięcie na płatność if(e.target.name === "payform_id"){ // Usunięcie klona poprzedniego przelewu online/ karty płatniczej removePrevClone(); // Wyskakujące okienko od vouchera if(e.target.value === "2" && (e.target.parentElement.querySelector(".voucher-value") && e.target.parentElement.querySelector(".voucher-value").style.display === "none")) { app_shop.fn.voucherModal = new Modal({ element: $(".order__voucher_container"), classList: "--fade-in-modal", afterShow: () => { disablePageScroll(); document.getElementById("order_voucher_id").addEventListener("keydown", handleClickVoucherEnter); document.querySelector(".order__voucher_button").addEventListener("click", handleClickVoucherSubmit); }, beforeClose: () => { enablePageScroll(); document.getElementById("order_voucher_id").removeEventListener("keydown", handleClickVoucherEnter); document.querySelector(".order__voucher_button").removeEventListener("click", handleClickVoucherSubmit); // Odznacz/Zaznacz poprzedzni jeśli użytkownik nie podał poprawnego kodu if(e.target.parentElement.querySelector(".voucher-value").style.display === "none"){ if(prevPayment) prevPayment.checked = true; else e.target.checked = false; } }, }); return; } // Przelewy online i karty płatnosci if(e.target.dataset.group === "transfer" || e.target.dataset.group === "card"){ if(!e.target.closest(".osc_item-modal")) showPaymentMethodModal(e.target.dataset.group); return; } // Inne metody płatności if(document.getElementById("payitem_2") && e.target.value !== "2" && e.target.dataset.group !== "transfer" && e.target.dataset.group !== "card"){ const voucherOptionContainer = document.getElementById("payitem_2").parentElement; voucherOptionContainer.querySelector(".voucher-value").style.display = "none"; voucherOptionContainer.querySelector(".voucher-value").innerHTML = ``; } // Zmien metody dostawy pomiedzy prepaid a dvp if(e.target.id === "payitem_cash" && document.getElementById("osc_order1_dvp").style.display === "none" || e.target.id !== "payitem_cash" && document.getElementById("osc_order1_dvp").style.display === "block") changeDeliveryOptions(); prevPayment = e.target; } }); // Zmiana aktywnej daty w kalendarzu function handleChangeDeliveryDate(el){ if(el.classList.contains("--another")){ return el.classList.add("--open"); } const optionsContainer = el.closest(".delivery_date__options"); optionsContainer.querySelector(".delivery_date__calendar_option.active").classList.remove("active"); el.classList.add("active"); } // Schowanie sklonowanej metody płatności function removePrevClone(){ const prevClone = document.querySelector(".osc_item-clone"); if(!prevClone) return; const cloneGroupName = prevClone.querySelector("input").dataset.group; document.getElementById(`payitem_${cloneGroupName}`).closest(".osc_item").style.display="grid"; prevClone.remove(); } // Utworzenie modala po kliknieciu na "przelewy online" lub "karta platnicza" let ifChosenNewPaymentMethod = false; function showPaymentMethodModal(method){ app_shop.fn.paymentModal = new Modal({ element: $(`.${method}__methods`), classList: "--fade-in-modal", afterShow: () => { disablePageScroll(); document.querySelectorAll(`.${method}__methods .osc_item`).forEach(el => { el.addEventListener("click", handlePaymentMethodClick); }) }, beforeClose: () => { enablePageScroll(); if(!ifChosenNewPaymentMethod) prevPayment ? prevPayment.checked = true : document.getElementById(`payitem_${method}`).checked = false; document.querySelectorAll(`.${method}__methods .osc_item`).forEach(el => { el.removeEventListener("click", handlePaymentMethodClick); }) ifChosenNewPaymentMethod=false; }, }) } // Metoda oblugujaca kliknieca w metody platnosci w popupie function handlePaymentMethodClick(e){ // znajdz input const inputEl = e.target.closest(".osc_item").querySelector("input"); // Usuń poprzedni klon i stwórz nowy removePrevClone(); cloneElement(inputEl); // Zamkniecie modala ifChosenNewPaymentMethod = true; app_shop.fn.paymentModal.closeModal(); return false; } function cloneElement(originalPaymentElement){ // Sklonowanie kliknietego elementu const clonedMethod = originalPaymentElement.closest(".osc_item").cloneNode(true); const clonedInput = clonedMethod.querySelector("input"); // Zmiana id i klasy sklonowanego elementu dla rozróżnienia clonedInput.id = clonedInput.id+"-clone"; clonedMethod.setAttribute("for", clonedInput.id); clonedMethod.classList.add("osc_item-clone"); // Wstawienie klona po "przelewy online" lub "karta platnicza" const standInEl = document.getElementById(`payitem_${clonedInput.dataset.group}`).closest(".osc_item"); standInEl.after(clonedMethod); standInEl.style.display = "none"; clonedInput.checked = true; } // Zmiana opcji dostawy zależnie od płatności function changeDeliveryOptions(){ if(document.getElementById("payitem_cash") && document.getElementById("payitem_cash").checked) changePrepaidDvp("none", "block"); else changePrepaidDvp("block", "none"); document.querySelectorAll("#bm-oscop-deliveries input").forEach((el) => el.checked = false); app_shop.vars.checkedShipping = ""; calculateBasketCost(); } // Zmień pokazane metody dostawy function changePrepaidDvp(prepaidStyle, dvpStyle){ const prepaid = document.getElementById("osc_order1_prepaid"); const dvp = document.getElementById("osc_order1_dvp"); prepaid.style.display = prepaidStyle; dvp.style.display = dvpStyle; clearSelectedPoints(); } // Wyczyszczenie informacji o punktach odbioru function clearSelectedPoints(){ const fSelectedPoints = document.querySelectorAll("#osc_order1 .fselectedPoint"); fSelectedPoints.forEach(el => { el.innerHTML=""; el.style.display="none"; }); } // Zatwierdź bon towarowy enterem function handleClickVoucherEnter(e){ if(e.key === "Enter") handleClickVoucherSubmit(); } // Zatwierdź bon towarowy function handleClickVoucherSubmit(){ const voucherNumber = document.getElementById("order_voucher_id"); const voucherRadioButton = document.getElementById("payitem_2"); const voucherOptionContainer = voucherRadioButton.parentElement; $.ajax({ url: "/ajax/gift-cards-and-vouchers.php", type: "POST", timeout: 16000, data: `action=auth&number=${voucherNumber.value}`, complete: function (e, a) { throwAjaxError(a); }, success: function (e) { // Jeśli nieprawidłowy kod wyświetl błąd if(e.errno !== "0"){ addErrorMessage(voucherNumber, ); return; } // Zmien z dvp na prepaid jesli wcześniej była zapłata za pobraniem if(prevPayment && voucherRadioButton.id !== prevPayment.id && prevPayment.id === "payitem_cash") changeDeliveryOptions(); prevPayment = e.target; // Pokaż cenę voucherOptionContainer.querySelector(".voucher-value").style.display = "block"; voucherOptionContainer.querySelector(".voucher-value").innerHTML = `${e.result.value} ${e.result.currency}`; // Wyczyść walidacje removeErrorMessage(voucherNumber); clearValidation(voucherNumber); // Zamknij modal app_shop.fn.voucherModal.closeModal(); }, }) } ////////////////////////////////////////////////////////////////////// // PODSUMOWANIE // Przeliczenie i pokazanie ceny w podsumowaniu let xhrs; function calculateBasketCost() { const deliveryCostEl = document.querySelector("#order2_shipping_value .operation_value"); const productsPointsEl = document.querySelector("#order2_products_points .operation_value"); const summaryPointsEl = document.getElementById("summary-points"); const attatchedSummaryPointsEl = document.getElementById("attatched-points"); // Przygotowanie informacji o metodzie dostawy i platnosci const orderInfo = { delivery: document.querySelector('.bm-oscop__container input[name="shipping"]:checked') ? document.querySelector('.bm-oscop__container input[name="shipping"]:checked').value : "0-1", payform_id: document.querySelector('.bm-oscop__container input[name="payform_id"]:checked') ? document.querySelector('.bm-oscop__container input[name="payform_id"]:checked').value : "cash" } xhrs && 4 != xhrs.readyState && 0 != xhrs.readyState && xhrs.abort(), xhrs = $.ajax({ url: "/ajax/basket-cost.php", dataType: "json", data: orderInfo, success: function (t) { document.querySelector("#order2_products_worth .operation_value").innerHTML = formatPrice(t.products_worth, t.currency_sign) + "" + + ""; // Sprawdź cene dostawy if(t.shipping_undefined) deliveryCostEl.parentElement.style.display = "none"; else { deliveryCostEl.parentElement.style.display = "flex"; deliveryCostEl.classList.remove("cost_free"); if(t.shipping_cost_points) deliveryCostEl.innerHTMl = `${t.shipping_cost_points}${}`; else if(t.shipping_cost_after_rebate > 0) deliveryCostEl.innerHTML = formatPrice(t.shipping_cost_after_rebate, t.currency_sign) + "" + + "" else if(t.shipping_cost > 0){ deliveryCostEl.innerHTML = "" + formatPrice(t.shipping_cost, t.currency_sign) + " " + `${} `; deliveryCostEl.classList.add("cost_free"); }else{ deliveryCostEl.innerHTML = `${} `; deliveryCostEl.classList.add("cost_free"); } } checkShowPrice(document.querySelector("#order2_paymentcost_value .operation_value"), Number(t.prepaid_cost), t.currency_sign); checkShowPrice(document.querySelector("#order2_insurance_value .operation_value"), Number(t.insurance_cost), t.currency_sign); checkShowPrice(document.querySelector("#order2_total_rebate .operation_value"), Number(t.total_rebate_without_shipping), t.currency_sign); checkShowPrice(document.querySelector("#order2_saldo_value .operation_value"), Number(t.payment_amount_from_client_balance), t.currency_sign); // Punkty zamówienia if(t.products_worth_at_points){ productsPointsEl.innerHTML = `${t.products_worth_at_points} ${}.`; productsPointsEl.parentElement.style.display = "flex"; summaryPointsEl.innerHTML = `+ ${t.products_worth_at_points} ${}.`; summaryPointsEl.style.display = "block"; attatchedSummaryPointsEl.innerHTML = `+ ${t.products_worth_at_points} ${}.`; attatchedSummaryPointsEl.style.display = "block"; }else { productsPointsEl.parentElement.style.display = "none"; summaryPointsEl.style.display = "none"; attatchedSummaryPointsEl.style.display = "none"; } // Cena całkowita document.getElementById("summary-cost").innerHTML = formatPrice(t.total_to_pay, t.currency_sign) + "" + + ""; document.getElementById("attatched-cost").innerHTML = formatPrice(t.total_to_pay, t.currency_sign); }, }); }; // Funkcja od pokazania wybranej ceny (np rabat, ubezpieczenie...) function checkShowPrice(priceContainer, price, currencySign){ priceContainer.innerHTML = formatPrice(price, currencySign); if(price && price > 0) priceContainer.parentElement.style.display = "flex"; else priceContainer.parentElement.style.display = "none"; }; // Funkcja od formatowania ceny function formatPrice(price, currencySign) { return format_price(price, { mask: app_shop.vars.currency_format, currency: currencySign, currency_space: app_shop.vars.currency_space, currency_before_price: app_shop.vars.currency_before_value }); }; // Funkcja od ustalenia daty dostawy function calculateDeliveryDate(deliveryVal, delivery, pickuppoint) { const deliveryMessageEl = document.querySelector("#order2_shiptime span:not(.operation_value)"); const attatchedMessageEl = document.querySelector("#attatched-shiptime span:not(.operation_value)"); const deliveryDateEl = document.querySelector("#order2_shiptime .operation_value"); const attatchedDateEl = document.querySelector("#attatched-shiptime .operation_value"); const date = delivery.split("#"); // Wybranie nazwy zaleznie czy dostawa jest do twojego mieszkania czy nie if(deliveryVal === "0-0" || deliveryVal === "0-1" || pickuppoint === "true"){ deliveryMessageEl.innerHTML = `${}:`; attatchedMessageEl.innerHTML = `${}:`; } else{ deliveryMessageEl.innerHTML = `${}:`; attatchedMessageEl.innerHTML = `${}:`; } if(date[4]>0) { deliveryDateEl.innerHTML = `${} ` + parseInt(date[5]) + ` ${} `; attatchedDateEl.innerHTML = `${} ` + parseInt(date[5]) + ` ${} `; } else{ if(parseInt(date[5]) === 0){ deliveryDateEl.innerHTML = ; attatchedDateEl.innerHTML = ; } else{ deliveryDateEl.innerHTML = app_shop.txt[`week_day${parseInt(date[3])}`]; attatchedDateEl.innerHTML = app_shop.txt[`week_day${parseInt(date[3])}`]; } } }; // Zmiana informacji o dostawie function changeDeliveryInfoObject(deliveryObject, deliveryElement){ deliveryObject.deliveryVal = deliveryElement.value; deliveryObject.delivery = deliveryElement.dataset.delivery; deliveryObject.pickuppoint = deliveryElement.dataset.pickuppoint; } // Obsługa klilnięć na elementy w podsumowaniu document.getElementById("bm-oscop-section3").addEventListener("click", (e) => { const productsContainer = document.querySelector(".summary__container"); // Kliknięcie na przyciski "Pokaż pozozostałe produkty" i "Zwiń listę" const togggleProducts = e.target.closest(".order_products_action"); if(togggleProducts){ if(productsContainer.className.includes("--more")){ productsContainer.classList.remove("--more"); togggleProducts.querySelector("span").innerHTML = `${}`; }else{ productsContainer.classList.add("--more"); togggleProducts.querySelector("span").innerHTML = `${}`; } checkIfShowAttatched(); return; } // Kliknięcie na checkbox(nie zaznacz wszystkie i nie kod rabatowy) if(e.target.type === "checkbox" && e.target.id !== "checkall-terms" && e.target.id !== "rebate-option"){ document.querySelector(".bm-oscop__attatched-checkbox").classList.remove("--error"); const checkboxAllTerms = document.getElementById("checkall-terms"); const attatchedcheckboxAllTerms = document.getElementById("attatched-checkall-terms"); if(e.target.checked === false) { checkboxAllTerms.checked = false; attatchedcheckboxAllTerms.checked = false; // usuniecie bledu jesli jest na przyczepionym przycisku zakupowym document.querySelector(".bm-oscop__attatched-checkbox").classList.remove("--error"); } else{ const termsInputs = document.querySelectorAll(".order2_terms_wrapper input:not(#checkall-terms)"); let checkedCount = 0; termsInputs.forEach(el => el.checked === true ? checkedCount++ : ""); if(checkedCount === termsInputs.length) { checkboxAllTerms.checked = true; attatchedcheckboxAllTerms.checked = true; } } return; } // Kliknięcie na przycisk "Zaznacz wszystkie" if(e.target.id === "checkall-terms") return toggleAllTerms(); // Usuń error na regulaminie if(e.target.closest(".order2_terms_wrapper_sub") && e.target.closest(".order2_terms_wrapper_sub").querySelector(".text-danger")){ e.target.closest(".order2_terms_wrapper_sub").querySelector("span").classList.remove("text-danger"); e.target.closest(".order2_terms_wrapper_sub").querySelector("a").classList.remove("text-danger"); } }); function toggleAllTerms(){ removeErrorOnTerms(); const termsInputs = document.querySelectorAll(".order2_terms_wrapper input:not(#checkall-terms)"); let checkAll = false; termsInputs.forEach(el => el.checked === false ? checkAll = true : ""); termsInputs.forEach(function (el) { el.checked = checkAll; }); document.getElementById("checkall-terms").checked = checkAll; document.getElementById("attatched-checkall-terms").checked = checkAll; } function removeErrorOnTerms(){ document.querySelector(".bm-oscop__attatched-checkbox").classList.remove("--error"); document.querySelector(".order2_terms_conditions span").classList.remove("text-danger"); document.querySelector(".order2_terms_conditions a").classList.remove("text-danger"); document.querySelector(".order2_cancel span").classList.remove("text-danger"); document.querySelector(".order2_cancel a").classList.remove("text-danger"); } // PRZYCISK ZAKUPU PRZYTWIERDZONY NA DÓŁ STRONY function checkIfShowAttatched(){ const attatchedEl = document.querySelector("#attatched-summary .bm-oscop__attatched-container"); const summaryCheckAllPos = document.getElementById("checkall-terms").getBoundingClientRect(); // Sprawdzenie czy pokazać przytwierdzony przycisk do zakupu if(summaryCheckAllPos.top >= window.innerHeight - attatchedEl.offsetHeight){ attatchedEl.style.opacity = "1"; attatchedEl.closest("#attatched-summary").style.zIndex = "30"; } else{ attatchedEl.style.opacity = "0"; attatchedEl.closest("#attatched-summary").style.zIndex = "-1"; } // Sprawdzenie czy pokazywać cenę const summaryEl = document.querySelector(".order2_summary"); // Przeliczana wysokość elementu przytwierdzonego przycisku zakupu na wypadek gdyby cena miała display: none const attatchedElHeight = attatchedEl.querySelector(".bm-oscop__attatched-price").style.display === "none" ? (summaryEl.offsetHeight + attatchedEl.offsetHeight) : attatchedEl.offsetHeight if(summaryEl.getBoundingClientRect().top >= window.innerHeight - attatchedElHeight){ attatchedEl.querySelector(".bm-oscop__attatched-price").style.display = "block"; }else{ attatchedEl.querySelector(".bm-oscop__attatched-price").style.display = "none"; } } window.addEventListener("scroll", e=>{ checkIfShowAttatched() }); document.getElementById("attatched-checkall-terms").addEventListener("click", toggleAllTerms); //////////////////////////////////////////////////////////////////////////////// // KOD RABATOWY (funkcje) // Funkcje do przerobienia kodu rabatowego const ACTIVATE_REBATE_CODE = (code) => JSON.stringify({ query: `mutation { activateRebateCode(code: "${code.replace(/"/g, '\\"')}") { status error { code message } } }`, }) const DEACTIVATE_REBATE_CODE = () => JSON.stringify({ query: `mutation { deactivateRebateCode { status error { code message } } }`, }) // Aktywacja kodu rabatowego const rebateCode = document.getElementById("rebate-code"); async function updateCode(){ if(rebateCode.value.trim() === ""){ addError(rebateCode); rebateCode.insertAdjacentHTML("afterend",`${}.`); return; } app_shop.fn.ajaxLoadSite(1); // Wysłanie kodu do aktywacji const rebateStatus = await fetchData({ data: ACTIVATE_REBATE_CODE(rebateCode.value), linkParameter: "?mutation=activateRebateCode", }); const { status } = rebateStatus?.data?.activateRebateCode; app_shop.fn.ajaxLoadSite(0); // Przeliczenie kosztu koszyka jeśli sukces if (status === 'success') { toggleActiveCode(true); calculateBasketCost(); return; } // Pokazanie błędu const { message } = rebateStatus?.data?.activateRebateCode?.error; addError(rebateCode); addErrorMessage(rebateCode, message); // Schowaj kod (show=false, error=true) toggleActiveCode(false, true); } // Usunięcie aktywnego kodu rabatowego async function removeCode(){ app_shop.fn.ajaxLoadSite(1); const rebateStatus = await fetchData({ data: DEACTIVATE_REBATE_CODE(), linkParameter: "?mutation=deactivateRebateCode", }); app_shop.fn.ajaxLoadSite(0); const { status } = rebateStatus?.data?.deactivateRebateCode; if (status === 'success') { toggleActiveCode(false); calculateBasketCost(); } } // Zmień widoczność kodu rabatowego const rebateCodeContainer = document.querySelector(".rebate__code"); function toggleActiveCode(show, error=false){ const activeCodeEl = document.getElementById("active-code"); // Wyczyść walidacje if(!error){ removeErrorMessage(rebateCode); clearValidation(rebateCode); } // Zmień widoczność document.querySelector(".rebate__options").style.display = show ? "none" : "flex"; document.querySelector(".rebate__active").style.display = show ? "block" : "none"; if(!error) rebateCodeContainer.classList.remove("--fade-in"); else rebateCodeContainer.classList.add("--fade-in"); // Zmień wartości activeCodeEl.innerHTML = show ? rebateCode.value : ""; showInput = error ? true : false; document.getElementById("rebate-option").checked = error ? true : false; if(!error) rebateCode.value = ""; else activeCodeEl.innerHTML = ""; } // EventListenery dla kodu rabatowego let showInput = false; document.querySelector(".rebate").addEventListener("click", (e) => { // Rozwinięcie opcji rabatowej if(e.target.id === "rebate-option" || e.target.classList.contains("rebate__active-change")){ showInput = !showInput; if(showInput) rebateCodeContainer.classList.add("--fade-in"); else rebateCodeContainer.classList.remove("--fade-in"); } // Kliknięcie na zrealizuj i dezaktywuj if(e.target.className.includes("rebate__code-realize")) updateCode(); if(e.target.classList.contains("rebate__active-remove")) removeCode(); }); // Aktywacja kodu po naciśnięciu na enter rebateCode.addEventListener("keydown", e=>{ if(e.key === "Enter") updateCode(); }) /////////////////////////////////////////////////////////////////////// // ZŁOŻENIE ZAMÓWIENIA // Zwaliduj wszystkie dostępne inputy zawierające dane klienta i dane adresowe async function validateAllInputs(){ // Zmienna trzymająca informację czy wystąpił jakiś błąd let allGood = true; // Sprawdzenie loginu i hasła jeśli zaznaczone if(document.getElementById("register_client_checkbox") && document.getElementById("register_client_checkbox").checked){ allGood = testLogin() && allGood; allGood = testPassword() && allGood; } if(!document.querySelector(".--logged")){ // Sprawdzenie emaila i telefonu allGood = await validateRequest(document.getElementById("client_email"), true) && allGood; allGood = validatePhone(document.getElementById("client_phone")) && allGood; // Sprawdzenie nazwy firmy i nipu if(document.getElementById("client_type1").checked){ allGood = validateNotEmpty(document.getElementById("client_firm")) && allGood; allGood = await validateRequest(document.getElementById("client_nip"), true) && allGood; } // Sprawdzenie reszty pól allGood = await validateFormInputs("client") && allGood; } // Sprawdzanie pól dostawy na inny adres if(document.getElementById("deliver_to_billingaddr").checked){ allGood = await validateFormInputs("delivery") && allGood; allGood = validatePhone(document.getElementById("delivery_phone")) && allGood; } return allGood } async function validateFormInputs(query){ let isFormGood = true; isFormGood = validateNotEmpty(document.getElementById(`${query}_firstname`)) && isFormGood; isFormGood = validateNotEmpty(document.getElementById(`${query}_lastname`)) && isFormGood; isFormGood = validateStreet(document.getElementById(`${query}_street`)) && isFormGood; isFormGood = await validateRequest(document.getElementById(`${query}_zipcode`),true) && isFormGood; isFormGood = validateNotEmpty(document.getElementById(`${query}_city`)) && isFormGood; return isFormGood; } // Obsługa złożenia zamówienia document.querySelectorAll(".order2_button_order").forEach(btnEl=>{ btnEl.addEventListener("click", handleBuyOnClick); }) async function handleBuyOnClick(){ const termsConditionsInput = document.getElementById("order2_terms_conditions"); const cancelConditionsInput = document.getElementById("order2_cancel"); try { app_shop.fn.ajaxLoadSite(1); app_shop.vars.validation = 1; // Sprawdzenie pól formularza const allInputsCorrectlyValidated = await validateAllInputs(); if(allInputsCorrectlyValidated === false) app_shop.vars.validation = 0; // Znalezienie obecnie zaznaczonej metody dostawy i płatności const deliveryMethod = document.querySelector(".bm-oscop__container [name=shipping]:checked"); const paymentMethod = document.querySelector(".bm-oscop__container [name=payform_id]:checked"); // Sprawdzenie czy użytkownik zaakceptował regulamin if(!termsConditionsInput.checked || !cancelConditionsInput.checked){ app_shop.vars.validation = 0; showTermsError(termsConditionsInput); showTermsError(cancelConditionsInput); }// Sprawdzenie czy użytkownik wybrał metodę dostawy i płatności (też sprawdzenie czy wybrał paczkomat i wpisał voucher) else { if(deliveryMethod){ if(deliveryMethod.dataset.pickuppoint === "true" && deliveryMethod.parentElement.querySelector(".fselectedPoint").innerHTML === "") orderValidationError(); } else orderValidationError(); if(paymentMethod){ if(paymentMethod.value === "2" && document.getElementById("order_voucher_id").value === "") orderValidationError(); } else orderValidationError(); } // Sprawdzenie formularza rejestracji nowego konta wraz z zakupem let registerError = ""; const registerCheckbox = document.getElementById("register_client_checkbox"); if(registerCheckbox && registerCheckbox.checked){ if(!testLogin()) registerError += `${}
    `; if(!testPassword()) registerError += `${}`; if(registerError.length > 0){ orderValidationError(registerError); scrollToHeight(document.querySelector(".register")); } } // Przerwanie składania zamówienia jeśli w trakcie walidacji wystąpił błąd if (app_shop.vars.validation === 0) { const errorEl = document.querySelector(".--error.has-error"); let scrolledToElement; let alertMessage = ""; // Element sprawdzający czy regulamin jest zaznaczony const termsAndConditions = termsConditionsInput.checked && cancelConditionsInput.checked; if(!termsAndConditions){ document.querySelector(".bm-oscop__attatched-checkbox").classList.add("--error"); alertMessage += `${} ${}!
    `; } // Sprawdź metodę płatności i dostawy(scrollowanie do formularza ważniejsze) if(!document.querySelector(`input[name="shipping"]:checked`)){ scrolledToElement = errorEl || document.querySelector("#bm-oscop-deliveries h2"); alertMessage += `${}
    `; } if(!document.querySelector(`input[name="payform_id"]:checked`)){ scrolledToElement = errorEl || document.querySelector("#bm-oscop-payments h2"); alertMessage += `${}
    `; } // Błąd w formularzu if(errorEl){ scrolledToElement = errorEl; alertMessage += `${}`; } // Jeśli użytkownik zatwierdził regulamin, przescrolluj do elementu z błędem if(scrolledToElement) scrollToHeight(scrolledToElement); // Pokaż error i przerwij składanie zamówienia Alertek.show_alert(alertMessage); return app_shop.fn.ajaxLoadSite(0); } // Rejestracja użytkownika i/lub złożenie zamówienia if(registerCheckbox && registerCheckbox.checked){ addClient(function() { createOrder(deliveryMethod.value, paymentMethod.value); }, function() {}); } else createOrder(deliveryMethod.value, paymentMethod.value); return !1; } catch (e) { app_shop.fn.ajaxLoadSite(0); console.log(e); alert("blad"); } } // Przescrolluj do function scrollToHeight(scrollToEl){ let yOffset = -45; if(app_shop.vars.view === 1) yOffset = -100; if(app_shop.vars.view === 2) yOffset = -75; const y = scrollToEl.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } // Schowaj/Pokaż error na warunkach regulaminun function showTermsError(input){ if(!input.checked){ input.parentElement.querySelector("span").classList.add("text-danger"); input.parentElement.querySelector("a").classList.add("text-danger"); } } // Złożenie zamówienia function createOrder(deliveryMethod, paymentMethod){ // Weź dane klienta const phone = `+${document.querySelector("#client-contact-info .phone_number__code_number").value} ${document.getElementById("client_phone").value}`; const email = document.getElementById("client_email").value; const clientType = document.querySelector('.bm-oscop__container [name="client_type"]:checked').value; const firmname = clientType === "firm" ? document.getElementById("client_firm").value : ""; const nip = clientType === "firm" ? document.getElementById("client_nip").value : ""; let firstname = document.getElementById("client_firstname").value; let lastname = document.getElementById("client_lastname").value; const street = document.getElementById("client_street").value; const city = document.getElementById("client_city").value; const zipcode = document.getElementById("client_zipcode").value; const region = document.getElementById("client_region").value; // Weź dane dostawy z innego adresu jeśli jest zaznaczone let deliveryFirstname, deliveryLastname, deliveryFirmName, deliveryStreet, deliveryCity, deliveryZipcode, deliveryPhone, deliveryRegion; if (document.getElementById("deliver_to_billingaddr").checked){ deliveryFirstname = document.getElementById("delivery_firstname").value; deliveryLastname = document.getElementById("delivery_lastname").value; deliveryFirmName = document.getElementById("delivery_additional").value; deliveryStreet = document.getElementById("delivery_street").value; deliveryCity = document.getElementById("delivery_city").value; deliveryZipcode = document.getElementById("delivery_zipcode").value; deliveryPhone = `+${document.querySelector(".delivery_box .phone_number__code_number").value} ${document.getElementById("delivery_phone").value}`; deliveryRegion = document.getElementById("delivery_region").value; }; // Informacje o newsletterze const clientMailing = checkNewsletter("client_mailing_logg","#client_mailing"); const clientSms = checkNewsletter("client_send_sms_logg", "#client_sms"); // Kod rabatowy i kod vouchera let rebateCode; if (document.getElementById("active-code")) rebateCode = document.getElementById("active-code").innerHTML; else rebateCode = ""; let voucherCode; if(document.querySelector(".bm-oscop__container #payitem_2") && document.querySelector(".bm-oscop__container #payitem_2").checked) voucherCode = document.querySelector(".bm-oscop__container #order_voucher_id").value; // Jeśli zalogowany użytkownik jest firmą i nie ma imienia i nazwiska if (clientType.disabled && clientType.value === "firm") { if (!firstname) firstname = (deliveryFirstname) ? deliveryFirstname : 'Klient'; if (!lastname) lastname = (deliveryLastname) ? deliveryLastname : 'Firma'; } // Czyszczenie imienia i nazwiska ze znaków specjalnych firstname = firstname.replace(/[&\/\\#,+()$~%.'":*?<>{}!@~`^_]/g, ""); lastname = lastname.replace(/[&\/\\#,+()$~%.'":*?<>{}!@~`^_]/g, ""); // Dodatkowe informacje (uwagi, faktura, punkt odbioru) const shopRemarks = document.getElementById("shop_remarks").checked ? document.querySelector(".bm-oscop__container [name=remarks]").value : ""; const deliveryRemarks = document.getElementById("courier_remarks").checked ? document.querySelector(".bm-oscop__container [name=deliverer_remarks]").value : ""; // Czas dostawy jeśli jest taka opcja const pickedDeliveryMethod = document.querySelector("#bm-oscop-deliveries .osc_item:has(input[name='shipping']:checked)"); let deliveryDate = ""; let deliveryHour = ""; if(pickedDeliveryMethod.querySelector(".delivery_date__options")){ deliveryDate = pickedDeliveryMethod.querySelector(".delivery_date__calendar_option.active").dataset.date; deliveryHour = pickedDeliveryMethod.querySelector(".delivery_date__hours_options") ? pickedDeliveryMethod.querySelector(".delivery_date__hours_options").value : ""; } const invoiceOption = document.querySelector("input[name=invoice]:checked").value; const pickuppoint = document.querySelector("#osc_order1 input:checked").dataset.pickuppoint === "true" ? document.querySelector("#osc_order1 input:checked").parentElement.querySelector("label [name=pickup_point]").value : ""; const order = { affiliate: "", rebate_code: rebateCode, rebate_profit_points_id: "", client: { email: email, type: clientType, firm: firmname, nip: nip, firstname: firstname, lastname: lastname, street: street, city: city, zipcode: zipcode, phone: phone, phone2: "", region: region, province: "", delivery: { firstname: deliveryFirstname, lastname: deliveryLastname, additional: deliveryFirmName, street: deliveryStreet, city: deliveryCity, zipcode: deliveryZipcode, phone: deliveryPhone, region: deliveryRegion }, save_to_mailing_after_order: clientMailing, save_to_mailing_sms_after_order: clientSms, }, order: { stock: 1, payform_id: paymentMethod, voucher_code: voucherCode, remarks: shopRemarks, wants_invoice: invoiceOption, shipping: deliveryMethod, shipping_for_points: "", pickup_point: pickuppoint, delivery_hour: deliveryHour, delivery_date: deliveryDate, delivery_text: "", delivery_remarks: deliveryRemarks, }, }; // Złóż zamówienie jako zalogowany/niezalogowany użytkownik. if (document.querySelector(".--logged")) sendOrder(order); else { const clientData = new FormData(); if(firmname) clientData.append("client_firm", firmname); if(nip) clientData.append("client_nip", nip); clientData.append("client_firstname", firstname); clientData.append("client_lastname", lastname); clientData.append("client_street", street); clientData.append("client_zipcode", zipcode); clientData.append("client_city", city); clientData.append("client_region", region); clientData.append("client_email", email); clientData.append("client_phone", phone); $.ajax({ url: "/client-new.php?operation=onceorder", type: "POST", data: clientData, timeout: 1e4, cache: !1, contentType: !1, processData: !1, complete: function (e, a) { throwAjaxError(a); }, success: function (e, a) { sendOrder(order); }, }); } } function checkNewsletter(logged, regular){ if(document.querySelector(`.bm-oscop__container [name=${logged}]`)) return document.querySelector(`.bm-oscop__container [name=${logged}]`).value ? 1 : 0; else if(document.querySelector(regular)) return document.querySelector(regular).checked ? 1 : 0; else return 0; } // Funkcja wysyłająca zamówienie function sendOrder(data){ $.ajax({ url: "/ajax/order-create.php", type: "post", timeout: 16e3, dataType: "json", data: data, complete: function (e, a) { console.log("sendorder", e, a); throwAjaxError(a); }, success: function (e) { if(e.location){ // Zapisanie państwa żeby sprawdzić czy się zgadza const usedCountry = document.getElementById("deliver_to_billingaddr").checked ? document.getElementById("delivery_region").value : document.getElementById("client_region").value; // Zapisanie płatności i dostawy na następny raz const paymentInput = document.querySelector(`input[name="payform_id"]:checked`) const usedPaymentMethod = { id: paymentInput.id, group: paymentInput.dataset.group, }; const deliveryMethod = document.querySelector(`input[name="shipping"]:checked`); const selectedPoint = deliveryMethod.parentElement.querySelector(".fselectedPoint"); const usedDeliveryMethod = { id: deliveryMethod.id, fselectedPoint: selectedPoint ? { deliveryPointId: selectedPoint.dataset.deliveryPointId, name: selectedPoint.dataset.name, street: selectedPoint.dataset.street, zipcode: selectedPoint.dataset.zipcode, city: selectedPoint.dataset.city, courierId: selectedPoint.dataset.courierId } : false }; const prevOrderInfo = { prevPaymentMethod: usedPaymentMethod, prevDeliveryMethod: usedDeliveryMethod, prevCountry: usedCountry } localStorage.setItem("prevOrderInfo", JSON.stringify(prevOrderInfo)); // Przeniesienie na stonę informacji o zamóieniu window.location.href = e.location; return; } if(e.errno){ app_shop.fn.ajaxLoadSite(0) e.errno === 115 ? Alertek.show_alert(`${}`) : Alertek.show_alert(e.error); } }, }); } // REJESTRACJA KLIENTA const REGISTER_CLIENT = (registerClientInput) => JSON.stringify({ query: `mutation { registerClient(${registerClientInput}) { status error { code message } } }`, }); // Funkcja tworząca nowego klienta wraz z zamówieniem async function addClient(succes, error){ const clientType = document.querySelector("input[name=client_type]:checked").value; const saveToMailing = document.getElementById("client_mailing"); let saveToMailingData = false; if(saveToMailing && saveToMailing.checked) saveToMailingData = true; const saveToSms = document.getElementById("client_sms"); let saveToSmsData = false; if(saveToSms && saveToSms.checked) saveToSmsData = true; const registerClientData = await fetchData({ data: REGISTER_CLIENT(`RegisterClientInput: { clientData: { clientDeliveryData: { ${clientType === "firm" ? `companyName: "${document.getElementById("client_firm").value}",` : ""} firstname: "${document.getElementById("client_firstname").value}", lastname: "${document.getElementById("client_lastname").value}", street: "${document.getElementById("client_street").value}", zipcode: "${document.getElementById("client_zipcode").value}", city: "${document.getElementById("client_city").value}", country: ${document.getElementById("client_region").value}, phone: "${document.getElementById("client_phone").value}", } ${ document.getElementById("deliver_to_billingaddr").checked ? `clientDeliveryOtherAddressData: { companyName: "${document.getElementById("delivery_additional").value}", firstname: "${document.getElementById("delivery_firstname").value}", lastname: "${document.getElementById("delivery_lastname").value}", street: "${document.getElementById("delivery_street").value}", zipcode: "${document.getElementById("delivery_zipcode").value}", city: "${document.getElementById("delivery_city").value}", country: ${document.getElementById("delivery_region").value}, phone: "${document.getElementById("delivery_phone").value}", }` : "" } type: ${clientType}, ${clientType === "firm" ? `taxNumber: "${document.getElementById("client_nip").value}",` : ""} email: "${document.getElementById("client_email").value}", saveToMailingAfterOrder: ${saveToMailingData}, saveToSmsAfterOrder: ${saveToSmsData}, } loginAndPassword: { login: "${document.querySelector(".register__login").value}", password: "${document.querySelector(".register__password").value}", passwordRepeat: "${document.querySelector(".register__password").value}", } reCaptchaToken: "${document.querySelector(`input[name="iai-recaptcha-token"`).value}" }`), linkParameter: '?mutation=registerClient', }); if(!registerClientData?.data?.registerClient?.error || registerClientData?.error?.message) succes(); else { Alertek.show_alert(registerClientData.data.registerClient.error?.message); app_shop.fn.ajaxLoadSite(0); } } // Zmiana informacji formularza w url params function serializeFormData(form){ const formData = new FormData(form); let serializedString = ""; for (const [name, value] of formData) { serializedString += `${name}=${encodeURIComponent(value)}&`; } serializedString = serializedString.slice(0,-1); return serializedString; } // Pokaz error (płatności, dostawy, zalozenie nowego konta) function orderValidationError(text){ app_shop.vars.validation = 0; Alertek.show_alert(`${text}`); } /////////////////////////////////////////////////////////////////// // RESZTA // Wyłącz scrollowanie dla strony function disablePageScroll(){ const documentBody = document.querySelector("body"); documentBody.style.paddingRight = `${15 + window.innerWidth - documentBody.clientWidth}px`; documentBody.style.overflowY = "hidden"; } function enablePageScroll(){ const documentBody = document.querySelector("body"); documentBody.style.paddingRight = "15px"; documentBody.style.overflowY = "auto"; } // Zmiana funkcji by naprawić bugi app_shop.fn.load = function(_url,target,callback,paramets) { if(app_shop.vars.xhr && app_shop.vars.xhr.readystate != 4) app_shop.vars.xhr.abort(); $(target).addClass('load-content'); for(let i=0; target.length > i ; i++) $(target[i][0]).addClass('load-content'); app_shop.vars.xhr = $.ajax({ url: _url+paramets, timeout: 16000, success: function(data,textStatus) { for(let i=0; target.length > i ; i++) $(target[i][0]).removeClass('load-content').html($(data).find(target[i][1]).html()); app_shop.fn.change_url(_url); app_shop.fn.evalJSFromHtml(data); if(callback) callback(); }, error: function(data) { window.location.href = _url; } }); return app_shop.vars.xhr; }; function throwAjaxError(e) { -1 !== $.inArray(e, ["nocontent", "error", "timeout", "abort", "parsererror"]) && (console.log("Error:" + e), Alertek.show_alert( "Błąd podczas logowania, proszę spróbować ponownie" + " (" + e + ": " + $.now() + ")"), $.cookie("off_opc", !0)); }; async function fetchData(options = {}) { const {data,link,linkParameter = '',alert = true} = options; if (!data) return false; try { const response = await fetch(`${link || app_shop.urls.graphql || '/graphql/v1/'}${linkParameter}`, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, body: data }); const dataJson = await response.json(); if ((dataJson?.errors || dataJson?.error) && alert) { Alertek.Error(); } return dataJson; } catch (error) { console.error('GraphQL fetchData() Error:', error); if (alert) { Alertek.Error(); } return false; } } // ŚWIĘTA | HOLIDAYS const OSCOP_HOLIDAYS = () => JSON.stringify({ query: `query { pickupPoints(courierId: 0) { holidays { formatted } } }`, }) async function getHolidays(){ const res = await fetchData({ data: OSCOP_HOLIDAYS(), linkParameter: "?query=holidays", }); app_shop.vars.holidays = res?.data?.pickupPoints?.holidays; } let firstTimeLoadPage = true; function initOSCOP(){ // dodanie klasy do html document.querySelector("html").classList.add("--place-order-page") // Element z numerem edycji jeśli jest const editNumber = document.getElementById("edit-number"); if(document.querySelector(".bm-oscop__container").childElementCount && !editNumber) changeRegion(null); // Jeśli edycja zamówienia uzupełnij dane (niewiadomo jak z voucherem bo go się nie da edytować) if(editNumber){ const ORDER_DETAILS = (orderNumber) => JSON.stringify({ query: `query{ orderDetails(${orderNumber}){ status client { email phone billingData { companyName taxNumber firstname lastname street zipcode city province countryName } deliveryData { companyName firstname lastname street zipcode city countryName province phone } } payment { paymentMethod { id } isFirstPayment } shipping { courier { id fullId icon name carrierName pickupPoint companyKey companyGroupKey } pickupData { id codeExternal name location link markerIconUrl requiredClientNumber coordinates { latitude longitude distance } phone address { buildingAndHouseNumber city country postcode street } courierId } remarks } remarks checkoutType } }` }); // Pobranie danych o edytowanym zamówieniu async function getEditData(){ const data = await fetchData({ data: ORDER_DETAILS(`OrderDetailsInput: { orderNumber: ${editNumber.value}, requestSource: order_edit } `), linkParameter: "?query=orderDetails", alert: false, }); // Jesli error to zatrzymaj funkcje if(!data?.data?.orderDetails || !data) return changeRegion(); // Wstawienie danych insertEditData(data.data.orderDetails); } function insertEditData(orderDetails){ const orderData = { paymentMethodId: orderDetails.payment.paymentMethod.id, deliveryMethodId: orderDetails.shipping.courier.id, pickupData: orderDetails.shipping.pickupData, }; // Sprawdzenie czy użytkownik miał inny adres Dostawy niż Billingowy. let differentDelivery = false; for(const [key, value] of Object.entries(orderDetails.client.billingData)){ if(key !== "taxNumber" && key !== "companyName"){ if(value !== orderDetails.client.deliveryData[key]) differentDelivery = true; } } if(orderDetails.client.deliveryData.phone !== orderDetails.client.phone) differentDelivery = true; // Uzupełnienie informacji innego adresu if(differentDelivery){ // Pokazanie formularza dodatkowej dostawy document.getElementById("deliver_to_billingaddr").checked = true; document.querySelector(".bm-oscop__container #client_new_additional .delivery_box.cn_wrapper").classList.add("--more"); document.querySelector(".delivery__address-list-button").classList.add("--fade-in"); fillInput(document.getElementById("delivery_firstname"), orderDetails.client.deliveryData.firstname); fillInput(document.getElementById("delivery_lastname"), orderDetails.client.deliveryData.lastname); fillInput(document.getElementById("delivery_street"), orderDetails.client.deliveryData.street); fillInput(document.getElementById("delivery_zipcode"), orderDetails.client.deliveryData.zipcode); fillInput(document.getElementById("delivery_city"), orderDetails.client.deliveryData.city); fillInput(document.getElementById("delivery_phone"), orderDetails.client.deliveryData.phone); if(orderDetails.client.deliveryData.companyName) fillInput(document.getElementById("delivery_additional"), orderDetails.client.deliveryData.companyName); document.querySelectorAll("#delivery_region option").forEach(opt => { if(opt.text === orderDetails.client.deliveryData.countryName) document.getElementById("delivery_region").value = opt.value; }); // Metody płatności i dostaw if(document.getElementById("delivery_region").value !== document.getElementById("client_region").value) changeRegion(orderData); else getNewPaymentsAndDeliveries(orderData); // Jeśli nie było dostawy na inny adres uzupełnij metody dostaw i płatności }else getNewPaymentsAndDeliveries(orderData); // Uzupełnienie uwag dla sklepu/kuriera if(orderDetails.remarks){ document.getElementById("shop_remarks").checked = true; document.getElementById("order_comment_field").value = orderDetails.remarks; } if(orderDetails.shipping.remarks){ document.getElementById("courier_remarks").checked = true; document.getElementById("order_comment2_field").value = orderDetails.shipping.remarks; } } getEditData(); // Funkcja od uzupełnienia inputów function fillInput(input, value){ input.value = value; input.classList.add("focused"); input.parentElement.classList.add("--success", "has-success"); } } // Sprawdzenie czy schować przyczepiony przycisk od zakupu checkIfShowAttatched() // Ustaw numer kraju przy telefonie createPhoneCodeList(); setPhoneCountryNumberAtStart("client"); setPhoneCountryNumberAtStart("delivery"); //pobierz święta getHolidays(); } initOSCOP();