let shopping_cart = [];
let favourite_items = [];
let favouriteItems = [];
let tempCart = [];
let cartCount = 0;
const cartBadge = document.querySelector('.cart-badge-container .cart-badge');
console.log(cartBadge);

let iabPay = null;
let iabRef = null;
const inr = '<i class="fa fa-inr"></i>';
const unexpectedError = "Sorry, an unexpected error occurred while processing your request, please try again later.";
const env = "Production";
let base = "";
let fa= "fa fa-inr";
if (env === "Testing") {
  base = "https://localhost/cityneed_backend";
} else if (env === "Production") {
  base = "https://www.dtuat.com/apps/cityneed";
}


    
/***
 * checking and adding smart basket content into sessionStorage.
 */

if (!sessionStorage.smartBasket) {
  sessionStorage.smartBasket = JSON.stringify({
    category_code: 'all',
    category_name: "All"
  });
}

$(document).ready(function () { 

  if (localStorage['shopping-cart-items'] != null) {
    shopping_cart = JSON.parse(localStorage['shopping-cart-items'].toString());
  }

  if (localStorage['favourite-items'] != null) {
    favourite_items = JSON.parse(localStorage['favourite-items'].toString());
  }

  if (shopping_cart.length >= 1) {
    updateCartBadge();
  }

  //call subcategory on click category
  $('#main-container').on('click','.product_category', function(evt) {
    evt.preventDefault();
    var sub = $(this);
    var catid = sub.attr('data-id');
    var catname = sub.attr('data-name');
    var category_code = sub.attr('data-code');
    var category_level = sub.attr('data-level');
    var category_image = sub.attr('data-image');
    localStorage.category_image = category_image;
    localStorage.category_code = category_code;
    localStorage.category_level = category_level;
    localStorage.catname=catname;
    window.location.href = 'category.html';
  });
  //call product by  subcategorycollapsible_subcategory
  $('#main-container').on('click','.product_subcategory', function(evt) {
    // alert(1)
    evt.preventDefault();
    var product = $(this);
    var subcategory_id = product.attr('data-id');
    // alert(subcategory_id);return;
    var subcategory_name = product.attr('data-name');
    var subcategory_code = product.attr('data-code');
    var sub_category_level = product.attr('data-level');
    
    //alert(subcategory_code +','+sub_category_level);
    localStorage.sub_category_code = subcategory_code;
    localStorage.sub_category_level = sub_category_level;
    localStorage.subcategory_name=subcategory_name;
    //console.log()
    window.location.href = 'product.html';
  });
  
      
  //going in subcategories page from index
  $('#main-container').on('click', '.categories-item .thumbnail', function (evt) {
    evt.preventDefault();
    var category = $(this);
    localStorage.category_code = category.attr('data-code');
    console.log(localStorage.category_code);
    localStorage.subcategory_code = 'all';
    localStorage.products_code = 'all';
    localStorage.category_name = category.children('.caption').children('p').text();
    window.location.href = 'products.html';
  });

  $('#main-container').on('click', '.sub_subcategories-list .sub_subcategories-list-item', function (evt) {
    evt.preventDefault();
    console.log('Sub Sub category clicked');
    var sub_subcategory = $(this);
    localStorage.products_code = sub_subcategory.attr('data-code');
    console.log(localStorage.products_code);
    window.location.reload();
  });

  //selecting subcategory and making it work
  $('#main-container').on('click', '.subcategories-list .subcategories-list-item', function (evt) {
    evt.preventDefault();
    console.log('subcategory clicked');
    var subcategory = $(this);
    localStorage.subcategory_code = subcategory.attr('data-code');
    console.log(localStorage.subcategory_code);
    localStorage.products_code = 'all';
    window.location.reload();
  });

  $('.special-categories').on('click', '.products-list .special-product', function () {

    let button = $(this);
    let special_name = button.attr('data-code');
    console.log(special_name);
    localStorage.product_code = special_name;
    window.location.href = "product_details.html";
  });

  //go to wallet add money page
  $('#main-container').on('click', 'button.wallet-add-money', function (evt) {
    evt.preventDefault();

    window.location.href = 'wallet-add-money.html';
  });

  //home to login like amazon with button saying login for better experience

  $('#main-container').on('click', '.gotologin', function (evt) {
    evt.preventDefault();

    window.location.href = 'login.html';
  });

  //redirect to wallet history page

  $('#main-container').on('click', 'button.wallet-history', function (evt) {
    evt.preventDefault();

    window.location.href = 'wallet-history.html';
  });

  //clicking on special button on top of index
  //special products from special products buttons

  $('#main-container').on('click', '.special-buttons button', function (evt) {
    evt.preventDefault();

    let button = $(this);

    let special_name = button.attr('data-name');

    console.log(special_name);

    localStorage.special_name = special_name;

    window.location.href = "feature-product.html";
  });

  $('#main-container').on('click', 'button.more-special', function (evt) {
    evt.preventDefault();

    let button = $(this);
    let special_name = button.attr('data-name');
    console.log(special_name);
    localStorage.special_name = special_name;
    window.location.href = "feature-product.html";
  });

  //update profile function

  $('#main-container').on('click', 'button.update-profile', function (evt) {
    evt.preventDefault();

    let button = $(this);

    let email = button.siblings('input[name="email"]').val();
    let name = button.siblings('input[name="name"]').val();
    let username = button.siblings('input:hidden[name="username"]').val();

    let profile_info = {
      name: name,
      email: email,
      username: username
    };

    console.log(profile_info);

    if (name && email) {
      $.ajax({
        url: 'https://dtuat.com/apps/cityneed/appcode/update_profile.php',
        data: profile_info,
        dataType: 'json',
        type: 'post',
        success: function (response) {
          console.log(response);
          if (response == 'success') {
           alert('Profile Successfully Updated');
            let dat = JSON.parse(localStorage.userDetails.toString());
            dat.name = name;
            dat.email = email;

            localStorage.userDetails = JSON.stringify(dat);
          } else {
           alert('Sorry an unexpected error occured while updating' + ' Your Profile');
          }
        },
        error: function (response) {
          console.log(response);
        }
      });
    }
  });

  $('#main-container').on('click', 'button.update-phone', function (evt) {
    evt.preventDefault();

    var button = $(this);

    var phone = button.siblings('input[name="phone"]').val();
    var newPhone = button.siblings('input[name="new_phone"]').val();
    var username = button.siblings('input:hidden[name="username"]').val();

    var phoneDetails = {
      phone: phone,
      newPhone: newPhone,
      username: username
    };

    //console.log(phoneDetails);

    if (phone && newPhone) {
      $.ajax({
        url: 'https://dtuat.com/apps/cityneed/appcode/update_phone.php',
        data: phoneDetails,
        dataType: 'json',
        type: 'post',
        success: function (response) {
          console.log(response);
          if (response == 'success') {
           alert('Phone No. Successfully Updated');
            var dat = JSON.parse(localStorage.userDetails.toString());
            dat.phone = newPhone;

            localStorage.userDetails = JSON.stringify(dat);
          } else {
           alert('Sorry an unexpected error occured while updating' + ' Your Phone No.');
          }
        },
        error: function (response) {
          console.log(response);
        }
      });
    }
  });


  //login and logout checking
  var username = localStorage.username;
  var loginStatus = localStorage.loginStatus;
  var login_item = $('#slide-out').children('li').children('.login-item');
  var myAccount = $('#slide-out').children('li').children('.my-account');
  var login = localStorage.login;
  if (username == null && loginStatus == null) {
    // console.log("There is no username is memory.");
    // console.log("user not login");
  } else if (username != null && loginStatus == 'A' && localStorage.login == 'true') {

    // console.log("THere is a username is memmory.");
    login_item.empty().append(
      "<i class='ion-android-exit'> </i> Logout");

    login_item.on('click', function () {
      localStorage.username = "";
      localStorage.loginStatus = "";
      localStorage.login = false;
      localStorage.removeItem('username');
      localStorage.removeItem('loginStatus');
      localStorage.removeItem('login');
      localStorage.removeItem('userDetails');
      window.location.href = "index.html";

      window.plugins.toast.showWithOptions({
        message: "You Have Been logged out successfully.",
        duration: "short", // 2000 ms
        position: "bottom"
      });
    });
  }

  if (username != null && loginStatus == 'A' && login == 'true') {

  } else {
    myAccount.parent().remove();
  }

  $('#main-container').on('click', '.wallet-button', function (evt) {
    evt.preventDefault();

    var button = $(this);

    var amount = button.val();
    console.log(amount);

    button.parent().siblings().children('input[name="wallet-amount"]').empty().val(amount);
  });

  //continue shopping function page

  $('body').on('click', '.continue-shopping', function (evt) {
    evt.preventDefault();

    console.log("continue hah");
    window.location.href = 'index.html';
  });

  //order details functionality start from here

  $('#main-container').on('click', '.order_detail', function (evt) {
    evt.preventDefault();

    var clicked = $(this);

    var id = clicked.attr('data-id');

    localStorage.order_id = id;
    window.location.href = 'order-details.html';
  });

  //cancel order request functionality

  $('#main-container').on('click', '.cancel_order', function (evt) {
    evt.preventDefault();
//alert(1);
    var button = $(this);
    var id = $(this).attr('data-id');
    console.log(id);
    id = {id: id};

    var d = navigator.notification.confirm("Are you sure you want to submit cancilation request.", cancel_order,
      'Confirm Cancilation request', 'Yes,No');
//return;

    function cancel_order(buttonIndex) {

      if (buttonIndex == 1) {
        $.ajax({
          url: 'https://dtuat.com/apps/cityneed/appcode/cancel_order.php',
          type: 'post',
          dataType: 'json',
          data: id,
          beforeSend: function () {
            $('.supreme-container').show();
          },
          success: function (response) {
            console.log(response);
            if (response == 1) {
             alert("Order Cancilation has been requested successfully.");
			  window.location.href="order.html";
            } else {
             alert('Sorry There is an unexpected error occured while processing  your request.');
            }
          },
          error: function (response) {
            console.log(response);
          },
          complete: function () {
            $('.supreme-container').hide();
          }
        });
      }
    }
  });
  
  
  
  
  
    $('#main-container').on('click', '.cancel_order1', function (evt) {
    evt.preventDefault();
//alert(1);
    var button = $(this);
    var id = $(this).attr('data-id');
    console.log(id);
    id = {id: id};

    var d = navigator.notification.confirm("The order has already been packed. So there will be 30% penalty on cancellation. Do you want to proceed with cancellation?", cancel_order,
      'Confirm Cancilation request', 'Yes,No');
//return;

    function cancel_order(buttonIndex) {

      if (buttonIndex == 1) {
        $.ajax({
          url: 'https://dtuat.com/apps/cityneed/appcode/cancel_order1.php',
          type: 'post',
          dataType: 'json',
          data: id,
          beforeSend: function () {
            $('.supreme-container').show();
          },
          success: function (response) {
            console.log(response);
            if (response == 1) {
             alert("Order Cancilation has been requested successfully.");
			  window.location.href="order.html";
            } else {
             alert('Sorry There is an unexpected error occured while processing  your request.');
            }
          },
          error: function (response) {
            console.log(response);
          },
          complete: function () {
            $('.supreme-container').hide();
          }
        });
      }
    }
  });

  //on click on a specific product functionality

  /*$('#main-container').on('click', '.products-list .product', function (evt) {
    evt.preventDefault();

    var product = $(this);
    var code = product.parent().parent().attr('data-code');

    console.log(code);
    localStorage.product_code = code;
    window.location.href = "product_details.html";
  });*/

  //item reorder from order history details page

  $('#main-container').on('click', '.reorder_this', function (evt) {
    evt.preventDefault();

    var reorder = $(this);

    var product_code = reorder.parent().parent().attr('data-code');
    console.log(product_code);

    product_code = {code: product_code};
  });

  //outter add to cart button and function a.k.a. products page add to cart product

  $('#main-container').on('click', '.outter-addtocart-image', function (evt) {
    evt.preventDefault();

    var cart_button = $(this);

    var element = cart_button.parent().parent().parent().parent();
    var code = element.attr('data-code');
    var gst = element.attr('data-gst');
    var name = element.find('.product_name').text();
    var image = element.find('.product_image_preview').attr('src');
    var price = element.find('.product-price').text();
    var quantity = 1;
    var doesExist = false;

    if (shopping_cart.length > 0) {
      $.each(shopping_cart, function (index, item) {
        if (code == item.product_code) {
          doesExist = true;
          return false;
        }
      });
    }

    if (!doesExist) {
      addToCart(code, name, image, price, quantity, gst);
    } else {
      incrementCartItem(code);
    }
  });

  //inner add to cart functionality first
  //plus button function
  /*
    $('#main-container').on('click', '.cart-options .inner-quan-plus', function (evt) {
      evt.preventDefault();

      var plus = $(this);

      var current_quan = plus.siblings('.inner-quan-show');
      var current_quantity = parseInt(current_quan.text());

      current_quantity++;

      current_quan.text(current_quantity);
    });

    //inner add to cart functionality
    //minus button function

    $('#main-container').on('click', '.cart-options .inner-quan-minus', function (evt) {
      evt.preventDefault();

      var minus = $(this);

      var current_quan = minus.siblings('.inner-quan-show');
      var current_quantity = parseInt(current_quan.text());

      current_quantity--;

      current_quan.text(current_quantity);
    });*/

  $('#main-container').on('click', '.cart-options #addToCartInner', function (evt) {
    evt.preventDefault();

    console.log('adding');
    var cart_button = $(this);

    var element = cart_button.parent().parent();
    var code = element.attr('data-code');
    var gst = element.attr('data-gst');
    var name = element.children('.product-heading').text();
    var image = element.children('.product-image').attr('src');
    var price = element.children('.inner-product-details').attr('data-price');
    var quantity = parseInt(element.find('.inner-quan-show').text());

    addToCart(code, name, image, price, quantity, gst);
  });

  $('#main-container').on('click', '.outter-controls .plus-quan', function (evt) {// alert(1);
    console.log('plus');
    evt.preventDefault();

    var plus_button = $(this);

    var quan = $(plus_button).siblings('.show-quan');
    var quantity = parseInt($(quan).text());

    console.log(quantity);

    quantity++;

    if (quantity < 1) {
      replaceButtons(plus_button);
    } else {
      console.log(quantity);
      $(quan).text(quantity);
      var element = $(plus_button).parent().parent().parent().parent().parent();
      var code = $(element).attr('data-code');
      doToCartByOne(element, quantity, code, 'add');
    }
  });

  $('#main-container').on('click', '.outter-controls .minus-quan', function (evt) { //alert(0);
    console.log('minus');
    evt.preventDefault();

    var minus_button = $(this);

    var quan = $(minus_button).siblings('.show-quan');
    var quantity = parseInt($(quan).text());

    console.log(quantity);

    quantity--;

    if (quantity < 1) {
      replaceButtons(minus_button);
    } else {
      console.log(quantity);
      $(quan).text(quantity);
      var element = $(plus_button).parent().parent().parent().parent().parent();
      var code = $(element).attr('data-code');
      doToCartByOne(element, quantity, code, 'remove');
    }
  });

  //cart change quantity functionality

  //cart plus quantity functionality 

  $('#main-container').on('click', '.cart-quan-plus', function (evt) {
    evt.preventDefault();

    var e = $(this).siblings('.cart-quan-show');
    var ea = parseInt(e.text());
    ea++;
    e.text(ea);

    var quantity = parseInt(e.text());
    var code = e.parent().parent().parent().parent().parent().parent().attr('data-code');


    changeQuantity(quantity, code);

    var total = 0;
    var totalAfterGst = 0;

    for (var i in shopping_cart) {
      total += shopping_cart[i].product_price * shopping_cart[i].product_quantity;
      totalAfterGst += shopping_cart[i].product_after_gst * shopping_cart[i].product_quantity;
    }

    $('.normal_price').children('span').children('b').empty().append(inr + total)
      .children('i').addClass('p-font');

    $('.price_after_gst').children('span').children('b').empty().append(inr + totalAfterGst)
      .children('i').addClass('p-font');

    // console.log(total);
  });

  //cart minus quantity functionality

  $('#main-container').on('click', '.cart-quan-minus', function (evt) {
    evt.preventDefault();

    var e = $(this).siblings('.cart-quan-show');
    var ea = parseInt(e.text());
    ea--;
    e.text(ea);

    var quantity = parseInt(e.text());
    var code = e.parent().parent().parent().parent().parent().parent().attr('data-code');

    changeQuantity(quantity, code);

    var total = 0;
    var totalAfterGst = 0;

    for (var i in shopping_cart) {
      total += shopping_cart[i].product_price * shopping_cart[i].product_quantity;
      totalAfterGst += shopping_cart[i].product_after_gst * shopping_cart[i].product_quantity;
    }

    $('.normal_price').children('span').children('b').empty().append(inr + total)
      .children('i').addClass('p-font');

    $('.price_after_gst').children('span').children('b').empty().append(inr + totalAfterGst)
      .children('i').addClass('p-font');

    // console.log(total);
  });

  //reorder all working starts here

  $('body').on('click', '.reorder_all', function (evt) {
    evt.preventDefault();

    var button = $(this);
    var uniqueId = button.attr('data-id');

    uniqueId = {id: uniqueId};
    console.log(uniqueId);
    var tempItems = [];

    $.ajax({
      url: 'https://dtuat.com/apps/cityneed/appcode/fetch_these_orders.php',
      type: 'post',
      data: uniqueId,
      dataType: 'json',
      success: function (response) {
        console.log(response);

        $.each(response, function (index, item) {
			var gst = parseInt(item.gst);
			var price = parseInt(item.price);
			var quantity = 1;
			var code = item.product_code;
			var	name =item.name;
			var	price =item.price;
			var	img = 'https://dtuat.com/apps/cityneed/img/'+item.photo_link;
			var	gst = item.gst;
			var size = item.size;
          
		  addToCart(code, name, img, price, quantity, gst, size);
        });
      },
      error: function (response) {
        console.log(response);
      }
    });
  });
  
  
///view map 


  $('body').on('click', '.view_map', function (evt) {
    evt.preventDefault();

    var button = $(this);
    var uniqueId = button.attr('data-id');

    uniqueId = {id: uniqueId};
    console.log(uniqueId);
    var tempItems = [];
    $.ajax({
      url: 'https://dtuat.com/apps/cityneed/appcode/fetch_map.php',
      type: 'post',
      data: uniqueId,
      dataType: 'json',
      success: function (response) {
        console.log(response);

        $.each(response, function (index, item) {
			var gst = parseInt(item.gst);
			var price = parseInt(item.price);
			var quantity = 1;
			var code = item.product_code;
			var	name =item.name;
			var	price =item.price;
			var	img = 'https://dtuat.com/apps/cityneed/img/'+item.photo_link;
			var	gst = item.gst;
			var size = item.size;
          
		  addToCart(code, name, img, price, quantity, gst, size);
        });
      },
      error: function (response) {
        console.log(response);
      }
    });
  });  
  
  
});
//document.ready ends above

//random string generator

function randomString(length = 40, chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
  let result = '';
  for (let i = length; i > 0; --i) result += chars[Math.floor(
    Math.random() * chars.length)];
  return result;
}

/*** get fetch request ***/
const getFetchRequest = (url) => {
  return new Promise((resolve, reject) => {

    let fetchPram = {
      credentials: "same-origin",
      method: "GET",
      headers: {
        'Accept': 'application/json',
        "Content-Type": "application/json"
      },
    };

    fetch(base + url, fetchPram)
      .then((response) => response.json())
      .then((responseData) => {
        resolve(responseData);
      })
      .catch((error) => {
        console.log("error");
        console.dir(error);
        reject(error);
      });
  });
};

/*** post fetch request ***/
const postFetchRequest = (url, data = undefined) => {
  return new Promise((resolve, reject) => {

    let fetchPram = {
      credentials: "same-origin",
      method: "POST",
      headers: {
        'Accept': 'application/json',
        "Content-Type": "application/json"
      },
      body: JSON.stringify({data: data})
    };

    fetch(base + url, fetchPram)
      .then((response) => response.json())
      .then((responseData) => {
        resolve(responseData);
      })
      .catch((error) => {
        reject(error);
      });
  });
};


function doItemCalc(price, quantity, gst, couponDiscount) {
  let total = [];

  total['item_price'] = parseFloat(price);
  total['item_total_price'] = parseFloat(price) * parseFloat(quantity);
  var coupon_dis_amt = (parseInt(total['item_total_price']) / 100) * parseInt(couponDiscount);
  // localStorage.coupon_dis_amt = coupon_dis_amt;
  if (parseInt(couponDiscount)) {
    total['item_discount_amount'] = (parseInt(total['item_total_price']) / 100) * parseInt(couponDiscount);
    total['item_total_after_discount'] = parseInt(total['item_total_price']) - ((parseInt(total['item_total_price']) / 100) * parseInt(couponDiscount));
  } else {
    total['item_discount_amount'] = 0;
    total['item_total_after_discount'] = total['item_total_price'];
  }
  total['item_gst_amount'] = ((total['item_total_after_discount'] / 100) * parseInt(gst));
  total['item_total_after_gst'] = total['item_total_after_discount'] + ((total['item_total_after_discount'] / 100) * parseInt(gst));

  return total;
}



// $('.main-container').on('click', '.special-products', function () { alert(1);
  function viewBagDetailss(thi){
     // alert(0);
      var favourite_button = $(thi).children();
          //console.log($(thi).children());
        var product_code = $(thi).children('.add-to-favourites').attr('data-code');
        var name = $(thi).children('.add-to-favourites').attr('data-name');
        var size = $(thi).children('.add-to-favourites').attr('data-size');
        var id =  $(thi).children('.add-to-favourites').attr('data-id');
        var price =  $(thi).children('.add-to-favourites').attr('data-price');
        // var product_code =  $(this).parent().children('.add-to-favourite');
        

        // var imageSrc = favourite_button.siblings('img').attr('src');
        var imageSrc = $(thi).children('.add-to-favourites').attr('data-img');
        // console.log(id);
        var favouriteItem = {
        id: id,
        src: imageSrc,
        name: name,
        //mrp: mrp,
        price: price,
        product_code: product_code,
        size: size
      };

      console.log(favouriteItem);
      var exist ;
      exist = false;
      if (localStorage['favourite-items'] != null) {
          favouriteItems = JSON.parse(localStorage['favourite-items'].toString());
        }
        console.log('1');
            if (favouriteItems =>1)
            {
                console.log('2');
              var new_arr = new Array();
              exist=false;
              
              $.each(favouriteItems, function (index, value) {
                var name = value.name ;
                if (value.id == favouriteItem.id) {
                  window.plugins.toast.showWithOptions({
                    message: "Item is removed from your favourite list.",
                    duration: "short", // 2000 ms
                    position: "bottom",
                    styling: {
                      opacity: 1, //you can change it to your value.  0.0 (transparent) to 1.0 (opaque). Default 0.8
                      backgroundColor: '#666666', // make sure you use #RRGGBB. Default #333333
                      textColor: '#ffffff', // Ditto. Default #FFFFFF
                      textSize: 20.5, // Default is approx. 13.
                      cornerRadius: 16, // minimum is 0 (square). iOS default 20, Android default 100
                      horizontalPadding: 20, // iOS default 16, Android default 50
                      verticalPadding: 16 // iOS default 12, Android default 30
                    }
                  });
                  favourite_button.css("color", "#8cc516");
                  
                  console.log(
                    "Item is removed from your favourite list.");
                  exist = true;
                  //return false;
                }
                 else {
                  new_arr.push(value);
                  favourite_button.css("color", "red");
                }
            });
                console.log(new_arr);
            localStorage['favourite-items'] = JSON.stringify(new_arr);

            }

            if (!exist) {
              console.log("ttttt");
              console.log(favouriteItem);
              favouriteItems.push(favouriteItem);
              console.log(favouriteItems);
              window.plugins.toast.showWithOptions({
                message: "Item is Added in your favourite list.",
                duration: "short", // 2000 ms
                position: "bottom",
                styling: {
                  opacity: 1, //you can change it to your value.  0.0 (transparent) to 1.0 (opaque). Default 0.8
                  backgroundColor: '#666666', // make sure you use #RRGGBB. Default #333333
                  textColor: '#ffffff', // Ditto. Default #FFFFFF
                  textSize: 20.5, // Default is approx. 13.
                  cornerRadius: 16, // minimum is 0 (square). iOS default 20, Android default 100
                  horizontalPadding: 20, // iOS default 16, Android default 50
                  verticalPadding: 16 // iOS default 12, Android default 30
                }
              });
              localStorage['favourite-items'] = JSON.stringify(favouriteItems);
              favourite_button.css("color","red");

            }

        
       // localStorage['favourite-items'] = JSON.stringify(favouriteItems);
  }


 $(document).ready(function(){

  $('.main-container').on('click', '.add-to-favourite', function () { //alert(1);
        var favourite_button = $(this);
          //console.log($(this).parent().children('.add-to-favourite').attr('data-code'));
        var product_code = $(this).parent().children('.add-to-favourite').attr('data-code');
        var name = $(this).parent().children('.add-to-favourite').attr('data-name');
        var size = $(this).parent().children('.add-to-favourite').attr('data-size');
        var price = $(this).parent().children('.add-to-favourite').attr('data-price');
         var id =  $(this).parent().children('.add-to-favourite').attr('data-id');
        // var product_code =  $(this).parent().children('.add-to-favourite');     
        // var imageSrc = favourite_button.siblings('img').attr('src');
        var imageSrc = $(this).parent().children('.add-to-favourite').attr('data-img');
        // console.log(imageSrc);
        // var favouriteItem = {
        //   size: size,
        //   src: imageSrc,
        //   name: name,
        //   product_code: product_code
        // };
        //console.log(favouriteItem);
        var favouriteItem = {
        id: id,
        src: imageSrc,
        name: name,
        //mrp: mrp,
        price: price,
        product_code: product_code,
        size: size
      };

     // console.log(favouriteItem); 
     // return;
      var exist ;
        exist = false;
  if (localStorage['favourite-items'] != null) {
      favouriteItems = JSON.parse(localStorage['favourite-items'].toString());
    }
    //console.log('1');
    console.log(favouriteItems);
        if (favouriteItems.length >=1)
        {
            //console.log('2');
          var new_arr = new Array();
          exist=false;
          $.each(favouriteItems, function (index, value) {
            var name = value.name ;
            if (value.id == favouriteItem.id) {
            //alert(value.id +"=="+ favouriteItem.id)
              window.plugins.toast.showWithOptions({
                message: "Item is removed from your favourite list.",
                duration: "short", // 2000 ms
                position: "bottom",
                styling: {
                  opacity: 1, //you can change it to your value.  0.0 (transparent) to 1.0 (opaque). Default 0.8
                  backgroundColor: '#f5f5f5', // make sure you use #RRGGBB. Default #333333
                  textColor: '#000000', // Ditto. Default #FFFFFF
                  textSize: 15.5, // Default is approx. 13.
                  cornerRadius: 16, // minimum is 0 (square). iOS default 20, Android default 100
                  horizontalPadding: 20, // iOS default 16, Android default 50
                  verticalPadding: 16 // iOS default 12, Android default 30
                }
              });
              favourite_button.css("color", "#1bcb22");
              console.log("Item is removed from your favourite list.");
              exist = true;
              //return false;
            }
             else {
            new_arr.push(value);  
            }
        });
            console.log(new_arr);
        localStorage['favourite-items'] = JSON.stringify(new_arr);

        }

      if (!exist) {
        console.log("ttttt");
        //console.log(favouriteItem);
        favouriteItems.push(favouriteItem);
        console.log(favouriteItems);
        window.plugins.toast.showWithOptions({
          message: "Item is Added in your favourite list.",
          duration: "short", // 2000 ms
          position: "bottom",
          styling: {
            opacity: 1, //you can change it to your value.  0.0 (transparent) to 1.0 (opaque). Default 0.8
            backgroundColor: '#f5f5f5', // make sure you use #RRGGBB. Default #333333
            textColor: '#000000', // Ditto. Default #FFFFFF
            textSize: 15.5, // Default is approx. 13.
            cornerRadius: 16, // minimum is 0 (square). iOS default 20, Android default 100
            horizontalPadding: 20, // iOS default 16, Android default 50
            verticalPadding: 16 // iOS default 12, Android default 30
          }
        });
        localStorage['favourite-items'] = JSON.stringify(
        favouriteItems);
        favourite_button.css("color","red");
        //wish_button.addClass("red-text");
        

    }
     });
        
 });
     
// Wishlist ........
//wishlist
    function displayFavouriteItems() {//alert(0);
    //if(localStorage.loginStatus == 'A' && localStorage.login == '1'){
    var htmlString = "";
    var emptyCart ='';
    var img = base + "/appcode/img/";
    if(localStorage.loginStatus == 'A' && localStorage.login == 1){ //alert(1);
    if(localStorage['favourite-items'] != null && localStorage['favourite-items'].length > 2) { 
        favouriteItems = JSON.parse(localStorage['favourite-items'].toString());
        console.log(favouriteItems);
        $.each(favouriteItems, function (index, item) {
          var name= item.name;
        htmlString += '<div class="col s12 wishlist_product card" onclick="viewProductDetails(this)" data-id="' + item.id + '" data-code="' + item.product_code + '" data-name="' + item.name + '" data-price="' +  item.price + '" data-size="' + item.size + '" data-mrp="' + item.mrp + '" data-image="'+ item.src + '" >';
        
        htmlString += '<div class = "col s3">';
        htmlString += '<img src="'+item.src+'" class="responsive-img" style="margin-top:22px;">';
        htmlString += '</div>';   
        htmlString += '<div class="col s6 wishlist_show">';
        htmlString += '<p class="header product_names"><b>'+item.name+'</b></p>';
        // htmlString += '<span class="availables">Availablity : </span> <span class="stock">In stock</span><br>';
        htmlString += '<span class="wish_price">Our Price : </span><span class="price"><i class="fa fa-inr p-font"></i>'+item.price+'.00</></span><br> ';
        //htmlString += '<span class="wish_mrp">Mrp: </span><span class="price"><i class="fa fa-inr p-font"></i> '+item.mrp+'.00</></span><br> ';
        htmlString +='<span style="margin-left: 7px;">Weight : </span>';
          htmlString +='<span id="size_color">'+ item.size+'</span>';
         
        htmlString += '</div>';
        htmlString += '<div class="col s3 wishlist_btn" style="margin: 5px 0px 0px 0px;">';
        htmlString += '<span class="heart_fa">';
        htmlString += '<i class="fa fa-heart right fa-2x red-text"></i>';
        htmlString += '</span>';
        htmlString += '</div>';
        
        htmlString += '<div class="remove_wishlist" style="" data-code="' + item.product_code + '" data-price="'+item.price+'" data-id="'+item.id+'">';
        htmlString += '<p style="float: right; margin: 30px 15px 0px 0px;"><i class="fa fa-trash" data-code="' + item.product_code + '" data-price="'+item.price+'" data-id="'+item.id+'" aria-hidden="true"></i></p>';
        htmlString += '</div>'; 
        htmlString += '</div>';
        //htmlString += '</div>'; 
       

            $(document).ready(function(){
        $('select').material_select();
      });   
    });
    $('.wishlist').append(htmlString);
  }
  
  else{
    emptyCart+='<div class="" style="position: relative;margin-top:50%;text-align: center;">';
    emptyCart+='<img src="img/heart.png" class="responsive-img" style="height:50px ;width:50px;">';
    emptyCart+='<h6><b>Wishlist</b></h6>';
    emptyCart+='<p>Please  add items to wishlist</p><br>';
    
  
    //emptyCart+='<button class="btn waves-effect waves-light center-align" style="background-color: #40a745;" type="submit" name="action"></button>';
    emptyCart+='</div>';   
    $('.wishlist').empty().append(emptyCart);
  }
}else{
    emptyCart+='<div class="" style="position: relative;margin-top:50%;text-align: center;">';
    emptyCart+='<img src="img/heart.png" class="responsive-img" style="height:50px ;width:50px;">';
    emptyCart+='<h6><b>Wishlist</b></h6>';
    emptyCart+='<p style="color:red;">!!! Please login To Display Wishlist. !!!</p><br>';
    emptyCart+='</div>';   
    $('.wishlist').empty().append(emptyCart);
  
}
}
//Remove wishlist item
  $(document).ready(function() {
    $('#main-container').on('click', '.fa-trash', function(evt) { //alert(1)
      var remove = $(this);
      console.log(remove);
      var code = remove.attr('data-code');
      var id = remove.attr('data-id');
      var price = remove.attr('data-price');
      removefavitem(id)
    });
  });

//end 
//Remove wishlist item
function removefavitem(id) {

  favourite_items = JSON.parse(localStorage['favourite-items'].toString());
  for (var i = 0; i < favourite_items.length; i++) {
    var cur = favourite_items[i];
    if (cur.id == id) {
      favourite_items.splice(i, 1);
      break;
    }
  }
  localStorage['favourite-items'] = JSON.stringify(favourite_items);

  // updatePrice();
  location.reload();

  if (localStorage['favourite-items'].length < 1 &&
    favourite_items.length == 0) {

  }
}


//  function displayFavouriteItems() {

//   if (localStorage['favourite-items'] != null) {
//     favouriteItems = JSON.parse(localStorage['favourite-items'].toString());
//     var img = base + "/img/";

//     // $(".store-cart-1").html("");
//     var htmlString1 = "";
//     var htmlString = "";
//     //alert(favouriteItems);
//     //console.log(favouriteItems);
//     $.each(favouriteItems, function (index, item) {
//       console.log(item);
//       htmlString += "<div class='card horizontal list-item' onclick='viewProductDetails(this)' data-code="+item.product_code+" data-id='"+item.id+"'>";
//       htmlString += "<div class='card-image image'>";
//       htmlString += "<img src='" +item.src+"' class='thumbnail'>";
//       htmlString += "</div>";
//       htmlString += "<div class='card-stacked'>";
//       htmlString += "<div class='card-content favourite-content'>";
//       htmlString += "<p class='heading'>" + item.name + "</p>";
//       // htmlString += "<p class='sub-heading'>" + item.name + "</p>";
//        htmlString += "<div class='row col s6'>";
//        htmlString += "<div class='row'>";
//       htmlString +=
//         "<a class='buy-now waves-effect btn' style='background:#0cb30cbf;border-radius:5px;line-height:2;' name='buy-now' product_code='" + item.product_code + "' id='" + item.id + "'>";
//       //htmlString += "<i class='ion-android-information'></i>";
//       htmlString += "<i class='fa fa-eye' style='font-size: 12px !important;'>View Details</i></a>";
//        htmlString += "</div>";
//       htmlString += "<div class='row'>";
//       htmlString +=
//         "<a class='buy-now waves-effect btn' style='background:#ff0000;border-radius:5px;line-height:2;' name='buy-now' product_code='" + item.product_code + "' id='" + item.id + "'>";
//       //htmlString += "<i class='ion-android-information'></i>";
//       htmlString += "<i class='fa fa-trash' style='font-size: 12px !important;'>Remove</i></a>";
//        htmlString += "</div>";
//       htmlString += "</div></div></div></div>";
//     });

//     $('#main-container').append(htmlString);
//   }
// }



/*** shopping cart starts here ***/
const displayShoppingCart = () => {

  /*** checking if coupon applicable then go else remove the coupon ***
   if(localStorage.coupon_applied) {

  }
   **/

  let htmlString = '';
  let footer = '';
  let total = 0;
  let subTotal = 0;
  let gstAmount = 0;
  let coupon = '';
  let couponDiscount = 0;
  var maxdiscount = 0;
  var total_commission = 0;
  var total_cart_item = localStorage.countItems;
  if (localStorage.coupon_applied) {
    //alert()
    coupon = JSON.parse(localStorage['coupon_applied'].toString());
    console.log(coupon)
    var coupon_code = coupon.coupon_code;
    localStorage.coupon_code = coupon_code;
    console.log();
    couponDiscount = coupon.total_discount;
    maxdiscount = coupon.max_discount;
    // console.log(coupon);
    // alert(couponDiscount)
  }
  if (sessionStorage.pre_coupon) {
    let preCoupon = JSON.parse(sessionStorage['pre_coupon'].toString());
    if (findCartTotal() >= parseInt(preCoupon.min_limit)) {
      localStorage['coupon_applied'] = JSON.parse(sessionStorage['pre_coupon'].toString());
      window.location.reload();
    } else {
      let remainingAmount = parseInt(preCoupon.min_limit) - findCartTotal();
      alert(`Please add products of Rs. ${remainingAmount} in your cart to avail your offer discount.`);
    }
  }
  let final_buttons = '';
  let totalAfterGst = 0;

  if (localStorage['shopping-cart-items'] != null && localStorage['shopping-cart-items'].length > 2) {
    let shopping_cart = JSON.parse(localStorage['shopping-cart-items'].toString());
    console.log(shopping_cart);

    $.each(shopping_cart, function (index, item) {        
          // alert(item.product_vendor_phone);
      htmlString += `<div class="cart-items" style="" >
        <div class="item card" style="background-color: white;" data-code="${item.product_code}" data-price="${item.product_price}" 
          data-quantity="${item.product_quantity}" data-name="${item.product_name}" data-vendor_phone="${item.product_vendor_phone}">
          <div class="item-image">
            <img src="${item.product_image}" alt="${item.product_name}" style="margin: 35px 0px 0px 0px;">
          </div>
          <div class="item-detail">
            <div class="details">
              <span class="name" style ="font-size:15px;">${item.product_name}</span>
              <span class="quantity">Quantity: ${item.product_quantity}</span>
            </div>`;
      if(item.product_size!=''){
        htmlString+=`<p>Size:${item.product_size}</p>`;
      }     
            htmlString += `<span class="price">Price:<i class="fa fa-inr"></i>${item.product_price}</span>
            <div class="cart-quantity-control card" style="color: white;
    width: 40%;
    background: #689f39;
    border-radius: 5px;
    height: 25px;
    align-items: center;">
             <div class="cart-item-minus" data-code="${item.product_code}"  data-size="${item.product_size}" data-quantity="${item.product_quantity}"
                onclick="cartQuantityDecrement(this)">
                <i class="fa fa-minus p-font"></i>
              </div>
              
              <span class="cart-item-quantity">${item.product_quantity}</span>

               <div class="cart-item-plus" data-code="${item.product_code}" data-size="${item.product_size}" data-quantity="${item.product_quantity}" data-qty="${item.product_qty}"
                onclick="cartQuantityIncrement(this)">
                <i class="fa fa-plus p-font"></i>
              </div>
              
            </div>
          </div>
          <div class="item-delete card" onclick="removeFromCart(this);">
            <i class="fa fa-trash-o"></i>
          </div>
        </div>
      </div>`;
      let fetchedTotal = doItemCalc(item.product_price, item.product_quantity, item.product_gst, couponDiscount);
      gstAmount += parseFloat(fetchedTotal.item_gst_amount);
      // total += (item.product_price * item.product_quantity);
       subTotal += parseFloat(fetchedTotal.item_total_price);
        total += parseFloat(fetchedTotal.item_total_after_gst) ;       
      /*totalAfterGst += (item.product_after_gst * item.product_quantity);*/
      total_commission = (subTotal* item.product_commission/100);
	  localStorage.total_commission = total_commission;
    localStorage.subTotal = subTotal;
    });


  if(subTotal < localStorage.charged_order_amt){
    var del_charges = localStorage.delivery_ch;
    localStorage.del_charges = del_charges
    var total1 = parseInt(subTotal) + parseInt(del_charges);
    localStorage.total1 = total1;
    // alert("total"+total1);
    // alert("subTotal"+subTotal);

  }else{
    var del_charges = 0.00;
    localStorage.del_charges = del_charges;


    var total1 = subTotal;
    localStorage.total1 = total1;
  }
//alert(localStorage.delivery_ch);
console.log(parseFloat(subTotal) <= parseFloat(coupon.min_limit));
    if (!coupon || (parseFloat(subTotal) <= parseFloat(coupon.min_limit))) { //alert(3);
     // localStorage.removeItem('coupon_applied');
      if(localStorage.coupon_applied){

        // localStorage.coupon_code;
        // localStorage.dis_amount;
        htmlString += `
          <div class="input-field center-align hide">
            <button class="btn btn-teal-outline" style="border-radius: 10px 10px; background: #689f39;" type="button" onclick="window.location.href='coupons.html'">
              Apply Coupon
            </button>
          </div>`;
      }else{
        htmlString += `
          <div class="input-field center-align">
            <button class="btn btn-teal-outline" style="border-radius: 10px 10px; background: #689f39;" type="button" onclick="window.location.href='coupons.html'">
              Apply Coupon
            </button>
          </div>`;
      }
    }
    if(localStorage['cashback']){
      footer +='<div class="row" style="margin:10px;">';
      footer +='<div class="col s12" style="display:flex;justify-content:space-between;padding: 10px;background: #ccc;">';
      footer +='<div class ="text">';
      footer +='<p style="color:green">Cashback code applied</p>';
      footer +='</div>';
      footer +='<div class="icon" onclick="emptyCashback1(this)">';
      footer +='<i class="ion-android-close right">';
      footer +='</i>';
      footer +='</div>';
      footer +='</div>';
      footer +='</div>';
    }
    if(localStorage.pin){
      htmlString += `
          <div class="row center-align">     
            <div class="col s12">
              <input class="btn btn-teal-outline" onclick="remove_pin();" style="border-radius: 10px 10px; background: red;margin-bottom: 16px;margin-top: 6px;" type="button" value="Changed Pin">
            </div>
          </div>`;

    }else{
           htmlString += `
          <div class="row center-align">
      
      <div class="col s6">
      <input type="number" name="pin" id="pin"  placeholder="Enter Pincode">
      </div>
      <div class="col s6">
            <input class="btn btn-teal-outline check_pin" style="border-radius: 10px 10px; background: green;margin-bottom: 16px;margin-top: 6px;" type="button" value="submit">
            </div>
          </div>`;
    }
   if(localStorage.coupon_applied){
    // htmlString +=`<div class="input-field center-align">
    //     <div>
    //     <p>Coupon Code Applied Successfully</p>
    //     <i class="ion-android-close right"></i>
    //      </div>
    //     </div>`;
     htmlString +='<div class="row" style="margin:20px;">';
     htmlString +='<div class="col s12" style="display: flex; justify-content: space-between; padding: 1px; background: #cccccc59; border: 1px solid; border-radius: 25px 25px; height: 50px;">';
     htmlString +='<div class ="text" style="margin: 0px 0px 0px 10px;">';
     htmlString +='<p style="color:green">Coupon code applied</p>';
     htmlString +='</div>';
     htmlString +='<div class="icon" style="margin: 5px 10px 0px 0px;" onclick="emptyCoupon1(this)">';
     htmlString +='<i class="ion-android-close right">';
     htmlString +='</i>';
     htmlString +='</div>';
     htmlString +='</div>';
     htmlString +='</div>';
   }

    

    footer += `
    <div class="cart-summary card">
      <u><h5 class="third-color heading">Order Summary</h5></u>
      <div class="subtotal total-container">
        <span class="text">Commission</span>
        <span class="price">
          <i class="fa fa-inr p-font"></i>${total_commission.toFixed(2)}</span>
      </div>`;
	  
	  footer +=`<div class="subtotal total-container">
        <span class="text">Sub Total</span>
        <span class="price">
          <i class="fa fa-inr p-font"></i>${subTotal.toFixed(2)}</span>
      </div>`;

    if (coupon) {
       couponDiscount = parseFloat(coupon.total_discount);
      var dis = parseFloat(couponDiscount) * parseFloat(subTotal)/100;
      if(dis<maxdiscount){
       var dis_amount = dis;
       localStorage.dis_amount = dis_amount;
      } else{
        var dis_amount = maxdiscount;
       localStorage.dis_amount = dis_amount;

      }

      total =(parseFloat(subTotal) - parseFloat(dis_amount));
      localStorage.total = total;
      

      // g_total = parseInt(localStorage.total)+parseInt(localStorage.delivery_ch);
      // localStorage.g_total = g_total;
      // alert(localStorage.g_total);
      // alert(g_total);



      footer += `
      <div class="subtotal total-container">
        <span class="text">Total Coupon Discount</span>
        <span class="price">
          <i class="fa fa-inr p-font"></i>${parseFloat(dis_amount).toFixed(2)}</span>
      </div>`;
    } //alert(total);
     //alert(total1);

    /*footer += `
      <div class="tax-amount total-container">
        <span class="text">Total GST Tax</span>
        <span class="price">
          <i class="fa fa-inr p-font"></i> ${gstAmount.toFixed(2)}
        </span>
      </div>`;*/



       footer += `
      <div class="subtotal total-container">
        <span class="text">Delivery Charges</span>
        <span class="price">
          
          <i class="fa fa-inr p-font"></i>${parseInt(del_charges).toFixed(2)}</span>
      </div>`;

// <i class="fa fa-inr p-font"></i>${parseInt(del_charges).toFixed(2)}</span>
//<i class="fa fa-inr p-font"></i>${localStorage.delivery_ch}</span>
//<i class="fa fa-inr p-font"></i>${localStorage.total1}</span>
// <i class="fa fa-inr p-font"></i>${ parseInt(localStorage.total1).toFixed(2)}</span>
  var ttt = total+parseInt(del_charges)+total_commission;
  localStorage.ttt = ttt;
    footer += `
      <div class="finaltotal total-container">
        <span class="text">Total Payable Amount</span>
        <span class="price">
          <i class="fa fa-inr p-font"></i>${ttt.toFixed(2)}</span>
      </div>
    </div>`;

    // final_buttons += `
    //   <div class="row no-margin" style ="position: fixed;  bottom: 0;  z-index: 99; width:100%; padding:5px;">
    //     <button class="continue-shopping main-color-bg btn col s5" style="border-radius:5px;">Continue&nbsp;Shopping</button>
    //     <button class="btn col s5" style="background-color:#ff1a1a;border-radius:5px;" onclick="emptyCart()">Empty Cart</button>
    //     <button class="btn col s12" onclick="proceedToAddress()" style="border-radius:5px;">Proceed</button>
        
    //   </div>`;
    //var product_vendor_phone = ''
    final_buttons += `<div style="position: fixed;bottom: 0px;width: 100%;z-index: 99;">

      <div style="display: flex;   color: white;
       height: 36px; align-items: center; padding: 12px; margin: 0px 2px -5px 0px;">
            <div class="continue-shopping" style="background:#689f39!important;width: 50%;border-radius:5px;height:40px;margin: 0px 5px 0px 0px;padding: 8px 20px;text-overflow: ellipsis;white-space: nowrap;">Continue Shopping</div>
            <div onclick="emptyCart()" style="background:#ff0000;width: 50%;border-radius:5px;height:40px;padding: 8px 40px;text-overflow: ellipsis;white-space: nowrap;">Empty Cart</div>
      </div>
      <div onclick="proceedToAddress()"  style="display: flex; justify-content: space-around; background: #689f39; color: white;
       height: 36px; align-items: center; padding: 23px; margin: 10px 5px 0px 5px;border-radius:5px;"> 
            <div>Proceed</div>
      </div>

    </div>`;
  } else {

    // htmlString += `
      // <div class="empty-cart">
        // <h5 class="heading">Your Shopping cart is empty add some products for checkout</h5>
        // <button class="continue-shopping btn main-color-bg">Continue Shopping</button>
      // </div>`;
      // width:175px;width:175px;width:355px; margin:-10px 0px 0px 10px; margin:-10px 0px 5px 5px;
    htmlString += `
      <div class="empty-cart">
        <h5 class="heading"><i class="ion-android-cart"></i> Your Cart is empty.</h5>
        <button class="continue-shopping btn main-color-bg" style="border-radius:10px;">Continue Shopping</button>
      </div>`;
  }

  $('.shopping-cart').append(htmlString);

  if (htmlString) {
    $('.shopping-cart').append(footer).append(final_buttons);
  }
};


/*** apply coupon functionality starts here ***/
const applyCouponFrom = document.querySelector('.apply-coupon');
if (applyCouponFrom) { 
  applyCouponFrom.onsubmit = (e) => {
    e.preventDefault();

    let formData = new FormData(applyCouponFrom);

    let couponCode = formData.get('coupon');

    if (!couponCode) {
      couponCode = formData.get('coupon_radio');
    }

    couponCode = {
      code: couponCode,
      total: localStorage.ttt,
      username:localStorage.username,
      // total: findCartTotal(),
    };
    showLoader();
    postFetchRequest('/appcode/is_this_coupon.php', couponCode)
      .then((response) => {
        console.log(response);
        if (response.status === 1) {
          if(response.value.type =="cashback"){
            localStorage['cashback'] = response.value.total_discount;
             localStorage['cashback_applied'] = JSON.stringify(response.value);
            localStorage.removeItem('coupon_applied');
            alert(localStorage['cashback']+ "% Cashback will be given to you.")
            alert("Cashback Apply."); 
            } else{
              //alert(0)
                 localStorage['coupon_applied'] = JSON.stringify(response.value);
                 localStorage.removeItem('cashback');
                 alert("Coupon Apply."); 
          console.log(response.value);

         //  alert("Coupon Apply.");
         // return;

            }
          //alert("Coupon Apply.");
          localStorage['coupon_applied'] = JSON.stringify(response.value);
         // alert("Coupon Apply."); 
          window.location.href = 'cart.html'; 
          console.log(response.value);

        } else if (response.status === 3) {
            alert(response.msg);
            alert(response.msg);
            window.location.href = 'cart.html';
        } else if (response.status === 2) {
          alert("No Coupon Found.");
          window.location.href = 'cart.html';
        } else if (response.status === 0) {
          alert('Sorry there is an error please select coupon again.');
          window.location.href = 'cart.html';
        } else if (response.status === 99) {
          alert(unexpectedError, 4000);
          window.location.href = 'cart.html';
        } else {
          alert(unexpectedError, 4000);
          window.location.href = 'cart.html';
        }
        removeLoader();
      })
      .catch((error) => {
        console.log(error);
        alert(unexpectedError, 4000);
        removeLoader();
      });
  }
 }
/*** apply coupon functionality ends here ***/

function emptyCoupon1() {
   localStorage.removeItem('coupon_applied');
   localStorage.removeItem('dis_amount');
   localStorage.removeItem('coupon_code');
  location.reload();
};

function emptyCashback1() {
  localStorage.removeItem('cashback');
  location.reload();
};
/*** cart empty function ***/
function emptyCart() {
  localStorage.removeItem('te');
  localStorage.removeItem('shopping-cart-items');
  localStorage.removeItem('coupon_applied');
  localStorage.removeItem('cashback');
  shopping_cart = [];

  alert('Your shopping cart is now empty', 4000);
  window.location.href = 'index.html';
}

// function proceedToAddress() {

//   let isLogin = checkLogin();

//   // if (isLogin) {

//   localStorage.totalAmount = findCartTotal();
//   window.location.href = "checkout.html";
//   // }
//   /*else {
//     alert('Please login or register for checkout.');
//     window.location.href = 'login.html';
//   }*/
// }
function remove_pin() {
  
  
localStorage.removeItem('pin');
  // alert('Your shopping cart is now empty', 4000);
   window.location.reload();
}

function proceedToAddress() {
 var st = localStorage.subTotal;
  let isLogin = checkLogin();
  
  // if (isLogin) {

  localStorage.totalAmount = findCartTotal();
  if (parseInt(st) < 200 ) {
    var balanceamount = (200 - parseInt(st));
    alert('Please shop more for Rs. ' + balanceamount );
    //alert('Please shop more for Rs. ' + balanceamount );

  } else {

    // if (localStorage.username != null && localStorage.loginStatus ==
    ///   'A' &&
    //   localStorage.login == "true") {

    //  var val = total - (total * .10);
    // localStorage['tempDetails'] = val;

    localStorage['tempDetails'] = st;


    // localStorage['tempDetails'] = JSON.parse(localStorage[
    //   'shopping-cart-items'].toString());

    window.location.href = "checkout.html";
  }
  //window.location.href = "checkout.html";
  // }
  /*else {
    alert('Please login or register for checkout.');
    window.location.href = 'login.html';
  }*/
}


function removeFromCart(self) {

  let gotId = self.parentNode.getAttribute('data-code');

  let shoppingCart = JSON.parse(localStorage['shopping-cart-items'].toString());

  for (let i in shoppingCart) {
    if (shoppingCart[i].product_code === gotId) {
      shoppingCart.splice(i, 1);
      break;
    }
  }

  localStorage['shopping-cart-items'] = JSON.stringify(shoppingCart);

  updateCartBadge();
  alert('Item has been successfully removed from your cart.', 2000);
  location.reload();
}

//cart functionality
// function displayShoppingCart() {
//
//  var htmlString = '';
//  var footer = '';
//  var total = 0;
//  var final_buttons = '';
//  var totalAfterGst = 0;
//
//  if (localStorage['shopping-cart-items'] != null) {
//    shopping_cart = JSON.parse(localStorage['shopping-cart-items'].toString());
//
//    $.each(shopping_cart, function (index, item) {
//
//      htmlString += `<div class="cart-item" data-code="${item.product_code}">
//                <div class="row">
//                  <div class="col s12 no-padding">
//                    <div class="col s5">
//                      <img src="${item.product_image}" class="img-responsive product_image_preview">
//                    </div>
//                    <div class="col s7 no-padding">
//                      <b class="product_name">${item.product_name}</b>
//                      <div class="price-section">
//                        <span class="product-price">Price:
//                          <i class="fa fa-inr"></i>
//                          ${item.product_price}
//                        </span>
//                      </div>
//                      <div class="col s5 no-padding">
//                        <div class="cart-quantity-control">
//                          <div class="cart-quan-plus cart-quan">+</div>
//                          <div class="cart-quan-show cart-quan">${item.product_quantity}</div>
//                          <div class="cart-quan-minus cart-quan">-</div>
//                        </div>
//                      </div>
//                    </div>
//                  </div>
//                </div>
//              </div>
// `;
//      total += (item.product_price * item.product_quantity);
//      totalAfterGst += (item.product_after_gst * item.product_quantity);
//    });
//
//    footer += `
//          <div class="normal_price">
//            <i class="fa fa-shopping-cart"></i>
//            <span style="float:right;font-size;12px">
//              <b><i class="fa fa-inr" style="font-size: 14px !important"></i>${total.toFixed(2)}</b>
//            </span>
//          </div>
//
//          <div class="price_after_gst">
//            Price After GST
//            <span style="float:right;font-size;12px">
//              <b><i class="fa fa-inr" style="font-size: 14px !important"></i>${totalAfterGst.toFixed(2)}</b>
//            </span>
//          </div>
//    `;
//
//    final_buttons += `
//                <div class="row no-margin">
//                  <button class="continue-shopping button button-balanced col s6">
//                    Continue Shopping
//                  </button>
//                  <button class="checkout-next button button-balanced col s6">
//                    Next
//                  </button>
//                  <button class="emptyCart button button-balanced col s12 red">
//                    Empty Cart
//                  </button>
//                </div>
//    `;
//  } else {
//    htmlString += `
//              <div class="row">
//                <h5 class='red-text text-center padding_10_tb'>
//                  Your Shopping Cart is empty please add some product for checkout.
//                </h5>
//                <button class="continue-shopping padding_10_tb text-center button white-text col s12">
//                  Continue Shopping
//                </button>
//              </div>
//    `;
//  }
//
//  $('.cart').append(htmlString);
//
//  if (htmlString) {
//    $('footer').prepend(footer).append(final_buttons);
//  }
// }

//displaying final shopping cart only for cart functionality
// function displayFinalShoppingCart() {
//
//  var htmlString = '';
//  var footer = '';
//  var total = 0;
//  var totalAfterGst = 0;
//  var final_buttons = '';
//
//  if (localStorage['shopping-cart-items'] != null) {
//    shopping_cart = JSON.parse(localStorage['shopping-cart-items'].toString());
//
//    $.each(shopping_cart, function (index, item) {
//      htmlString += '<div class="cart-item" data-code="' + item.product_code + '">';
//      htmlString += '<div class="row">';
//      htmlString += '<div class="col s12 no-padding">';
//      htmlString += '<div class="col s5">';
//      htmlString += '<img src="img/fruit.jpg" class="img-responsive product_image_preview">';
//      htmlString += '</div>';
//      htmlString += '<div class="col s7 no-padding">';
//      htmlString += '<div class="col s12 no-padding">';
//      htmlString += '<b class="product_name">' + item.product_name + '</b>';
//      htmlString += '</div>';
//      htmlString += '<div class="col s5 no-padding">';
//      htmlString += '<div class="cart-final-quantity">';
//      htmlString += '<span>' + item.product_price + '</span>';
//      htmlString += '<span> x </span>';
//      htmlString += '<span>' + item.product_quantity + '</span>';
//      htmlString += '</div>';
//      htmlString += '</div>';
//      htmlString += '<div class="col s7 no-padding right-align">';
//      htmlString += '<span class=""><i class="fa fa-inr p-font"></i>' + item.product_price * item.product_quantity + '</span>';
//      htmlString += '</div>';
//      htmlString += '<div class="col s5 no-padding">';
//      htmlString += '<div class="cart-product-gst">';
//      htmlString += '<span>GST ' + item.product_gst + ' %</span>';
//      htmlString += '</div>';
//      htmlString += '</div>';
//      htmlString += '<div class="col s7 no-padding right-align">';
//      htmlString += '<span class=""><i class="fa fa-inr p-font"></i>' + item.product_after_gst * item.product_quantity + '</span>';
//      htmlString += '</div>';
//      // htmlString += '<input id="btnSubtract" value="-" onclick="subtract();" type="button">';
//      // htmlString += '<input id="txtNumber" style="width:40px" type="text" value="' + item.product_quantity +'">';
//      // htmlString += '<input id="btnAdd" value="+" onclick="add();" type="button"></div>';
//      htmlString += '</div>';
//      htmlString += '</div>';
//      htmlString += '</div>';
//      htmlString += '</div>';
//      total += (item.product_price * item.product_quantity);
//      totalAfterGst += (item.product_after_gst * item.product_quantity);
//    });
//
//    footer += '<div class="item1">';
//    footer += '<div class="footer2">Sub Total';
//    footer += '<span style="float:right;font-size;12px">' + total.toFixed(2);
//    +'</span>';
//    footer += '</div>';
//    footer += '</div>';
//    footer += '<div class="item1">';
//    footer += '<div class="footer2">Price After GST';
//    footer += '<span style="float:right;font-size;12px">' + totalAfterGst.toFixed(2) + '</span>';
//    footer += '</div>';
//    footer += '</div>';
//    footer += '<div class="footer1">';
//    footer += '<b>Total Payable</b>';
//    footer += '<span style="float:right;font-size;12px">';
//    footer += '<b><i class="fa fa-inr" style="font-size: 14px !important"></i>' + totalAfterGst.toFixed(2) + '</b>';
//    footer += '</span>';
//    footer += '</div>';
//
//    final_buttons += '<div class="row no-margin">';
//    final_buttons += '<button class="continue-shopping button button-balanced col s6 padding_10">Continue Shopping</button>';
//    final_buttons += '<button class="checkout-final button button-balanced col s6 padding_10">Next</button>';
//    final_buttons += '<button class="emptyCart button button-balanced col s12 red padding_10">Empty Cart</button>';
//    final_buttons += '</div>';
//  } else {
//    htmlString += '<div class="row">';
//    htmlString += "<h5 class='red-text text-center padding_10_tb'>Your Shopping Cart is empty please add some product for checkout.</h5>";
//    htmlString += '<button class="continue-shopping padding_10_tb text-center button white-text col s12 padding_10">Continue Shopping</button>';
//    htmlString += '</div>';
//  }
//
//  $('.cart').css('margin-bottom', '120px').append(htmlString);
//
//  if (htmlString) {
//    $('footer').prepend(footer).append(final_buttons);
//  }
// }

function doToCartByOne_inner(quantity, code, type) {
  if (type == 'add') {
    if (shopping_cart.length != 0) {
      $.each(shopping_cart, function (index, item) {
        if (code == item.code) {
          item.product_quantity = quantity;
          localStorage['shopping-cart-items'] = JOSN.stringify(shopping_cart);
          console.log('this cart item has been incremented by 1');
          return false;
        }
      });
    }
  } else if (type == 'remove') {
    if (shopping_cart.length != 0) {
      $.each(shopping_cart, function (index, item) {
        if (code == item.code) {
          item.product_quantity = quantity;
          localStorage['shopping-cart-items'] = JOSN.stringify(shopping_cart);
          console.log('this cart item has been decremented by 1');
          return false;
        }
      });
    }
  }
}

function removeProduct(code,size) {
  for (var i = 0; i < shopping_cart.length; i++) {
    var cur = shopping_cart[i];
  if (parseInt(cur.product_code) == parseInt(code) && cur.product_size==size) {
      shopping_cart.splice(i, 1);
      break;
    }
  }
  localStorage['shopping-cart-items'] = JSON.stringify(shopping_cart);

  location.reload();
}
function removeProduct1(code,size) {
  for (var i = 0; i < shopping_cart.length; i++) {
    var cur = shopping_cart[i];
    if (parseInt(cur.product_code) == parseInt(code) && cur.product_size==size) {
     // alert('r');
      shopping_cart.splice(i, 1);
      break;
    }
  }
  localStorage['shopping-cart-items'] = JSON.stringify(shopping_cart);

  location.reload();
}

function incrementCartItem(code) {

  console.log('receive by increment');
  $.each(shopping_cart, function (index, item) {
    if (code == item.product_code) {
      item.product_quantity++;
      item.product_total_after_gst = item.product_after_gst * item.product_quantity;
    }
  });

  window.plugins.toast.showWithOptions({
    message: "Item Has Been Added To The Cart",
    duration: "short", // 2000 ms
    position: "bottom",
    styling: {
      opacity: 1,
      backgroundColor: '#666666',
      textColor: '#ffffff',
      textSize: 20.5,
      cornerRadius: 16,
      horizontalPadding: 20,
      verticalPadding: 16
    }
  });

  localStorage['shopping-cart-items'] = JSON.stringify(shopping_cart);
}

//in app browser functions
function addToWallet(id) {
  let tag = base + "/appcode/pay_now_wallet.php?id=" + id;
  // alert(tag);
  iabPay = cordova.InAppBrowser.open(tag, '_blank');
  iabPay.addEventListener('loadstart', iabPayLoadStart);
  iabPay.addEventListener('loadstop', iabPayLoadStop);
  iabPay.addEventListener('loaderror', iabPayLoadError);
  iabPay.addEventListener('exit', iabPayClose);
}

//load start event
function iabPayLoadStart(event) {
}

function iabPayLoadStop(event) {
  if (event.url.match(base + '/appcode/wallet_success.php')) {
   alert('Thanks for the payment. We have updated your wallet balance.');
    window.location.href = "index.html";
    iabPay.close();
  } else {
    if (event.url.match(base + '/appcode/wallet_faliure.php')) {

     alert('Payment Failed, please try again after some time.');
      iabPay.close();
    }
  }
}

//load error event
function iabPayLoadError(event) {
  alert(event.type + ' - ' + event.message);
}

//close event
function iabPayClose(event) {
  $('.supreme-container1').hide();
  iabPay.removeEventListener('loadstart', iabPayLoadStart);
  iabPay.removeEventListener('loadstop', iabPayLoadStop);
  iabPay.removeEventListener('loaderror', iabPayLoadError);
  iabPay.removeEventListener('exit', iabPayClose);
}

function gotoPage(id) {
  // alert();
  let tag = base + "/appcode/pay_now.php?id=" + id;
  // alert(tag);
  iabRef = cordova.InAppBrowser.open(tag, '_blank');
  iabRef.addEventListener('loadstart', iabLoadStart);
  iabRef.addEventListener('loadstop', iabLoadStop);
  iabRef.addEventListener('loaderror', iabLoadError);
  iabRef.addEventListener('exit', iabClose);
}

//load start event
function iabLoadStart(event) {
}

function iabLoadStop(event) {

  if (event.url.match(base + "/appcode/pay_success.php")) {
    //alert('Payment Completed Successfully.');
   alert(`Your Order has been placed successfully, Your order id is ${localStorage.orderId}`);
    localStorage.removeItem('shopping-cart-items');
    shopping_cart = [];
    localStorage.removeItem('special_name');
    localStorage.removeItem('totalAmount');
    localStorage.removeItem('coupon_applied');
    localStorage.removeItem('cashback');
     localStorage.removeItem('orderId');
    window.location.href = "index.html";
    iabRef.close();
  } else {
    if (event.url.match(base + '/appcode/pay_faliure.php')) {
     alert('Payment Failed, Please try again after some time.');
      iabRef.close();
    }
  }
}

//load error event
function iabLoadError(event) {
  alert(event.type + ' - ' + event.message);
}

//close event
function iabClose(event) {
  // alert("test");
  $('.supreme-container').hide();
  iabRef.removeEventListener('loadstart', iabLoadStart);
  iabRef.removeEventListener('loadstop', iabLoadStop);
  iabRef.removeEventListener('loaderror', iabLoadError);
  iabRef.removeEventListener('exit', iabClose);
}


function goBack() {
   //history.go(-1);

  window.history.back();
    //navigator.app.backHistory();
}
function goLoginBack() {
  window.location.href='index.html';
}

const backButton = () => {
  history.go(-1);
     navigator.app.backHistory();
 };

/*** Show Toast ***/
function showToast(msg, duration = 'short', position = 'bottom') {
  window.plugins.toast.showWithOptions({
    message: msg,
    duration: duration,
    position: position
  });
}

/*** loading animation ***/
function showLoader() {
  let loader = "<div class='supreme-container'><div id='loader'></div></div>";
  document.body.insertAdjacentHTML('beforeend', loader);
  document.body.style.overflow = 'hidden';
}

function removeLoader() {
  let loader = document.querySelector('.supreme-container');
  document.body.style.overflow = 'visible';
  loader.remove();
}

function checkLogin() {
  let login = false;

  if (parseInt(localStorage.login) === 1 && localStorage.username && localStorage.loginStatus === 'A') {
    login = true;
  } else {
    login = false;
  }
  return login;
}

function getUserDetails() {
  return JSON.parse(localStorage['userDetails'].toString());
}

function loginThenProfile(profileItem) {

  if (checkLogin() === true) {

    profileItem.parentElement.querySelectorAll('.showonlogin').forEach((item) => {
      item.style.display = "block";
    });

    profileItem.parentElement.querySelectorAll('.hideonlogin').forEach(item => {
      item.classList.add('hide');
    });

    replaceProfile();

    /***
     * user login show logout button and logout on click.
     * @type {Element}
     */

    const logoutLink = document.querySelector('#slide-out .logout-link');
    if (logoutLink) {
      logoutLink.addEventListener('click', (evt) => {

        localStorage.username = "";
        localStorage.loginStatus = "";
        localStorage.login = 0;
        localStorage.removeItem('username');
        localStorage.removeItem('loginStatus');
        localStorage.removeItem('login');
        localStorage.removeItem('userDetails');

        alert('You have been logged out successfully.');
        window.location.href = "index.html";
      }, false);
    }
    /*profileItem.querySelector('.text').textContent = 'Profile';
    profileItem.style.display = "none";
    profileItem.remove();*/
  }
}

const findCartTotal = (cart = localStorage['shopping-cart-items']) => {

  let shoppingCart = JSON.parse(localStorage['shopping-cart-items'].toString());
  let total = 0;
  for (let i in shoppingCart) {
    total += shoppingCart[i].product_price * shoppingCart[i].product_quantity;
  }

  return total;
};

function replaceProfile() {
  let userDetails = getUserDetails();

  let profileArea = document.querySelector('#slide-out .profile-area');
  let image = profileArea.querySelector('.profile-image img');
  let name = profileArea.querySelector('.name');

  if (userDetails.profile_pic) {
    image.src = base + "/img/" + userDetails.profile_pic;
  }
  name.textContent = `Welcome ${userDetails.name}`;
}


/*** login functionality ***/
// let login_form = document.querySelector('.login-form');

// if (login_form) {
//   login_form.onsubmit = (e) => {
//     showLoader();
//     e.preventDefault();

//     let formData = new FormData(login_form);
//     let loginDetails = {
//       phone: formData.get('phone'),
//       password: formData.get('password')
//     };

//     if (loginDetails.phone && loginDetails.password) {

//       let fetchPram = {
//         credentials: "same-origin",
//         method: "POST",
//         headers: {
//           'Accept': 'application/json',
//           "Content-Type": "application/json"
//         },
//         body: JSON.stringify({data: loginDetails})
//       };

//       postFetchRequest('/appcode/login.php', loginDetails)
//         .then((response) => {
//           console.dir(response);
//           if (response.status === 1) {
//             /*** success message ***/
//             if (response.userDetails.status === 'A') {

//               localStorage.username = response.userDetails.username;
//               localStorage.loginStatus = response.userDetails.status;

//               let userDetails = {
//                 username: response.userDetails.username,
//                 name: response.userDetails.name,
//                 email: response.userDetails.email,
//                 phone: response.userDetails.phone,
//                 dob: response.userDetails.dob,
//                 address: response.userDetails.address,
//                 status: response.userDetails.status,
//                 profile_pic: response.userDetails.profile_pic,
//                 city: response.userDetails.city,
//               };

//               localStorage.userDetails = JSON.stringify(userDetails);
//               localStorage.login = 1;

//               alert(`Hey, Welcome Back ${response.userDetails.name}`, 4000);
//               window.location.href = 'index.html';

//             } else {
//              alert('Sorry, your account has been disabled please contact us to activate it.');
//             }
//           } else if (responseData.status === 2) {
//             /*** unexpected error (everything received but couldn't proceed. ***/
//             alert("Sorry, there is no user with the following details. Make sure phone no and password you entered is correct.");
//           } else if (responseData.status === 0) {
//             /*** one of the fields is empty ***/
//             alert('Please fil all fields and try again.');
//           } else {
//             alert('Phone or password incorrect. Please Fill valid phone or password');
//           }
//           removeLoader();
//         })
//         .catch((err) => {
//           console.dir(err);
//           alert('Phone or password incorrect. Please Fill valid phone or password');
//           removeLoader();
//         });

//     } else {
//       alert('Please fill all fields and try again.');
//       removeLoader();
//     }
//   }
// }


var login_form = document.querySelector('.login-form');
// alert(.login-form);
/*** login functionality ***/

if (login_form) {
  //alert(1);
  login_form.onsubmit = (e) => {
    showLoader();
    e.preventDefault();

    var formData = new FormData(login_form);
    var loginDetails = {
      phone: formData.get('phone'),
      password: formData.get('password')
    };
    // console.log(loginDetails);return;

    if (loginDetails.phone && loginDetails.password) {
      
      console.log(loginDetails);
      $.ajax({
        ////url: "http://localhost/multirestaurant/appcode/login.php",
        url: base+"/appcode/login.php",
        data: loginDetails,
        type: "post",
        dataType: "json",
        success: function (response) {
          // console.log(response);
          if (response.status == 'A') {
            
            localStorage.username = response.username;
            localStorage.loginStatus = response.status;
            localStorage.login = true;
            localStorage.userDetails = [];
            var userDetails = {
              username: response.username,
              email: response.email,
              phone: response.phone,
              status: response.status,
              name: response.name,
              pincode: response.pincode,
              address: response.address,
            };

              localStorage.userDetails = JSON.stringify(userDetails);
              localStorage.login = 1;

              //alert('Hey, Welcome Back '+userDetails.response.name, 4000);
              window.location.href = 'index.html';

          }
          else if (response.status == 'I') {
            console.log('Account Suspended');
           alert("Your account is inactive please contact us to activate.");
          }
          else {
            console.log("username / password dosen't match.");
           alert("username / password dosen't match.");
          }
          removeLoader();
        },
        error: function(error){
          console.dir(err);
          alert(unexpectedError);
          removeLoader();
        }
      });
    } else {
      alert('Please fill all fields and try again.');
      removeLoader();
    }
  }
}
/*** login ends ***/
/*** login ends ***/

/*** update profile ***/

let updateProfile = document.querySelector('.edit-personal-form');
if (updateProfile) {
  updateProfile.onsubmit = (e) => {
    e.preventDefault();
    showLoader();

    let formData = new FormData(updateProfile);

    let oldDetails = JSON.parse(localStorage['userDetails'].toString());
    let userDetails = {
      name: formData.get('name'),
      email: formData.get('email'),
      phone: oldDetails.phone,
      // dob: formData.get('dob'),
      address: formData.get('address'),
      city: formData.get('city'),
      status: oldDetails.status,
      username: oldDetails.username,
      profile_pic: oldDetails.profile_pic,
    };
    console.log(oldDetails); //return;
    console.log(userDetails); //return;

    postFetchRequest('/appcode/update_profile.php', userDetails)
      .then((response) => {
        console.log(response);
        if (response.status === 1) {
          alert("Your profile has been updated successfully.");
          localStorage.userDetails = JSON.stringify(userDetails);
        } else if (response.status === 2) {
          alert(unexpectedError, 4000);
        } else if (response.status === 3) {
          alert(response.msg, 4000);
        } else if (response.status === 0) {
          alert("Please fill all fields and try again.", 4000);
        } else if (response.status === 99) {
          alert(unexpectedError, 4000);
        } else {
          alert(unexpectedError, 4000);
        }
        removeLoader();
      })
      .catch((error) => {
        console.log(error);
        removeLoader();
        alert(unexpectedError, 4000);
      });
  }
}

/*** update profile ends ***/

/***
 * get the mime type of file.
 * @param file
 * @returns {string}
 */
const getMimeType = (file) => {

  let ext = file.split('.').pop();
  let mime = "";

  switch (ext) {
    case "txt" : {
      mime = "text/plain";
      break;
    }
    case "pdf" : {
      mime = "application/pdf";
      break;
    }
    case "jpeg" : {
      mime = "image/jpeg";
      break;
    }
    case "jpg" : {
      mime = "image/jpeg";
      break;
    }
    case "png" : {
      mime = "image/png";
      break;
    }
    case "doc" : {
      mime = "application/msword";
      break;
    }
  }

  return mime;
};

/*** this will pick file form file manager and send the url back as promise
 *  (so you can receive it by using then())
 ***/
const pickFile = () => {

  return new Promise((resolve, reject) => {
    window.OurCodeWorld.Filebrowser.filePicker.single({
      success: (data) => {
        if (!data.length) {
          //no file selected.
          reject(Error("Nothing Selected"));
        }
        resolve(data[0]);
      },
      error: (err) => {
        console.log(err);
        reject("Nothing Selected");
      }
    });
  });
};


/*** document picker function ***/
/*** open custom file manager for browsing and selecting document or file and then assign the file url
 * to the given session variable name. ***/
function documentPicker(name = 'upload_profile_pic') {

  /*** use this piece of code to extract the filename form file url
   * url.substr(url.lastIndexOf('/') + 1);
   * Or you can use this
   * a.split('/').pop();
   ***/
  pickFile()
    .then((response) => {
      console.dir(response);

      sessionStorage[name] = response;
    })
    .then(() => {
      uploadProfilePic();
    })
    .catch((error) => {
      console.dir(error);
    });
}

/*** document picker function ends ***/

/*** image picker same as document picker but with only image and videos ***/

function imageGalleryPicker(name = 'upload_profile_pic') {
  window.imagePicker.getPictures(
    function(results) {
      /*** removing loop which makes it to select only one image to upload even though the user had select multiple
       * images
       */
      sessionStorage[name] = results[0];
      console.log('Image URI: ' + results[0]);
      uploadProfilePic();
      /*for (let i = 0; i < results.length; i++) {
        console.log('Image URI: ' + results[i]);

        sessionStorage[name] = results[i];
      }*/
    }, function (error) {
      console.log('Error: ' + error);
    }
  );
}

/*** update profile_pic starts ***/
// const uploadProfilePic = () => {
//   console.log("click event received.");

//   let file = sessionStorage['upload_profile_pic'];
//   let userDetails = getUserDetails();
//   let url = base + "/appcode/upload_new_profile_pic.php";
//   if (file) {

//     showLoader();

//     let options = new FileUploadOptions();
//     options.fileKey = "profile_pic";
//     options.fileName = file.substr(file.lastIndexOf('/') + 1);
//     options.mimeType = getMimeType(options.fileName);

//     console.dir(options);

//     if (!options.mimeType) {
//       options.mimeType = "image/jpeg";
//     }

//     let params = new Object();
//     params.username = userDetails.username;
//     params.phone = userDetails.phone;
//     options.params = params;
//     options.chunkedMode = false;

//     let ft = new FileTransfer();

//     ft.upload(file, url, (response) => {
//       console.dir(response);
//       let res = JSON.parse(response.response.toString());
//       console.log(res);

//       if (res.status === 1) {
//         let tempUserDetails = getUserDetails();
//         tempUserDetails.profile_pic = res.file;
//         localStorage['userDetails'] = JSON.stringify(tempUserDetails);

//         /*** success message ***/
//         alert("File Uploaded Successfully.");
//         window.location.reload();
//       } else if (res.status === 2) {
//         alert(unexpectedError);
//       } else if (res.status === 0) {
//         alert("Sorry an error occurred while uploading your selected image please try some other image.");
//       } else {
//         alert(unexpectedError);
//       }
//       removeLoader();
//     }, (error) => {
//       removeLoader();
//       console.dir(error);
//       alert(unexpectedError);
//     }, options);
//   } else {
//     alert("Couldn't upload this file please select some other file.");
//   }
// };
/*** update profile_pic ends ***/

/*** Change Password form ***/

let changePassword = document.querySelector('.change-password');
if (changePassword) {
  changePassword.onsubmit = (e) => {
    e.preventDefault();

    let formData = new FormData(changePassword);
    let userDetails = JSON.parse(localStorage['userDetails'].toString());

    userDetails['old_password'] = formData.get('old_password');
    userDetails['new_password'] = formData.get('new_password');
    userDetails['new_password_repeat'] = formData.get('new_password_repeat');

    if (formData.get('old_password') && formData.get('new_password') && formData.get('new_password_repeat')) {

      if (userDetails.new_password === userDetails.new_password_repeat) {

        console.log(userDetails);

        showLoader();
        postFetchRequest('/appcode/change_password.php', userDetails)
          .then((response) => {
            console.log(response);

            changePassword.reset();
            if (response.status === 1) {
              alert("Your password has been changed successfully.");
            } else if (response.status === 2) {
              alert(unexpectedError, 4000);
            } else if (response.status === 3) {
              alert("Sorry, your password is incorrect.", 4000);
            } else if (response.status === 4) {
              alert("Password and retype password doesn't matched.", 4000);
            } else if (response.status === 0) {
              alert("Please fill all fields and try again.", 4000);
            } else if (response.status === 99) {
              alert(unexpectedError, 4000);
            } else {
              alert(unexpectedError, 4000);
            }
            removeLoader();
          })
          .catch((error) => {
            console.log(error);
            removeLoader();
            alert(unexpectedError, 4000);
          });
      } else {
        alert("Your New password and retype password doesn't matched.");
      }
    } else {
      alert("Please fill all fields correctly and try again.", 4000);
    }
  }
}

/*** update profile ends ***/

// /*** registration method starts ***/
// $('#main-container').on('click', '.register-now-buttonn', function (evt) {
//     evt.preventDefault();
//     var name = $("input[name='name']").val();
//     var email = $("input[name='email']").val();
//     var phone = $("input[name='phone']").val();
//     var password = $("input[name='password']").val();
//     var confirm_password = $("input[name='confirm_password']").val();
//     var city = $("input[name='city']").val();
//     //var gst = $("input[name='gst']").val();
//     var address = $("input[name='address']").val();
//     var id_proof = $("input[name='id_proof']").val();
//     localStorage.checkphone = phone;
    
//   if (name!="" && email!="" && phone!="" && password!="" && confirm_password!="" && id_proof!="") {

//       if (password === confirm_password) {
//     var formdata = new FormData();
//     formdata.append('name',name);
//     formdata.append('email',email);
//     formdata.append('phone',phone);
//     formdata.append('password',password);
//     formdata.append('confirm_password',confirm_password);
//     formdata.append('city',city);
//     //formdata.append('gst',gst); 
//     formdata.append('address',address); 
     
//     formdata.append('id_proof', $('#id_proof')[0].files[0]);
//         $.ajax({
//       url: base+'/appcode/registertest.php',
//       data: formdata,
//       type: 'post',
//       dataType: 'json',
//       data: formdata,
//       processData: false,
//       contentType: false,
//       success: function(response) {
//             console.log(response); //return;
//             if (response.status === 1) { 
//               /*** success message ***/
//               if (response.status === 'A') { 

//                 localStorage.username = response.userDetails.username;
//                 localStorage.loginStatus = response.userDetails.status;

//                 var userDetails = {
//                   username: response.username,
//                   name: response.name,
//                   email: response.email,
//                   phone: response.phone,
//                   status: response.status,
//                   city: response.city,
//                   address: response.address,
//                   //pincode: response.userDetails.pincode
//                 };

//                 localStorage.userDetails = JSON.stringify(userDetails);
//                 localStorage.login = 1;
//                 //alert(`Thank you ${response.userDetails.name}, You've been regstered successfully.`, 2000);
//                 //window.location.href = 'index.html';
                
                

//               } else { 
//                 //alert("Sorry, your account has been disabled please contact us for more information");
//                // alert("Sorry, your account has been inactive");
                
//                 window.location.href = 'verify-otp.html';
//               }
//             } else if (response.status === 2) { 
//               /*** unexpected error (everything received but couldn't proceed. ***/
//               alert("Sorry, there is already a user with the following details.");
//             } else if (response.status === 0) {
//               /*** one of the fields is empty ***/
//               alert("Please fill all fields and try again.");
//             } else {
//               alert(unexpectedError);
//             }
//             //removeLoader();
//             },
//             error :function(error){
//               console.error(error);
//             //removeLoader();
//             alert(unexpectedError);
//             }
//           });
          
//       } else {
//        alert('Sorry the password and retype password doesn\'t match.');
//       }

//     } else {
//      alert('Please fill all fields and try again.');
//     }
// });


////////// // old resiter form



var registration_form = document.querySelector('.register-form');
if (registration_form) {
  registration_form.onsubmit = (e) => {
    e.preventDefault();
showLoader();
    var formData = new FormData(registration_form);
    var registerDetails = {
      name: formData.get('name'),
      email: formData.get('email'),
      phone: formData.get('phone'),
      password: formData.get('password'),
      retypePassword: formData.get('confirm_password'),
      city: formData.get('city'),
     // pincode: formData.get('pincode'),
      address: formData.get('address'),
      //referrer: formData.get('referrer'),
    };
	console.log(registerDetails);
localStorage.checkphone = registerDetails.phone;
// return;
    if (registerDetails.name && registerDetails.email && registerDetails.phone && registerDetails.password
      && registerDetails.retypePassword) {

      if (registerDetails.password === registerDetails.retypePassword) {

        
        $.ajax({
          url: base+'/appcode/register2.php',
          data: registerDetails,
          type: 'POST',
          dataType: 'JSON',
          success: function(response) {
            console.log(response);
            if (response.status === 1) { 
              /*** success message ***/
              if (response.userDetails.status === 'A') { 

                localStorage.username = response.userDetails.username;
                localStorage.loginStatus = response.userDetails.status;

                var userDetails = {
                  username: response.userDetails.username,
                  name: response.userDetails.name,
                  email: response.userDetails.email,
                  phone: response.userDetails.phone,
                  status: response.userDetails.status,
                  city: response.userDetails.city,
                  address: response.userDetails.address,
                  //pincode: response.userDetails.pincode
                };

                localStorage.userDetails = JSON.stringify(userDetails);
                localStorage.login = 1;
                //alert(`Thank you ${response.userDetails.name}, You've been regstered successfully.`, 2000);
                alert(`Thank you ${response.userDetails.name}, You've been regstered successfully.`, 2000);
                window.location.href = 'index.html';
                
                

              } else { 
                //alert("Sorry, your account has been disabled please contact us for more information");
                //alert("Sorry, your account has been inactive");
                
                window.location.href = 'verify-otp.html';
              }
            } else if (response.status === 2) { 
              /*** unexpected error (everything received but couldn't proceed. ***/
              alert("Sorry, there is already a user with the following details.");
            } else if (response.status === 0) {
              /*** one of the fields is empty ***/
              alert("Please fill all fields and try again.");
            } else {
              alert(unexpectedError);
            }
            removeLoader();
            },
            error :function(error){
              console.error(error);
            removeLoader();
            alert(unexpectedError);
            }
          });
          
      } else {
       alert('Sorry the password and retype password doesn\'t match.');
       removeLoader();
      }

    } else {
     alert('Please fill all fields and try again.');
    }
  }
}



const addWalletMoneyForm = document.querySelector('.add-wallet-money-form');
if (addWalletMoneyForm) {
  addWalletMoneyForm.onsubmit = (e) => {
    e.preventDefault();

    let formData = new FormData(addWalletMoneyForm);

    let userDetails = getUserDetails();
    userDetails['amount'] = formData.get('amount');
    userDetails.uniqueId = randomString();
    userDetails.type = "App";
    userDetails.order_type = "Wallet";

    showLoader();
    if (userDetails.amount) {

      postFetchRequest('/appcode/add_money_wallet.php', userDetails)
        .then((res) => {
          console.log(res);
          if (res.status === 1) {

            addToWallet(res.uniqueId);

          } else if (res.status === 2) {
            alert(unexpectedError);
          } else if (res.status === 0) {
            alert('Please logout and login to see your account balance.');
          } else if (res.status === 99) {
            alert(unexpectedError);
          } else {
            alert(unexpectedError);
          }
          removeLoader();
        })
        .catch((err) => {
          console.error(err);
          removeLoader();
        })

    } else {
      alert("Please fill details correctly.");
      removeLoader();
    }
  }
}

function showSubCategories(element) {
  sessionStorage.category = JSON.stringify({
    category_code: element.dataset.code,
    category_name: element.dataset.name,
    sub_category_code: "all"
  });getPosition();
  window.location.href = 'product.html';
}

function setSubCategories(element) {
  category = JSON.parse(sessionStorage['category'].toString());
  sessionStorage.category = JSON.stringify({
    category_code: category.category_code,
    category_name: category.category_name,
    sub_category_code: element.dataset.code,
    sub_category_name: element.dataset.name,
  });
  window.location.reload();
}

function setSmartBasketCategory(element) {
  sessionStorage.smartBasket = JSON.stringify({
    category_code: element.dataset.code,
    category_name: element.dataset.name,
  });

  window.location.reload();
}

function decideFaithOfThisCategory(element) {

 
    // sessionStorage.category = JSON.stringify({
     localStorage.sub_category_code =  element.dataset.code;
      localStorage.category_name= element.dataset.name;
     // alert(localStorage.sub_category_code);
     window.location.href = 'product.html';

   
  // });
    // alert( sessionStorage.category.category_code)

}

function showBannerCategory(element) {
  
   localStorage.category_code= element.dataset.code;
  localStorage.parent_code= element.dataset.parent_code;

 

  window.location.href = 'banner_product.html';   
  
 
}

function decideCategoryCode(element) {
  sessionStorage.category = JSON.stringify({
    category_code: element.dataset.code,
    category_name: element.dataset.name,
    sub_category_code: element.dataset.subCode,
    sub_category_name: element.dataset.name,
  });
  // console.log(element.dataset);
  window.location.href = 'product.html';
}

function checkAndAddToCart(element, combo_product = false) { 
  //alert(1);

  let elementData = element.dataset;

  let [code, name, price, gst, img, quantity,size,vendor_phone,qty,commission] = [elementData.code, elementData.name, elementData.price,
    elementData.gst, elementData.img, elementData.quantity,elementData.size,elementData.vendor_phone,elementData.av_qt,elementData.commission];

  if (!code || !name || !price || !gst || !img || !vendor_phone) { 
    //alert(2);
     //alert(code);
    alert(unexpectedError);
  } else {
    if (!quantity) {
      quantity = 1;
    }
	
	if(quantity > qty) {
		alert("There are only " + qty + " quantity in stock for this size.");
	}else{
		addToCart(code, name, img, price, quantity, gst,size,combo_product, vendor_phone, qty,commission);
	}
  }


  $(element).parent().prev().children()[1].innerText=elementData.quantity;
  //$(element).parent().prev().children()[0].setAttribute('data-quantity',elementData.quantity); working..

    $(element).parent().parent().parent().children().find(":selected").attr('data-cquan',elementData.quantity);
    // $(element).parent().parent().parent().siblings().find(":selected").attr('data-cquan',elementData.quantity);
   // console.log($(element).parent().parent().parent().siblings().find(":selected").attr('data-cquan'))
   // console.log($(element).parent().parent().parent())
   //console.log($(element).parent().parent().parent().children().find(":selected").attr('data-cquan'))

}
function checkAndAddToCart2(element, combo_product = false) { 
  //alert(1);

 let elementData = element.dataset;

  let [code, name, price, gst, img, quantity,size,vendor_phone,qty,commission] = [elementData.code, elementData.name, elementData.price,
    elementData.gst, elementData.img, elementData.quantity,elementData.size,elementData.vendor_phone,elementData.av_qt,elementData.commission];

  if (!code || !name || !price || !gst || !img || !vendor_phone) { 
    //alert(2);
     //alert(code);
    alert(unexpectedError);
  } else {
    if (!quantity) {
      quantity = 1;
    }
  
  if(quantity > qty) {
    alert("There are only " + qty + " quantity in stock for this size.");
  }else{
    addToCart(code, name, img, price, quantity, gst,size,combo_product, vendor_phone, qty,commission);
  }
  }

 // $(element).parent().prev().children()[1].innerText=elementData.quantity;

    //$(element).parent().parent().parent().children().find(":selected").attr('data-cquan',elementData.quantity);
    $('.size_quantity').find(":selected").attr('data-cquan',elementData.quantity);
    // $(element).parent().parent().parent().siblings().find(":selected").attr('data-cquan',elementData.quantity);
   // console.log($(element).parent().parent().parent().siblings().find(":selected").attr('data-cquan'))
   // console.log($(element).parent().parent().parent())
   //console.log($(element).parent().parent().parent().children().find(":selected").attr('data-cquan'))

}
function checkAndAddToCart3(element, combo_product = false) { 
  //alert(1);

  let elementData = element.dataset;

  let [code, name, price, gst, img, quantity,size,vendor_phone,qty,commission] = [elementData.code, elementData.name, elementData.price,
    elementData.gst, elementData.img, elementData.quantity,elementData.size,elementData.vendor_phone,elementData.av_qt,elementData.commission];
  
    var all_quantity = parseInt(qty);
  
  let showOn = element.dataset.show;
  let currentQuantity = document.querySelector(showOn).textContent;
  
  var a = parseInt(currentQuantity) + 1;
  if (!code || !name || !price || !gst || !img || !vendor_phone) { 
    //alert(2);
     //alert(code);
    alert(unexpectedError);
  } else {
    if (!quantity) {
      quantity = 1;
    }
  
  if(quantity > qty) {
    alert("There are only " + qty + " quantity in stock for this size.");
  }else{
    currentQuantity++;
      document.querySelector(showOn).textContent = currentQuantity;
      console.log('plus')
      $(element).attr('data-quantity', currentQuantity);
      $(element).prev().prev().attr('data-quantity', currentQuantity);
      $(element).parent().parent().parent().children().find(":selected").attr('data-cquan',currentQuantity);
    addToCart(code, name, img, price, quantity, gst,size,combo_product, vendor_phone, qty,commission);
  }
  }


 // $(element).parent().prev().children()[1].innerText=elementData.quantity;

    //$(element).parent().parent().parent().children().find(":selected").attr('data-cquan',elementData.quantity);
    //$('.size_quantity').find(":selected").attr('data-cquan',elementData.quantity);
    // $(element).parent().parent().parent().siblings().find(":selected").attr('data-cquan',elementData.quantity);
   // console.log($(element).parent().parent().parent().siblings().find(":selected").attr('data-cquan'))
   // console.log($(element).parent().parent().parent())
   //console.log($(element).parent().parent().parent().children().find(":selected").attr('data-cquan'))

}



function checkAndAddToCart1(element, combo_product = false) { 
  // alert(1);

  let elementData = element.dataset;

  let [code, name, price, gst, img, quantity,size,vendor_phone,qty,commission] = [elementData.code, elementData.name, elementData.price,
    elementData.gst, elementData.img, elementData.quantity,elementData.size,elementData.vendor_phone,elementData.av_qt,elementData.commission];
	
	var all_quantity = parseInt(qty);
	
	let showOn = element.dataset.show;
	let currentQuantity = document.querySelector(showOn).textContent;

	
	var a = parseInt(currentQuantity) + 1;
	
  if (!code || !name || !price || !gst || !img || !vendor_phone) { 
    // alert(2);
     //alert(code);
    alert(unexpectedError);
  } else {
    if (!quantity) {
      quantity = 1;
    }
		if(a > qty) {
			alert("There are only " + qty + " quantity in stock for this size.");
			
		}else{
    // alert(3);

			currentQuantity++;
      // alert(currentQuantity);
			document.querySelector(showOn).textContent = currentQuantity;
      // console.log($(element).prev().textContent(currentQuantity));      
			$(element).attr('data-quantity', currentQuantity);
			$(element).prev().prev().attr('data-quantity', currentQuantity);
			$(element).parent().parent().parent().children().find(":selected").attr('data-cquan',currentQuantity);
 
			addToCart(code, name, img, price, currentQuantity, gst,size,combo_product, vendor_phone, all_quantity,commission);
		}
  }

    //$(element).parent().parent().parent().children().find(":selected").attr('data-cquan',elementData.quantity);
    //$(element).parent().parent().parent().siblings().find(":selected").attr('data-cquan',elementData.quantity);
   // console.log($(element).parent().parent().parent().siblings().find(":selected").attr('data-cquan'))
   // console.log($(element).parent().parent().parent())
   console.log($(element).parent().parent().parent().children().find(":selected").attr('data-cquan'))

}

function addToCart(code, name, image, price, quantity, gst,size, combo_product = false, vendor_phone, qty,commission, toast = true) {
 localStorage.vendor_phone=vendor_phone;
  //alert(3);
   //alert(code); 
  price = parseFloat(price);
  commission = parseFloat(commission);
  gst = parseInt(gst);
  let product_after_gst = price + ((price / 100) * gst);
  let total_product_after_gst = product_after_gst * parseInt(quantity);
  console.log('product_total_after_gst: ' + total_product_after_gst);


  let product = {
    product_code: code,
    product_name: name,
    product_price: price,
    product_commission: commission,
    product_image: image,
    product_size:size,
    product_vendor_phone: vendor_phone,
    product_gst: gst,
    product_quantity: quantity,
    product_qty: qty,
    product_after_gst: product_after_gst,
    product_total_after_gst: total_product_after_gst,
    combo_product: combo_product
    
  };
  //alert(4);
  
console.log(product);
//return;
  let exist = false;

  if (shopping_cart.length > 0) {
     // alert(5);
    $.each(shopping_cart, function (index, item) {
      //alert(code);
      //alert(price);
      //alert(size);
     if (parseInt(code) === parseInt(item.product_code) && size === item.product_size) {
      

        // alert(item.product_code);
        // alert(item.product_price);
        // alert(item.product_size);

        // console.log('quantity==='+quantity);
        // console.log('item.product_quantity==='+item.product_quantity);

        // item.product_quantity = parseInt(item.product_quantity)+ parseInt(quantity);
        // console.log('item.product_quantity in cart==='+item.product_quantity);

       item.product_quantity++;
        item.product_total_after_gst = total_product_after_gst;
        exist = true;
      }
    });
  }

  if (!exist) {
    //alert(6);
    shopping_cart.push(product);
  }

  if (toast) {
    // alert('Item Has Been Added To The Cart');
  }
  updateCartBadge();
  localStorage['shopping-cart-items'] = JSON.stringify(shopping_cart);
}

function comboToCart(element) {
  let code = {code: element.dataset.code};

  showLoader();
  postFetchRequest('/appcode/fetch_combo_products.php', code)
    .then((res) => {
      console.log(res);
      if (res.status === 1) {
        res.product.forEach((item) => {
          addToCart(item.product_code, item.name, base + "/img/" + item.photo_link, res.average_price, 1, item.gst, true, false);
          alert('Combo has been added into your cart successfully.');
        });
      } else {
        alert(unexpectedError);
      }
      removeLoader();
    })
    .catch((err) => {
      console.error(err);
      alert(unexpectedError);
      removeLoader();
    });
}

function viewProductDetails(element) { //alert(0);return;
 // console.log($(element).children()[0]);
  sessionStorage.code = element.dataset.code;
  sessionStorage.name = element.dataset.name;
  localStorage.similar_product = element.dataset.category_code;
  // sessionStorage.mrp = element.dataset.mrp;
  sessionStorage.price = element.dataset.price;
  sessionStorage.gst = element.dataset.gst;
  sessionStorage.img = $(element).children()[0].src;
//  getPosition();
  console.log(sessionStorage.code); 
  console.log(sessionStorage.name); 
  // console.log(sessionStorage.mrp); 
  console.log(sessionStorage.price); 
  console.log(sessionStorage.gst); 
   console.log(sessionStorage.img); 
   console.log(localStorage.similar_product); 
 // return;
  window.location.href = 'product_details.html';
}

function takeItToAllSpecialProducts(element) {
  console.log(element);
  sessionStorage.specialCategory = element.dataset.category;
  sessionStorage.specialName = element.dataset.name;
  getPosition();

  console.log(sessionStorage.specialCategory)
  console.log(sessionStorage.specialName)
  //return;
  window.location.href = 'feature-product.html';
}




// lkdsflajfd
var id =localStorage['id'];
//alert(id+'l');
function changeOrderQuantity(id){ //alert(0)

var url = base + "/appcode/change_quantity.php";
  $.ajax({
    url: url,
    dataType: "json",
    type: "post",
    data: {id:id},
    success: function (response) {
      console.log(response);
      //alert(1);
    },
    error: function (response) {
      console.log("error response:");
      console.log(response);
      //alert(2);
    },
  })
}


// dlfjaldfjla

// Review -----------
function rev1(ele){
  var code = ele.dataset.code;
  localStorage.code = code;
  window.location.href= "product_review.html"
}

/*** homepage search ***/

let homeSearch = document.querySelector('input[name="search"]');

if (homeSearch) {
  if (homeSearch.dataset.searchPage == "false") {
  // keyup
    homeSearch.addEventListener('keypress', (evt) => { 
      event.preventDefault();
      // if (event.keyCode === 13) {
      sessionStorage.searchFor = homeSearch.value;
      window.location.href = 'search.html';
      // }
    }, false);
  }
}

function openNav() {
  document.getElementById("mySidenav").style.width = "264px";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
}

/***
 * quantity control A.K.A (product quantity plus, minus)
 */

function quantityPlus(element) { //alert(0);
  let plus_button = $(element);
  let showOn = element.dataset.show;
  let affectOn = element.dataset.affect;
  let av_qt =  parseInt($(plus_button).attr('data-av_qt'));
  //let quantity =  parseInt($(plus_button).attr('data-quantity'));

  let currentQuantity = document.querySelector(showOn).textContent;
  
  var a = parseInt(currentQuantity) + 1;
  
	
		
	currentQuantity++;
		
		
 
  //alert(currentQuantity);
  document.querySelector(showOn).textContent = currentQuantity;
        console.log('plus')
  //document.querySelector(affectOn).setAttribute('data-quantity', currentQuantity);
  //console.log(element);
 $(element).attr('data-quantity', currentQuantity);
  $(element).prev().prev().attr('data-quantity', currentQuantity);
 //element.nextElementSibling.nextElementSibling.setAttribute('data-quantity', currentQuantity);

 $(element).parent().parent().parent().children().find(":selected").attr('data-cquan',currentQuantity);
    //$('.size_quantity').find(":selected").attr('data-cquan',elementData.quantity);

  //$('.size_quantity').find(":selected").attr('data-cquan',currentQuantity);
    // if(av_qt > currentQuantity){
      
    //     //alert('a');
    //     //alert(currentQuantity);
    //     //console.log(parseInt(quantity)+parseInt(localStorage.quantity));
    //     quantity = parseInt(currentQuantity);
    //     quantity++;

    //     if (quantity < 0) { 
    //     //alert('b');

    //       //replaceButtons(plus_button);
    //     } else {
    //       //console.log(quantity);
    //       $(currentQuantity).text(quantity);
    //       //alert(1);
    //     //alert('c');

    //       $("plus").attr("data-quantity",currentQuantity);
          
    //       var code = $(element).attr('data-code');
    //       //doToCartByOne(element, quantity, code, 'add');
    //     }


    //   } else{
    //     alert("Sorry you can't add more then "+ av_qt +" AND Out Of Stock");
    //    $(element).attr('disabled',true);

    //   }
       //quantity.text(quantity);
	 
	
}

function quantityMinus(element) { //alert(1);
  let minus_buttonn = $(element);
  let showOn = element.dataset.show;
  let affectOn = element.dataset.affect;
  let minus_button = element.dataset.minius;
  let av_qt =  parseInt($(minus_buttonn).attr('data-av_qt'));

  let currentQuantity = document.querySelector(showOn).textContent;
  if (currentQuantity > 1) {
    currentQuantity--;
  }
  // if (quantity < 1) {
  //     //replaceButtons(minus_button);
      
  //   } else {
  //     console.log(quantity);
  //     $(quan).text(quantity);
  //     $(".product-add-btn").attr("data-quantity",quantity);
  //     var code = $(element).attr('data-code');
  //     //doToCartByOne(element, quantity, code, 'remove');
  //   }
  console.log(minus_button);
  console.log('a');

  document.querySelector(showOn).textContent = currentQuantity;
  $(element).parent().parent().parent().children().find(":selected").attr('data-cquan',currentQuantity);
  //document.querySelector(showOn).textContent = currentQuantity;
 // document.querySelector(minus_button).setAttribute('data-quantity', currentQuantity);
element.setAttribute('data-quantity', currentQuantity);
}

function changeQuantity(quantity, code,size) {  //alert(quantity);
  if (quantity == 0) { //alert("c");
    removeProduct(code,size);
  } else { 
    shopping_cart.forEach((item, index) => {
      if (parseInt(code) == parseInt(item.product_code) && size== item.product_size) {  
        //alert(quantity);
        item.product_quantity = quantity;
        item.product_total_after_gst = parseFloat(item.product_after_gst) * parseInt(item.product_quantity);
        localStorage['shopping-cart-items'] = JSON.stringify(shopping_cart);
        return false;
      }
    });
  }
  window.location.reload();
}

function changeQuantity1(quantity, code,size) { 
console.log(quantity);
//alert(quantity)
  if (quantity == 0 ) { 
   // alert(0);
    removeProduct1(code,size);
  } else {
    shopping_cart.forEach((item, index) => {
      if (parseInt(code) == parseInt(item.product_code) && size == item.product_size) {
      console.log(quantity);
        item.product_quantity = quantity;
        item.product_total_after_gst = parseFloat(item.product_after_gst) * parseInt(item.product_quantity);
     //  console.log(item.product_quantity);
        localStorage['shopping-cart-items'] = JSON.stringify(shopping_cart);
        return false;
      }
    });
  }
  //window.location.reload();
}


/*** cart quantity control ***/
function cartQuantityIncrement(element) {//alert(0);
	var quantity = parseInt(element.dataset.quantity) + 1;
	var qty = parseInt(element.dataset.qty);
	
	if(quantity > qty) {
			alert("There are only " + qty + " quantity in stock for this size.");
	}else{
		changeQuantity(quantity, element.dataset.code,element.dataset.size);
	}
}

function cartQuantityDecrement(element) {
 // if(element.dataset.quantity>1){
  changeQuantity(parseInt(element.dataset.quantity) - 1, element.dataset.code,element.dataset.size);
// }
// else{
//   alert(1);
// }
}

function cartQuantityDecrement1(element) {
  //alert(1)
  changeQuantity1(parseInt(element.dataset.quantity) -1, element.dataset.code,element.dataset.size);
}

/*** device ready event ***/

$(document).ready(function(){

  const profileItem = document.querySelector('#slide-out .profile');
  if (profileItem) {
    loginThenProfile(profileItem);
  }


  /***
   * category side bar adding it into the sidebar
   * @type {Element}
   */

  const categorySideNav = document.querySelector('#mySidenav1');
  let sideCategoryContent = "";
  if (categorySideNav) {

    getFetchRequest('/appcode/fetch_categories_tree.php')
      .then((res) => {
        console.log(res);
        if (res.status === 1) {
          sideCategoryContent += `
           <!-- <ul class="black-text">
              <li style="padding-bottom: 46px">
                <a href="javascript:void(0)" class="closebtn" style="min-height: 94px;background: #524d4d;color: #fff!important;width: 100%;" 
                    onclick="closeNav()">
                  <i class="ion-android-arrow-back" style="color: #fff!important"></i>
                  Main Menu<br> Shop By Category</a>

              </li>-->
  
  
              `;

          res.categories.forEach((category) => {


            if (category.child) {

              sideCategoryContent += `
              <li class="dropdown-submenu" style="">
                <a class="test" tabindex="-1" href="#" class="waves-effect waves-green">
                  ${category.name}`;

              sideCategoryContent += `
                  <i class="fa fa-plus" style="float:right;font-size: 22px!important;"></i>
                </a>
                <ul class="dropdown-menu center" style="display: none;">`;

              category.child.forEach((sub_category) => {
                sideCategoryContent += `
                  <li data-code="${sub_category.category_code}" data-name="${sub_category.name}"
                      data-parent-code="${category.category_code}" data-parent-name="${category.name}" 
                      data-level="2" onclick="decideFaithOfThisCategory(this)">
                    <a href="#" class="waves-effect waves-green">${sub_category.name}</a>
                  </li>`
              });

              sideCategoryContent += `</ul>`;

            } else {
              sideCategoryContent += `
                <li class="dropdown-submenu" style="">
                  <a class="test" tabindex="-1" href="#" class="waves-effect waves-green" 
                    data-code="${category.category_code}" data-name="${category.name}" data-level="1" 
                    onclick="decideFaithOfThisCategory(this)"> 
                      ${category.name} 
                  </a>`;
            }

            //sideCategoryContent += `</li>`;
          });
         // sideCategoryContent += `</ul>`;

          categorySideNav.innerHTML = sideCategoryContent;
        }
      })
      .then(() => {
        $('.dropdown-submenu a.test').on("click", function (e) {
        // console.log($(this).children('i').attr('class')); 
        $(this).next('ul').toggle();
          e.stopPropagation();
          e.preventDefault();
        // var temp1 = $(this).children('i').attr('class');
         
        // return;


        //   $(this).next('ul').toggle();
        //   e.stopPropagation();
        //   e.preventDefault();
          //console.log($(this).children().attr('class')); 
          var temp = $(this).children('i').attr('class');
          //console.log(temp);
          //console.log("fjdl");
          // if(temp1 == "fa fa-plus"){
            if (temp == 'fa fa-plus') {
              $(this).children('i').removeClass('fa-plus');
              $(this).children('i').addClass('fa-minus');
            } else {
              $(this).children('i').removeClass('fa-minus');
              $(this).children('i').addClass('fa-plus');
            }
          // }else{
          //   $(this).children('i').removeClass('fa-plus');
          //     $(this).children('i').addClass('fa-minus');
          // }
        });
      })
      .catch((err) => {
        console.error(err);
      });
  }

  /**
   * checking if writing  permission is granted or not.
   * if(not it will asks for permission.
   */
  // checkPermission();
});

function searchProducts(keyword, appendTo) {

  let results = "";

  showLoader();
  postFetchRequest('/appcode/search_products1.php', {keyword: keyword})
    .then((res) => {
      console.log(res);
      if (res.status === 1) {
        res.products.forEach((item, index) => {

          if(item.quantity != '' && item.quantity != 0){
            var str =item.size;
            //console.log(str); return;
            var split_size = str.split(',');
            str_length = str.split(',').length;
            str_length_new = (str_length-1);
            var str_sec =item.old_price;
            var split_str_sec = str_sec.split(',');
            var str_mrp =item.price;
            var split_str_mrp = str_mrp.split(',');
            var np1 = str_mrp.split(',');

            //console.log(split_size); return;
            var av_qt =item.quantity;
            //alert(av_qt);
            var av_qt1 = av_qt.split(',');
            localStorage.av_qt1 =av_qt1[0];
            // alert(localStorage.av_qt1);
            // <i class="fa fa-shopping-bag" style="color:#fff600;"></i>
          results += `
           <div class="products-details no-padding card">
                      <div class="row" style="margin: 0;">
                        <div class="col s9 no-padding relative product" style="margin: 20px 0px;">
                          <div class="product-add-btnn col s5 no-padding"  onclick="viewProductDetails(this)"
                          data-code="${item.product_code}"data-quantity="1" data-size = "${split_size[0]}" data-name="${item.name}" data-price="${np1[0]}" data-gst="${item.gst}" data-vendor_phone="${item.vendor_phone}">
                            `;
              if(item.discount!=''){
              results += `
              <img src="${base}/img/${item.photo_link}" class="img-responsive product_image_preview" style="position: relative;display: flex; align-items: center; z-index: 99;">

              <div class="discount-offer-box"><p style="color: #fff;font-size:1rem; line-height: 1.2rem;"><b>${item.discount}</b></p></div>`  
              }
              else{
                results += `<img src="${base}/img/${item.photo_link}" class="img-responsive product_image_preview">`;
              }             
                            
              results += `</div>
              <div class="col s7">
                <b class="product_name">${item.name}</b>
                <div class="price-section">`;

                var check=0;
                var qun=0;

                 if (localStorage['shopping-cart-items'] != null) { //alert(0);
                    shopping_cart = JSON.parse(localStorage['shopping-cart-items'].toString());                       
                  for(var k=0; k<shopping_cart.length;k++){
                    if(parseInt(shopping_cart[k].product_code) == parseInt(item.product_code) && shopping_cart[k].product_size == split_size[0]){         
                      check=1;
                      //alert();
                      qun = shopping_cart[k].product_quantity;
                      }     
                  }
                }


        if(str !=''){
            results+='<select class="size_quantity" onchange="changeSize(this)">'
            for( j=0;j<=str_length_new;j++){
              if(str_mrp.split(',')[j]==undefined){
                    var str_mrp_new = 0;
                }else{
                    var str_mrp_new = str_mrp.split(',')[j];
                }

            results+='<option value="'+str.split(',')[j]+'"  data-cquan="';
                  var selquan=0;
                   if (localStorage['shopping-cart-items'] != null) { //alert(0);
                  shopping_cart = JSON.parse(localStorage['shopping-cart-items'].toString());              
                for(var k=0; k<shopping_cart.length;k++){
                  if(parseInt(shopping_cart[k].product_code) == parseInt(item.product_code) && shopping_cart[k].product_size == str.split(',')[j]){
                      selquan = shopping_cart[k].product_quantity;
                  }             
                }
              }/// 
                  results+=selquan;
                  results+= '"data-av_qt="'+av_qt1[j]+'" data-gst='+item.gst+' price-new='+str_sec.split(',')[j]+' data-id='+item.id+' mrp-new='+str_mrp_new+'>'+str.split(',')[j]+'</option>'
            }
            results+='</select>';
        }
        results +='<p class="price-section2">';
        results +='MRP:-<span class="old-price price_new fa fa-inr">'+str_sec.split(',')[0]+'</span>';
        results +='</p>';
        results +='<span class="price-section1">'
        // products +=''+item.price+''
        if(str_mrp.split(',')[0] !=''){  
        results+='Rs.'; 
        }
        results+='<span class="mrp_new">'+str_mrp.split(',')[0]+'</span>'
        results +='</span>';
// <i class="fa fa-shopping-bag" style="color:#1bcb22;"></i>
                            results+=`</div>
                          </div>
                        </div>

                        <div class="col s3 no-padding text-center" style="margin: 40px 0px 0px 0px;">`;
                            if(check == 1){
                              results += `<div class="product-quantity-control setpad " style="margin:10px -5px;">
                                         <div class="item-quan-minus add_val" onclick="cartQuantityDecrement1(this);quantityMinus(this);"  data-code="${item.product_code}" data-vendor_phone="${item.vendor_phone}" data-name="${item.name}" data-minius='item-quan-minus' data-gst="${item.gst}" data-show=".item-quan-show-${index}"
                                        data-affect=".addToCart-${index}" data-av_qt="${av_qt1[0]}" data-quantity="${qun}" data-price="${np1[0]}" data-img="${base}/img/${item.photo_link}" data-size = "${split_size[0]}">
                                        <i class="fa fa-minus p-font"></i>
                                        </div>

                                        <div class="item-quan-show-${index} show_qun">${qun}</div>
                                        
                                        <div class="item-quan-plus add_val" onclick="checkAndAddToCart1(this);" data-show=".item-quan-show-${index}" data-code="${item.product_code}" data-name="${item.name}" data-gst="${item.gst}" data-vendor_phone="${item.vendor_phone}"
                                        data-affect=".addToCart-${index}" data-av_qt="${av_qt1[0]}" data-quantity="1" data-price="${np1[0]}" data-img="${base}/img/${item.photo_link}" data-size = "${split_size[0]}">
                                        <i class="fa fa-plus p-font"></i>
                                        </div>
                                       
                                      </div>`;
                             results+=`<div class="product-quantity-control product-add-btn hide " style="border-radius: 10px 10px;width: 60px;    margin: 5px 0px 0px 5px;">
                                       <a class="product-add-btnn addToCart-${index}" onclick="checkAndAddToCart(this);" data-quantity="1" data-size = "${split_size[0]}" data-code="${item.product_code} " data-name="${item.name}" data-price="${np1[0]}" data-gst="${item.gst}" data-vendor_phone="${item.vendor_phone}" data-img="${base}/img/${item.photo_link}" style="border-radius:10px 10px;color:white!important;width:50px;margin: 0px 0px 0px 10px;">ADD
                                      </a>
                                      </div>
                                      `;

                            } else{
                              results+=`<div class="product-quantity-control hide">
                                        <div class="item-quan-minus" onclick="cartQuantityDecrement1(this);quantityMinus(this);"  data-code="${item.product_code}" data-vendor_phone="${item.vendor_phone}" data-name="${item.name}" data-minius='item-quan-minus' data-gst="${item.gst}" data-show=".item-quan-show-${index}"
                                        data-affect=".addToCart-${index}" data-av_qt="${av_qt1[0]}" data-quantity="${qun}" data-price="${np1[0]}" data-img="${base}/img/${item.photo_link}" data-size = "${split_size[0]}">
                                        <i class="fa fa-minus p-font"></i>
                                        </div>

                                        <div class="item-quan-show-${index}" >1</div>
                                        
                                        <div class="item-quan-plus" onclick="quantityPlus(this);checkAndAddToCart(this);" data-show=".item-quan-show-${index}" data-code="${item.product_code}" data-name="${item.name}" data-gst="${item.gst}" data-vendor_phone="${item.vendor_phone}"
                                        data-affect=".addToCart-${index}" data-av_qt="${av_qt1[0]}" data-quantity="1" data-price="${np1[0]}" data-img="${base}/img/${item.photo_link}" data-size = "${split_size[0]}">
                                        <i class="fa fa-plus p-font"></i>
                                        </div>
                                        
                                      </div>`;
                              results+=`<div class="product-quantity-control product-add-btn" style="margin:5px 0px 0px 10px;border-radius: 10px 10px;width: 60px;">
                                       <a class="product-add-btnn addToCart-${index}" onclick="checkAndAddToCart(this);" data-quantity="1" data-size = "${split_size[0]}" data-code="${item.product_code} " data-name="${item.name}" data-price="${np1[0]}" data-gst="${item.gst}" data-vendor_phone="${item.vendor_phone}" data-img="${base}/img/${item.photo_link}" style="border-radius:10px 10px;color:white!important;width:50px;margin: 0px 0px 0px 0px;">ADD
                                      </a>
                                      </div>`;

                            } 
                  
              }

                          results+=`</div>`;
                          if(localStorage['favourite-items']!= null && localStorage['favourite-items']!= "" && localStorage['favourite-items'].length!=2) {
                      favouriteItems = JSON.parse(localStorage['favourite-items'].toString());
                      //displayFavouriteItems() 
                      //console.log(favouriteItems.length);
                       var alreadyexists=0;
                      
                      for(var i=0; i<favouriteItems.length; i++){
                          var cur = favouriteItems[i];
                          // console.log(cur.product_code);
                          if (parseInt(cur.product_code) == parseInt(item.product_code)) {
                                      alreadyexists=1;                        
                                  }
                              }
                        // if(favouriteItems[i].product_code == item.product_code){
                        if(alreadyexists==0){
                        console.log(cur.product_code +"=="+ item.product_code);
                          results+=`<div class="col s1" style = "margin:20px 0px 0px -58px;" onclick="viewBagDetails(this)">
                            <i class="fa fa-heart add-to-favourite" data-quantity="1" data-id="${item.id}" data-size = "${split_size[0]}" data-code="${item.product_code} " data-name="${item.name}" data-price="${np1[0]}" data-gst="${item.gst}" data-vendor_phone="${item.vendor_phone}" data-img="${base}/img/${item.photo_link}" style="font-size: 18px!important;padding: 5px;display:flex;justify-content:center;color:#1bcb22;"></i>
                        </div>`;
                        }else{
                          results+=`<div class="col s1" style = "margin:20px 0px 0px -58px;" onclick="viewBagDetails(this)">
                            <i class="fa fa-heart add-to-favourite" data-quantity="1" data-id="${item.id}" data-size = "${split_size[0]}" data-code="${item.product_code} " data-name="${item.name}" data-price="${np1[0]}" data-gst="${item.gst}" data-vendor_phone="${item.vendor_phone}" data-img="${base}/img/${item.photo_link}" style="font-size: 18px!important;padding: 5px;display:flex;justify-content:center;color:red;"></i>
                          </div>`;

                        }
                      // }
                      }else{
                        results+=`<div class="col s1" style = "margin:20px 0px 0px -58px;" onclick="viewBagDetails(this)">
                            <i class="fa fa-heart add-to-favourite" data-quantity="1" data-id="${item.id}" data-size = "${split_size[0]}" data-code="${item.product_code} " data-name="${item.name}" data-price="${np1[0]}" data-gst="${item.gst}" data-vendor_phone="${item.vendor_phone}" data-img="${base}/img/${item.photo_link}" style="font-size: 18px!important;padding: 5px;display:flex;justify-content:center;color:#1bcb22;"></i>
                          </div>`;

                      }

                          // <div class="col s1" style = "margin:20px 0px 0px -62px;" onclick="viewBagDetails(this)">
                          //   <i class="fa fa-heart add-to-favourite" data-quantity="1" data-size = "${split_size[0]}" data-code="${item.product_code} " data-name="${item.name}" data-price="${np1[0]}" data-gst="${item.gst}" data-vendor_phone="${item.vendor_phone}" data-img="${base}/img/${item.photo_link}" style="font-size: 18px!important;padding: 5px;display:flex;justify-content:center;color:#1bcb22;"></i>
                          // </div>
                        results+=`</div>
                      </div>
                    </div>`;
                  
                
        });

      } else if (res.status === 2) {
        results += `<p class="red-text text-darken-2">Sorry, there are no products matched with your search.</p>`;
      } else {
        results += `<p class="red-text text-darken-2">${unexpectedError}</p>`;
      }
      appendTo.innerHTML = results;
      removeLoader();
    })
    .catch((err) => {
      console.error(err);
      alert(unexpectedError);
      removeLoader();
    });
}

function addCouponShopping(element) {

  let offerCode = {
    code: element.dataset.couponCode,
  };
  showLoader();
  postFetchRequest('/appcode/is_this_offer.php', offerCode)
    .then((res) => {
      console.log(res);
      if (res.status === 1) {
        sessionStorage['pre_coupon'] = JSON.stringify(res.value);
      } else {
        alert(unexpectedError);
      }
      removeLoader();
    })
    .catch((err) => {
      console.log(err);
      removeLoader();
    });
 alert("Your selected offer has been applied successfully now add minimum amount items in " +
    "cart to avail offer discount.");
  window.location.href = 'index.html';
}

function updateCartBadge() { 
  cartCount = shopping_cart.length;
  if (cartBadge) {
  
    cartBadge.textContent = cartCount;
    cartBadge.style.display = 'flex';
  }
}

function showComboDetails(element) {
  sessionStorage.comboCode = element.dataset.code;
  window.location.href = 'combo-details.html';
}

/*** refer & earn ***/
//share this app code starts here
const referEarn = document.querySelectorAll('.refer-earn');
if (referEarn) {

  referEarn.forEach((share) => {
    share.onclick = (evt) => {
      evt.preventDefault();

      if (checkLogin()) {

        let userDetails = JSON.parse(localStorage['userDetails'].toString());

        window.plugins.socialsharing.share(`Your friend ${userDetails.name} has shared this app with you named as Oranze Bird. Here is the link to download.`,
          `cityneed`, null, `https://play.google.com/store/apps/details?id=com.oranzebird.app`, `Share Oranze Bird`);
      } else {
        alert("Please login if you want to refer your friend.", 3000);
      }
    }
  });
}

/*** refer & earn ends ***/

/*** setting profile values ***/
function setPersonalProfile(items, target) {

  if (items.name) {
    target.querySelector('.name .text').textContent = items.name;
  } else {
    target.querySelector('.name .text').textContent = "Not Set";
  }

  if (items.email) {
    target.querySelector('.email .text').textContent = items.email;
  } else {
    target.querySelector('.email .text').textContent = "Not Set";
  }

  if (items.phone) {
    target.querySelector('.phone .text').textContent = items.phone;
  } else {
    target.querySelector('.phone .text').textContent = "Not Set";
  }

  /*if (items.gender) {
    target.querySelector('.gender .text').textContent = items.gender;
  } else {
    target.querySelector('.gender .text').textContent = "Not Set";
  }*/

  if (items.address) {
    target.querySelector('.address .text').textContent = items.address;
  } else {
    target.querySelector('.address .text').textContent = "Not Set";
  }

  /*if (items.dob && items.dob !== '0000-00-00') {
    target.querySelector('.dob .text').textContent = items.dob;
  } else {
    target.querySelector('.dob .text').textContent = "Not Set";
  }*/
}

/*** set profile name & image ***/
function setProfileHeader(items, target) {
  if (items.profile_pic) {
    target.querySelector('.profile-pic img').src = base + "/img/" + items.profile_pic;
  } else {
    target.querySelector('.profile-pic img').src = "img/taazakhao.jpeg";
  }

  target.querySelector('.name').textContent = items.name;
}

function viewInvoice(element) {
  sessionStorage.orderId = element.dataset.id;
  window.location.href = 'invoice.html';
}


function checkPermission() {
  const permissions = cordova.plugins.permissions;
  permissions.checkPermission(permissions.WRITE_EXTERNAL_STORAGE, (status) => {
    if (status.hasPermission) {
      console.log("Yes :D ");
    }
    else {
      console.warn("No :( ");
      askPermissions();
    }
  }, () => {
    console.error("Error occurred while processing.");
  });
}

function askPermissions() {
  const permissions = cordova.plugins.permissions;
  const allPermissions = [permissions.WRITE_EXTERNAL_STORAGE];

  permissions.requestPermissions(allPermissions, (status) => {
    console.log("Status");
    console.log("permission granted :D");
  }, () => {
    console.log("error :(");
  });
}


  // .....................notification.....

document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
      var push = PushNotification.init({android: {"senderID": "541496723883", icon: "icon", iconColor: "blue",vibrate: true }});
      push.on('registration', function (data) {
        console.log(data);
        //alert(data.registrationId);
       // localStorage.registrationId= data.registrationId;
      // alert(localStorage.registrationId);

      deviceRegi(data.registrationId);
        
      });


       push.on('notification', function (data) {
        console.log(data);
        window.location.href = 'notification.html';
      });
      push.on('error', function (e) {
        console.log(e);
        alert(e.message);
      });
    }



function deviceRegi(id){
    

     // AAAAfhO4Sas:APA91bG1gL6B46jVpCMv76b5d_JAy2sYGGtJH1pIdwycz7utzz3h3Ww6myUE1pPCLc5OYbj1LZkuDYOPPoxzkAt3G6dC4NNETqIt1apu_h4chCTsdnMTKVZDz_vpNK4s8oNuH9sn4Bs-
  var device_username = localStorage.username;
  // var device_name = localStorage.name;
  let get_name = JSON.parse(localStorage.userDetails.toString());
  var device_name = get_name.name;
  var device_user = id;

  
    $.ajax({
      url: base + "/appcode/register_device.php",
      data: {username:device_username,name:device_name,device_id:device_user},
      type: "post",
      dataType: "json",
      success: function (response) {
        //alert(response.status);
        console.log("Registration Success");
        console.log(response);
        localStorage.deviceRegister = response.status;
      },
      error: function (response) {
        console.log("Registration Error");
        console.log(response);
      }
    });
}



function getCurrentAddress() {
    
    //alert(ff)
  navigator.geolocation.getCurrentPosition(onSuccess, onError);
}

function onSuccess(position) {
       
    var lat = position.coords.latitude; 
    var lng = position.coords.longitude; 
    
   getAddress(lat,lng);    
   initMap(lat,lng);     
}

    
function onError(error) {
   console.log('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
	getAddress(28.4723641,77.01968620000002);   
	//initMap(28.4723641,77.01968620000002);   
	initMap(28.7041,77.1025);   
    //document.querySelector('textarea[name="address"]').value = 'results[1].formatted_address';
 }

 function getAddress(lat,lng){
   
   var geocoder = new google.maps.Geocoder;
        var latlng = {lat: lat, lng: lng};
        geocoder.geocode({'location': latlng}, function(results, status) {
          if (status === 'OK') {
            if (results[0]) {
             
            var current_address = document.getElementById('address').value=(results[0].formatted_address);
              localStorage.c_address = lat+','+lng;
			  localStorage.current_address = current_address;
			 
            }

        }
      });  
 }




 /*** set profile name & image ***/
function setProfileHeader(items, target) {
// console.log(items);
  if (items.profile_pic) {
    
    target.querySelector('.profile-pic img').src = base + "/img/" + items.profile_pic;
  } else {
    
    target.querySelector('.profile-pic img').src = "img/boy1.png";
  };

  
}


// forgot password 
$(document).ready(function(){
  $('#main-container').on('click', '.send_otp_forgot_password', function () {
    //console.log('ddsafr');
    var patt = new RegExp("^([0|\+[0-9]{1,5})?([6-9][0-9]{9})$");
    var phone = $('input[name="phone"]').val();
    var res = patt.test(phone);
    // alert(res);return;
    if(res){

		var type = 'forgot';

		var empty = true;

		if (!phone) {
		  empty = true;

		} else {
		  empty = false;
		}

		if (empty == false) {

		  var forgot_pass_data = {
			phone: phone,
			type: type
		  };
      // console.log(forgot_pass_data);return;
		  localStorage['forgot-pass-data'] = JSON.stringify(forgot_pass_data);
		  // alert("tes");
		  var url =
			base + "/appcode/generateotp_register.php";
		  var tempLogin = false;
		  $.ajax({
			url: url,
			type: "post",
			data: forgot_pass_data,
			dataType: "json",
			success: function (response) {
			  console.log(response);
			  if (response == 1) {
				alert('OTP Sent!');
			  }
			  else{
				alert('your phone no. is not registered!!!!!');
			  }

			},
			error: function (response) {
			  //console.log("Error Log");
			  console.log(response);
			},

			complete: function () {
			  $(".supreme-container").css("display", "hide");
			}
		  }); // ajax request ends

		}
    }

  });


  $('.main-container').on('click', '.change_password-button', function () {
    var otp_code = $('input[name="otp_code"]').val();
    var new_pass = $('input[name="new_password"]').val();
    if (otp_code && new_pass) {
      var url = base+"/appcode/check_otp_register.php";
      var forgot_data_check = JSON.parse(localStorage['forgot-pass-data'].toString());
      var phone = forgot_data_check['phone'];

      var type = 'forgot';
      //console.log(register_data_check);

      var data_for_check = {
        otp_code: otp_code,
        phone: phone,
        type: type,
        new_pass: new_pass

      };
      console.log(data_for_check);
      $.ajax({
        url: url,
        type: "post",
        data: data_for_check,
        dataType: "json",
        success: function(response) {
          console.log(response);

          if (response.status == 1) {
           alert('Now Your Password Successfully Changed.');
            window.location.href = 'login.html';
          } else if (response.status == 0) {
           alert('Incorrect OTP!');
          } else {
            $('.contact-heading').prepend("<h5 class='green-text center-align'>Sorry could not able to submit, Please try again.</h5>");
          }
          console.log("Success Log");
        },
        error: function error(response) {
          console.log("Error Log");
          // console.log(response);
        },
        beforeSend: function beforeSend() {
          $('body').append("<div class='supreme-container'><div id='loader'></div></div>");
          $(".supreme-container").css("display", "block");
        },
        complete: function complete() {
          $(".supreme-container").css("display", "none");
        }
      }); // ajax request ends
    } else {
     alert('Enter OTP And New Password First!');
    }
  });
});



function fetchOrderId(uniqueId) {

 // alert(uniqueId);
 url = base + "/appcode/fetch_order_id.php";
  $.ajax({
    url:url,
     type: "post",
    dataType:"JSON",
    data: {uniqueId: uniqueId},

success: function (response) {
  //alert(response.id);
  var orderId = response.id;
  localStorage.orderId = orderId;
 // showId(response.id);


},
  });
}





$(document).ready(function(){
   $.ajax({
        url: base + "/appcode/fetch_delivery_charge.php",
        type: "post",
        dataType:"json",
        success: function(response) {

          localStorage.delivery_ch = response.delivery_charge;
          localStorage.charged_order_amt = response.charged_order_amount;
          console.log("success");
          console.log(response);  
        },
        error: function(error) {
          console.log("Error");
          console.log(error);
        },
        complete: function() {
          $('.supreme-container').hide();
        }
      });

 });


$(document).ready(function(){
  

//call product by  subcategory
  $('#main-container').on('click','.all_product', function(evt) {
    evt.preventDefault();
    var product = $(this);
    var product_id = product.attr('data-id');
    var product_name = product.attr('data-name');
    var product_code = product.attr('data-code');
    //alert(product_code);
    localStorage.product_code = product_code;
    localStorage.product_name=product_name;
    window.location.href = 'product.html';
  });



 });


  var allFilters = document.querySelector('.all-filters');
  if (allFilters) {
    allFilters.onsubmit = function (e) {
      e.preventDefault();

      var form = new FormData(allFilters);

      sessionStorage.min_price = form.get('min_price');
      sessionStorage.max_price = form.get('max_price');
      sessionStorage.colors = form.get('colors');
      sessionStorage.sizes = form.get('sizes');
      sessionStorage.brand = form.get('brand');

      if (form.get('sizes') == null) {
        sessionStorage.sizes = 0;
      }

      if (form.get('colors') == null) {
        sessionStorage.colors = 0;
      }
       if (form.get('brand') == null) {
        sessionStorage.brand = 0;
      }

      window.location.href = 'filtered-products.html';
    };
  }

  

$(document).ready(function(){
  var username = localStorage.username;
  var rating_order_id = sessionStorage.id;
  var product_id = sessionStorage.product_id;
  var product_code = sessionStorage.product_code;
  var url =base + "/appcode/show_review.php";
   // console.log(rating_order_id)
   // console.log(username)
   // console.log(product_id)
   // console.log(product_code)

  $.ajax({
      url:url,
      data:{username:username,rating_order_id:rating_order_id,product_id:product_id,product_code:product_code},
      dataType:"json",
      type:"post",
      success:function(response){
        // console.log(response + 'abc')

        console.log("rating " + response);

        for(var i =1;i<=response;i++){
        $('#'+i).addClass("star");
    }
        // if(response == 5)
        // {
        //   $(".s5").addClass("star");
        //   $(".s4").addClass("star");
        //   $(".s3").addClass("star");
        //   $(".s2").addClass("star");
        //   $(".s1").addClass("star");

        // } 
        // else if(response == 4){
        //   $(".s4").addClass("star");
        //   $(".s3").addClass("star");
        //   $(".s2").addClass("star");
        //   $(".s1").addClass("star");
        // }
        // else if(response == 3){
        //   $(".s3").addClass("star");
        //   $(".s2").addClass("star");
        //   $(".s1").addClass("star");
        // }
        // else if(response == 2){
        //   $(".s2").addClass("star");
        //   $(".s1").addClass("star");
        // }
        // else if(response == 1){
        //   $(".s1").addClass("star");
        // }
      }
  }); 


//=====================================//

/*** checkout functionality ***/

const checkout_form = document.querySelector('.checkout-form');
//console.log(checkout_form)
if (checkout_form) {
 

  checkout_form.onsubmit = (e) => {
   
    showLoader();
    e.preventDefault();

    let formData = new FormData(checkout_form);
    let uniqueId = randomString(40, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
    let total = findCartTotal();
    var t = localStorage.ttt;
    let isLogin = checkLogin();
    console.log(total)
    console.log(t)
    sessionStorage.uniqueId=uniqueId;
    let userDetails = {};
    if (checkLogin()) {
      userDetails = JSON.parse(localStorage['userDetails'].toString());
    } else {
      userDetails = {
        username: "",
        phone: "",
        email: "",
      };
    }
       if(total < localStorage.charged_order_amt){
      var del_charges = localStorage.delivery_ch;
    }
    else{
      var del_charges = 0;
    }

     if(localStorage['cashback']==undefined)
     {
      var cashback = 0;
     } else{
      var cashback = parseInt(localStorage['cashback']);
     }

    let form_details = {
      walletUsername: userDetails.username,
      walletPhone: userDetails.phone,
      walletEmail: userDetails.email,
      name: formData.get('name'),
      email: formData.get('email'),
      phone: formData.get('phone'),
      address: formData.get('address'),
	    delivery_date: formData.get('delivery_date'),
      delivery_time: formData.get('delivery_time'),
     
      pincode: localStorage.pin,
      delivery_charge:del_charges,
  
      uniqueId: uniqueId,
      subtotal: localStorage.subTotal,
      total: t,
      payment_method: formData.get('payment_method'),
      type: "App",
      order_type: "Shopping",
      vendor_phone : localStorage.vendor_phone,
      commission :  localStorage.total_commission,
	    c_address: localStorage.c_address,
      cashback:cashback,
      coupon_price:localStorage.dis_amount,
      coupon_code:localStorage.coupon_code
    };
// console.log(form_details);return;
    

    let coupon = "";

   
      if (localStorage.coupon_applied) {
        coupon = JSON.parse(localStorage['coupon_applied'].toString());
      } else{
        // localStorage['coupon_applied'] = JSON.stringify(response.value);
           if(localStorage['cashback_applied']!=null){
           coupon = JSON.parse(localStorage['cashback_applied'].toString());
      }
    }

  
       if (form_details.name && form_details.email && form_details.phone && form_details.address) {

      let shoppingCart = JSON.parse(localStorage['shopping-cart-items'].toString());

      let fetchPram = {
        credentials: "same-origin",
        method: "POST",
        headers: {
          'Accept': 'application/json',
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          data: form_details,
          cart: shoppingCart,
          coupon: coupon
        })
      };

      fetch(base + "/appcode/checkout.php", fetchPram)
      .then((response) => response.json())
      .then((responseData) => {
        // console.dir(responseData);
        console.log(responseData);
        if (responseData.status === 1) {
         
               fetchOrderId(form_details.uniqueId);
          
              //sendNotification(responseData.uniqueId);
          if (form_details.payment_method === "pay_u") {
            gotoPage(responseData.uniqueId);
          }else {
         


              $.ajax({
              url: 'https://dtuat.com/apps/cityneed/appcode/send_sms.php',
              data: {uniqueId: sessionStorage.uniqueId},
              dataType: 'json',
              type: 'POST',
              success: function(res){
                console.log('Successfully');
                console.log(res);
              },
              complete: function(){
               alert('Your Order Placed Successfully!');
                changeOrderQuantity(localStorage['id']);
            //alert('Payment Compvared Successfully.');
            localStorage.removeItem('shopping-cart-items');
            localStorage.removeItem('deliveryCount');
            shopping_cart = [];
            localStorage.removeItem('special_name');
            localStorage.removeItem('totalAmount');
            localStorage.removeItem('coupons_code');
            localStorage.removeItem('coupon_amount');

            //alert(`Your Order has been placed successfully.` );
            window.location.href = "index.html";
          }
        });
          }

        } else if (responseData.status === 2) {
         alert(unexpectedError);
        } else if (responseData.status === 3) {
         alert("Sorry, you don't have enough balance in your wallet.");
        } else if (responseData.status === 4) {
         alert("Sorry an error occurred please logout and login and try again.");
        } else if (responseData.status === 5) {
         alert("sorry an unexpected error occurred while processing your request, " +
            "please try again by re-selecting payment method", 6000);
        } else if (responseData.staus === 0) {
         alert("Please fill all fields and try again.");
        } else if (responseData.status === 99) {
         alert(unexpectedError);
        } else {
         alert(unexpectedError);
        }
        removeLoader();
        /*** if success then go to payU ***/
        //gotoPage();
      })
      .catch((error) => {
        console.log("error");
        // console.dir(error);
        removeLoader();
       alert(unexpectedError);
      });

      

    } else {
      removeLoader();
     alert('Please fill all the details and try again.');
    }

      

         

  };
}



//=====================================//
/*** faq send message method starts ***/
$('#main-container').on('click', '.question', function (evt) {
    evt.preventDefault();
    var message = $("textarea[name='message']").val();
  if (message!="") {
    $.ajax({
      url: base+'/appcode/faq_message.php',
      data: {message:message},
	  dataType:'json',
	  type: 'post',
      success: function(response) {
            console.log(response);
            if (response === 1) { 
              //alert("Your Query is successfully sent.");
			  alert("Your Query is successfully sent.");
			  location.reload();
            } else if (response.status === 2) { 
              /*** unexpected error (everything received but couldn't proceed. ***/
              alert("Sorry, there is already a user with the following details.");
            } else if (response.status === 0) {
              /*** one of the fields is empty ***/
              alert("Please fill all fields and try again.");
            } else {
              alert(unexpectedError);
            }
            //removeLoader();
            },
            error :function(error){
              console.error(error);
            //removeLoader();
            alert(unexpectedError);
            }
    });
    } else {
     alert('Please write your Question...');
    }
});
});

$(document).ready(function(){


/*** Add Wholeselle Profile ***/

let updateProfile = document.querySelector('.add-wholesale-profile');
if (updateProfile) {
  updateProfile.onsubmit = (e) => {
    e.preventDefault();
    showLoader();

    let formData = new FormData(updateProfile);

    let oldDetails = JSON.parse(localStorage['userDetails'].toString());
    let userDetails = {
      name: formData.get('name'),
      email: formData.get('email'),
      phone: oldDetails.phone,
      // dob: formData.get('dob'),
      address: formData.get('address'),
      city: formData.get('city'),
      description: formData.get('description'),
     
    };
    // console.log(oldDetails); //return;
    // console.log(userDetails); return;

    postFetchRequest('/appcode/add_wholesele.php', userDetails)
      .then((response) => {
        console.log(response);
        if (response.status === 1) {
          // alert("You are requesting successfully for Wholesale");
          alert("You are requesting successfully for Wholesale");
          window.location.href = 'index.html';
          // localStorage.userDetails = JSON.stringify(userDetails);
        } else if (response.status === 2) {
          alert(response.msg);
          window.location.href = 'index.html';
          alert(unexpectedError, 4000);
        } else if (response.status === 3) {
          alert(response.msg, 4000);
        } else if (response.status === 0) {
          alert("Please fill all fields and try again.", 4000);
        } else if (response.status === 99) {
          alert(unexpectedError, 4000);
        } else {
          alert(unexpectedError, 4000);
        }
        removeLoader();
      })
      .catch((error) => {
        console.log(error);
        removeLoader();
        alert(unexpectedError, 4000);
      });
  }
}

/*** update profile ends ***/

});


