function empty(data) {
  if (
    typeof data === "undefined" ||
    data == null ||
    data == "" ||
    data == "null" ||
    data == "undefined"
  ) {
    return true;
  }
  return false;
}
jQuery.fn.exists = function () {
  return this.length > 0;
};
var menu = {
  addressModal: false,
  menuPage: false,
  init: function () {
    menu.menuPage = true;
    menu.loadCart();
    menu.searchModal = $("#addressModal");
    menu.geoInitialize();
  },
  errorMessage: function (message) {
    swal({
      title: "Error",
      text: message,
      icon: "warning",
      buttons: true,
      dangerMode: true,
    });
  },
  successMessage: function (message) {
    swal({
      title: "Success",
      text: message,
      icon: "success",
      buttons: true,
      dangerMode: true,
    });
  },
  geocodeLat: function (lat, lng) {
    if (empty(lat) || empty(lng)) {
      return;
    }
    var geocoder = new google.maps.Geocoder();
    var latlng = { lat: parseFloat(lat), lng: parseFloat(lng) };
    geocoder.geocode({ location: latlng }, function (results, status) {
      if (status === "OK") {
        if (results[0]) {
          var resp = menu.parseAdress(results[0]);
          $("#search_address").val(resp.formatted_address);
          $("#search_lat").val(resp.lat);
          $("#search_lng").val(resp.lng);
          $("#street_number").val(resp.street);
          $("#locality").val(resp.city);
          $("#administrative_area_level_1").val(resp.state);
          $("#postal_code").val(resp.zipcode);
          $("#country").val(resp.country);
          $("#country_code").val(resp.country_code);
        } else {
          //showToast( t("No results found") );
        }
      } else {
        //showToast( t("Geocoder failed due to:") + status  );
      }
    });
  },
  parseAdress: function (result) {
    geocoded_address = [];

    var street = "",
      city = "",
      state = "",
      zipcode = "",
      kountry = "",
      formatted_address = "",
      country_code = "";

    formatted_address = result.formatted_address;

    $.each(result.address_components, function (reskey, resval) {
      $.each(resval.types, function (types_key, types_val) {
        if (
          types_val == "street_number" ||
          types_val == "route" ||
          types_val == "street_address" ||
          types_val == "sublocality_level_3"
        ) {
          if (!empty(street)) {
            street += " " + resval.long_name;
          } else {
            street += resval.long_name;
          }
        }

        if (types_val == "sublocality") {
          if (!empty(city)) {
            city += " " + resval.long_name;
          } else {
            city += resval.long_name;
          }
        }

        if (types_val == "administrative_area_level_1") {
          if (!empty(state)) {
            state += " " + resval.long_name;
          } else {
            state += resval.long_name;
          }
        }

        if (types_val == "postal_code") {
          if (!empty(zipcode)) {
            zipcode += " " + resval.long_name;
          } else {
            zipcode += resval.long_name;
          }
        }

        if (types_val == "country") {
          if (!empty(kountry)) {
            kountry += " " + resval.long_name;
            country_code += resval.short_name;
          } else {
            kountry += resval.long_name;
            country_code += resval.short_name;
          }
        }
      });
    });

    geocoded_address = {
      formatted_address: formatted_address,
      street: street,
      city: city,
      state: state,
      zipcode: zipcode,
      country: kountry,
      country_code: country_code,
      lat: result.geometry.location.lat(),
      lng: result.geometry.location.lng(),
    };
    console.log(geocoded_address);
    return geocoded_address;
  },
  geolocate: function () {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function (position) {
        menu.geocodeLat(position.coords.latitude, position.coords.longitude);
        var geolocation = new google.maps.LatLng(
          position.coords.latitude,
          position.coords.longitude
        );
        var circle = new google.maps.Circle({
          center: geolocation,
          radius: position.coords.accuracy,
        });
        autocomplete.setBounds(circle.getBounds());
      });
    }
    menu.searchModal.modal("show");
  },

  // 	geoInitialize: function () {
  // 		var searchInput = menu.searchModal.find('#search_address')[0];
  // 		autocomplete = new google.maps.places.Autocomplete((searchInput), {
  // 			types: ['geocode'],
  // 			country:[settings_map_country]
  // 		});
  // 		// google.maps.event.addDomListener(searchInput, 'focus', menu.geolocate);
  // 		autocomplete.addListener("place_changed", menu.fillInAddress);
  // 	},

  geoInitialize: function () {
    var searchInput = menu.searchModal.find("#search_address")[0];
    autocomplete = new google.maps.places.Autocomplete(searchInput, {
      types: ["geocode"],
      componentRestrictions: { country: "nz" },
    });
    // google.maps.event.addDomListener(searchInput, 'focus', menu.geolocate);
    autocomplete.addListener("place_changed", menu.fillInAddress);
  },

  fillInAddress: function () {
    var place = autocomplete.getPlace();
    var resp = menu.parseAdress(place);

    $("#search_address").val(resp.formatted_address);
    $("#search_lat").val(resp.lat);
    $("#search_lng").val(resp.lng);
    $("#street_number").val(resp.street);
    $("#locality").val(resp.city);
    $("#administrative_area_level_1").val(resp.state);
    $("#postal_code").val(resp.zipcode);
    $("#country").val(resp.country);
    $("#country_code").val(resp.country_code);
  },
  googleMapsDeliveryLocation: function () {
    dl_map = new GMaps({
      div: ".delivery_map_accuracy",
      lat: temporary_address_lat,
      lng: temporary_address_lng,
      scrollwheel: false,
      styles: [
        { stylers: [{ saturation: -100 }, { lightness: 0 }, { gamma: 1 }] },
      ],
    });

    dl_marker = dl_map.addMarker({
      lat: temporary_address_lat,
      lng: temporary_address_lng,
      draggable: true,
    });

    dl_marker.addListener("dragend", function (event) {
      $("#map_accurate_address_lat").val(event.latLng.lat());
      $("#map_accurate_address_lng").val(event.latLng.lng());
    });

    if (typeof address_list === "undefined" || address_list == null) {
      //
    } else {
      try {
        address_book_id = $("#address_book_id").val();
        lat = address_list[address_book_id].lat;
        lng = address_list[address_book_id].lng;
        dl_map.setCenter(lat, lng);
        dl_marker.setPosition(new google.maps.LatLng(lat, lng));
        $("#map_accurate_address_lat").val(lat);
        $("#map_accurate_address_lng").val(lng);
        return;
      } catch (err) {
        //
      }
    }

    GMaps.geolocate({
      success: function (position) {
        dl_map.setCenter(temporary_address_lat, temporary_address_lng);
        dl_marker.setPosition(
          new google.maps.LatLng(temporary_address_lat, temporary_address_lng)
        );
        $("#map_accurate_address_lat").val(temporary_address_lat);
        $("#map_accurate_address_lng").val(temporary_address_lng);
      },
      error: function (error) {
        //uk_msg(  js_lang.geolocation_failed + ': '+error.message);
      },
      not_supported: function () {
        //uk_msg( js_lang.browser_not_supported );
      },
      always: function () {
        //alert("Done!");
      },
    });
  },
  loadCart: function () {
    if (menu.menuPage) {
      /*	$('.rborder').load(window.location.href+' .cart_detail');*/
      $("#cart-container").load("menu/load_cart");
    } else {
      $("#cart-container").load("order/load_cart");
    }
  },

  deleteItem: function (row) {
    $(".main-preloader").show();
    $.ajax({
      url: "menu/delete_item",
      data: { row: row },
      dataType: "json",
      method: "POST",
      success: function (response) {
        if ((response.code = 1)) {
          // menu.successMessage(response.msg);
          menu.loadCart();

          $(".main-preloader").hide();
        } else {
          $(".main-preloader").hide();
          // menu.errorMessage(response.msg);
        }
      },
    });
  },

  deletemobileItem: function (row) {
    $(".main-preloader").show();
    $.ajax({
      url: "menu/delete_item",
      data: { row: row },
      dataType: "json",
      method: "POST",
      success: function (response) {
        if ((response.code = 1)) {
          // menu.successMessage(response.msg);
          window.location.reload();
          $(".main-preloader").hide();
        } else {
          $(".main-preloader").hide();
          // menu.errorMessage(response.msg);
        }
      },
    });
  },

  showItem: function (id, cat_id, row, qty) {
    $.ajax({
      type: "POST",
      url: "menu/get_item",
      data: { id: id, cat_id: cat_id, row: row, qty: qty },
      success: function (response) {
        if (response.code == 1) {
          if (empty(response.itemmenu.details.ordering_msg)) {
            $("#menumodel").html(response.html).modal("show");
          } else {
            menu.errorMessage(response.itemmenu.details.ordering_msg);
          }
        } else {
          menu.errorMessage(response.itemmenu.msg);
        }
      },
    });
  },

  showItem_promotion: function (id, cat_id, row, qty,promo_id) {
    $.ajax({
      type: "POST",
      url: "menu/get_item_promotion",
      data: { id: id, cat_id: cat_id, row: row, qty: qty, promo_id: promo_id },
      success: function (response) {
        if (response.code == 1) {
          if (empty(response.itemmenu.details.ordering_msg)) {
            $("#menumodel").html(response.html).modal("show");
          } else {
            menu.errorMessage(response.itemmenu.details.ordering_msg);
          }
        } else {
          menu.errorMessage(response.itemmenu.msg);
        }
      },
    });
  },

  ajaxForm: function (form, cb) {
    var $form = $(form);
    $.ajax({
      url: $form.attr("action"),
      data: $form.serialize(),
      dataType: "json",
      method: "POST",
      success: function (response) {
        cb(response);
      },
    });
  },
  setDeliveryAddress: function (form) {
    menu.ajaxForm(form, function (response) {
      if (response.code == 1) {
        menu.searchModal.modal("hide");
        /*	menu.loadCart();*/
      } else if (response.code == 2) {
        menu.searchModal.modal("hide");
        //menu.errorMessage(response.msg);
      }
      menu.loadCart();
    });
  },
  clearCart: function () {
    $.ajax({
      url: "menu/clearCart",
      method: "GET",
      success: function (response) {
        menu.loadCart();
      },
    });
  },
  addToCart: function (form) {
    $(".main-preloader").show();
    menu.ajaxForm(form, function (response) {
      /*	$('.rborder').load(window.location.href+' .cart_detail');*/
      if (response != null) {
        if (response.code == 1) {
          console.log(response);
          $(".item_count").text(response.post.item_count);
          $(".total_price_row").text(response.post.item_price_total);
          $("#menumodel").modal("hide");

          // menu.successMessage(response.msg);
          if (window.location.pathname.indexOf("/cart") != -1) {
            window.location.reload();
          } else {
            if (menu.menuPage) {
              menu.loadCart();
            } else {
              window.location.reload();
            }
          }
          $(".main-preloader").hide();
        } else if (response.code == 2) {
          $(".main-preloader").hide();
          menu.errorMessage(response.msg);
        }
      } else {
        $("#menumodel").modal("hide");
        $(".main-preloader").hide();
        if (menu.menuPage) {
          menu.loadCart();
        } else {
          window.location.reload();
        }
      }
      // 			window.location.reload();
    });
  },
  initPaymentOption: function () {
    menu.menuPage = false;
    menu.loadCart();
    menu.googleMapsDeliveryLocation();
  },

  addReviews: function (form) {
    menu.ajaxForm(form, function (response) {
      if (response.code == 1) {
        menu.successMessage(response.msg);
        $("#addreviewmodal").modal("hide");
      } else {
        menu.errorMessage(response.msg);
      }
      if ($(".write-review-new").exists()) {
        window.location.reload();
      }
    });
  },
};

function use_voucher() {
  var voucher_code = $("#voucher_code").val();
  $.ajax({
    type: "POST",
    url: "order/checkvoucher",
    data: { voucher_code: voucher_code },
    dataType: "json",
    success: function (data) {
      if (data.code == 1) {
        // menu.loadCart();
        //   $('#voucher_code').hide();
        //   $('.apply_voucher').hide();
        //   $('.remove_voucher').show();

        menu.successMessage(data.msg);
        menu.loadCart();
      } else {
        menu.errorMessage(data.msg);
      }
    },
    error: function () {},
  });
}

function remove_voucher() {
  $.ajax({
    type: "POST",
    url: "order/removevoucher",
    dataType: "json",
    success: function (data) {
      if (data.code == 1) {
        //   $('.remove_voucher').hide();
        //   $('#voucher_code').show();
        //   $('.apply_voucher').show();

        menu.successMessage(data.msg);
        menu.loadCart();
      } else {
        menu.errorMessage(data.msg);
      }
    },
    error: function () {},
  });
}

function save_address() {
  var street = $("#street").val();
  var city = $("#city").val();
  var state = $("#state").val();
  var zipcode = $("#zipcode").val();
  var country_code = $("#country_code").val();
  var location_name = $("#location_name").val();
  $.ajax({
    type: "POST",
    url: "addressbook/save_addressbook",
    data: {
      street: street,
      city: city,
      state: state,
      zipcode: zipcode,
      country_code: country_code,
      location_name: location_name,
    },
    dataType: "json",
    success: function (data) {
      //alert(data.msg);
    },
    error: function () {},
  });
}

function countrylist() {
  $.ajax({
    url: "site/countrylist",
    success: function (data) {
      $("#country_code").html(data);
    },
  });
}

// $('.payment_option').on('change', function (event) {
// 	$('.change_wrap1').show();
// });

//  $(document).on("click", ".edit_address_book", function () {

// 	$('.address-block').show();
// 	$('#address_book_id').hide();
// });

function getaddress(id) {
  var id = $("#address_book_id").val();
  $(".main-preloader").show();
  $.ajax({
    type: "POST",
    url: "order/addressdata",
    data: { id: id },
    dataType: "JSON",
    success: function (data) {
      if (data.code == 1) {
        $("#street").val(data.details.data.street);
        $("#city").val(data.details.data.city);
        $("#state").val(data.details.data.state);
        $("#zipcode").val(data.details.data.zipcode);
        $(".main-preloader").hide();
      } else {
        //	menu.errorMessage(data.msg);
        $(".main-preloader").hide();
      }
    },
  });
}

function profileImg($this) {
  var formData = new FormData();
  formData.append(
    "file",
    document.querySelector("#validatedCustomFile").files[0]
  );
  $.ajax({
    type: "POST",
    url: "site/uploadprofile",
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
    success: function (data) {
      window.location.reload();
    },
  });
}

function scroll_class(id) {
  if ($("." + id).is(":visible")) {
    $("html,body").animate(
      { scrollTop: $("." + id).offset().top - 100 },
      "slow"
    );
  }
}

removeStorage = function (key) {
  localStorage.removeItem(key);
};

setStorage = function (key, value) {
  localStorage.setItem(key, value);
};

//   function setAsap(){
// 	 var delivery_asap = document.getElementById('delivery_asap');
// 	 is_selected = delivery_asap.checked;
// 	 if (is_selected=="true" || is_selected == true){
// 		 $(".hasTimepicker_deliverytime").val('');
// 		 $(".hasTimepicker_deliverytime").html('');
// 		 removeStorage("delivery_time_set");
// 		 setStorage("delivery_asap_enabled", 1);
// 	 } else {
// 		 setStorage("delivery_asap_enabled", 0);
// 	 }
//  };

function setAsap() {
  $("#delivery_asap")
    .on("change", function () {
      this.value = this.checked ? 1 : 0;
    })
    .change();

  var checkBox = document.getElementById("delivery_asap");
  if (checkBox.checked == 1) {
    $(".hasTimepicker_deliverytime").val("");
    removeStorage("delivery_time_set");
  }
}

$(document).on("change", "#delivery_date", function () {
  var date = $("#delivery_date").val();

dell='0';
if ($('#ms-collection-Basket').is(":checked")){dell='Pickup';dell_type='pickup';pick='Delivery';}else if ($('#ms-delivery-Basket').is(":checked")){dell_type='delivery';dell='Delivery';pick='Pickup';}

//alert(dell);
  $.ajax({
    url: "menu/timelist",
    type: "post",
    data: { date: date ,dell:dell_type},
    success: function (data) {
		
		if(data){$('#not_div').html(' ');$("#proceedOrder").removeClass("disabled-button");		$("#proceedOrder").prop("disabled",false);	
		$("#delivery_time").html(data);}else{
			
			
			
			
		if(dell!=0){
			
			$("#proceedOrder").addClass("disabled-button");	
			mess='<div class="alert alert-danger notifac">'+dell+' time not available, please change to '+pick+'</div>';
			$('#not_div').html(mess);$("#delivery_time").html(data);
			
			
			$("#proceedOrder").prop("disabled", true);
			}	
		}
		
		
		
    },
  });
});

$(document).on("change", "#date_booking", function () {
  var date = $("#date_booking").val();

  $.ajax({
    url: "menu/bookingtimelist",
    type: "post",
    data: { date: date },
    success: function (data) {
      $("#booking_time").html(data);
    },
  });
});

function addReview(order_id) {
  $.ajax({
    type: "POST",
    url: "order/getreview",
    data: { order_id: order_id },
    success: function (html) {
      $("#addreviewmodal").modal("show");
      $("#addreviewmodal").html(html);
    },
    error: function () {},
  });
}

function bookingDetails(id) {
  $.ajax({
    type: "POST",
    url: "order/getBookingDetails",
    data: { booking_id: id },
    success: function (html) {
      $("#bookingtablemodal").modal("show");
      $("#bookingtablemodal").html(html);
    },
    error: function () {},
  });
}

$(document).on("click", "#RadioCollection", function () {
  $(".main-preloader").show();
  var deliveryfee = $("#cart_delivery_fee").val();
  var total = $("#cart_total_detail").val();
  var total = total - deliveryfee;
  var transaction_type = "pickup";
  $(".cart_total_total").text(total);
  $(".delivery-asap").hide();
  $(".delivery-fee-wrap").hide();

  $.ajax({
    type: "POST",
    url: "menu/save_transactionType",
    data: { transaction_type: transaction_type },
    success: function (data) {
      if (menu.menuPage) {
        menu.loadCart();
      } else {
        window.location.reload();
      }
      $(".main-preloader").hide();
    },
    error: function () {},
  });
});

$(document).on("click", "#RadioDelivery", function () {
  $(".main-preloader").show();
  var total = $("#cart_total_detail").val();
  var transaction_type = "delivery";

  $.ajax({
    type: "POST",
    url: "menu/save_transactionType",
    data: { transaction_type: transaction_type },
    success: function (data) {
      if (menu.menuPage) {
        menu.loadCart();
      } else {
        window.location.reload();
      }
      $(".main-preloader").hide();
    },
    error: function () {},
  });
  $(".cart_total_total").text(total);
  $(".delivery-asap").show();
  $(".delivery-fee-wrap").show();
});

$(".payment_option").on("change", function (event) {
  var seleted_payment = $(this).val();
  if (seleted_payment == "cod") {
    $("#order_change").show();
  } else if (seleted_payment == "pyr") {
    $(".payment_option_provider").show();
  } else {
    $("#order_change").hide();
    $(".payment_option_provider").hide();
  }
});

$(document).on("click", ".goto-reviews-tab", function () {
  $(".view-reviews").click();
  scroll_class("view-reviews");
});

$(document).on("click", ".write-review-new", function () {
  if ($(this).hasClass("user_reviews")) {
    $("#order_id").val("");
    $("#review_content").val("");
    $(".review-input-wrap_review").slideToggle("fast");
  } else {
    menu.errorMessage("You must be logged in to leave a review");
  }
});
