/*jshint esversion: 6 */
// ! Drop Down Menu function for Cart
let dropDownCartStatus = false;
let toggleNavStatus = false;
// ! For updating cart items
let $clickedBtn;
let $clickedForm;
let $clickedFormTag;
let quickBuy = false;
// For My Account Tab
let dropDownStatus2 = false;
let itemFormSubmission;
// Translations
let $submittedForm;
let updateText;
let updateCart;
let cartLoad = false;
let currencyLang = $('meta[name=currency]').attr("content");
let path;
let sumItems;
let outOfStock = "Out of stock";
let free = "Free";
let getDimensions;
let q8Currency;
if ($('html').attr("lang") === "ar") {
path = "/";
q8Currency = "دينار";
} else {
path = window.location.origin + "/en/";
q8Currency = "KWD";
}
$(document).on("click", '.prev-card, .next-card', function (e) {
if ($(this).hasClass("prev-card")) {
$(this).parent().find('.cards-slider').animate({
scrollLeft: "-=775px"
}, 700);
} else {
$(this).parent().find('.cards-slider').animate({
scrollLeft: "+=775px"
}, 700);
}
});
// ! Sync Quantity and Price
let syncPriceQuantity = function () {
sumPrice = 0.0;
sumQuantity = 0;
$('.cart-price-overlay').each(function () {
sumPrice += Number(parseFloat($(this).text()));
});
$('.cart-form-overlay .quantity-input').each(function () {
sumQuantity += Number(parseInt($(this).val()));
});
$(".cart-items-number-overlay").text(sumQuantity);
$(".total_price-overlay .totals").text(sumPrice.toFixed(3) + " " + currencyLang);
};
syncPriceQuantity();
// ! Active Anchor
const checkActiveMenu = function () {
let menu = document.querySelectorAll('.nav_menu li a');
for (let i = menu.length - 1; i >= 0; i--) {
if (menu[i].href == document.URL) {
menu[i].setAttribute("class", "active-anchor");
}
if (menu[i].href != document.URL) {
menu[i].setAttribute("class", "");
}
}
};
// {# Recaptcha function #}
function reloadRecaptcha(pageName) {
grecaptcha.ready(function () {
grecaptcha.execute($('meta[name=recaptcha]').attr("content"), {
action: pageName
}).then(function (token) {
var recaptchaResponse = document.getElementsByClassName('recaptcha_response');
var i;
for (i = 0; i < recaptchaResponse.length; i++) {
recaptchaResponse[i].value = token;
}
});
});
}
$(document).ready(function () {
// {# Google Analytics #}
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', $('meta[name=analytics]').attr("content"));
// // {# Reload page if back button pressed #}
// window.addEventListener("pageshow", function (event) {
// var historyTraversal = event.persisted ||
// (typeof window.performance != "undefined" &&
// window.performance.navigation.type === 2);
// if (historyTraversal) {
// // Handle page restore.
// window.location.reload();
// }
// });
function ulDropDown(data, open) {
if ($(data).next().height() > 0) {
$(data).children().removeClass("animate_arrow").addClass("animate_arrow_up");
$(data).next().css({
"visibility": "hidden",
"height": "0"
});
} else {
if (open) {
$(data).next().css({
"visibility": "visible",
"height": "250px"
});
$(data).children().removeClass("animate_arrow_up").addClass("animate_arrow");
}
}
}
$(document).mouseup(function (e) {
let container = $(".menu, .menu2");
let searchContainer = $(".search-div");
// if the target of the click isn't the container nor a descendant of the container
if (!container.is(e.target) && container.has(e.target).length === 0 && e.target.id != "cart-img" && e.target.id != "toggle_icon") {
if (dropDownCartStatus === true) {
$("#cart-img").trigger("click");
}
if (toggleNavStatus === true) {
$("#toggle_icon").trigger("click");
}
$('.account_desktop>a').each(function () {
ulDropDown(this, false);
});
}
if (!searchContainer.is(e.target) && searchContainer.has(e.target).length === 0) {
$(".search-result").css("display", "none");
}
});
if ($('html').attr("lang") === "ar") {
free = "مجاناً";
outOfStock = "غير متوفر";
}
$(".stock-check").each(function () {
stockCheck = (parseInt($(this).attr("stock")))
if (stockCheck <= 0) {
$(this).parent().parent().parent().append("" + outOfStock + "");
$(this).parent().parent().remove();
}
});
// ! Currency Tab
$(document).on("click", '.currencies', function () {
if ($(".currencies ul").height() === 0) {
$(".currencies ul").css("height", "190px");
$(".currencies .fas").removeClass("animate_arrow_up").addClass("animate_arrow");
} else {
$(".currencies ul").css("height", "0");
$(".currencies .fas").removeClass("animate_arrow").addClass("animate_arrow_up");
}
});
$(document).on("click", '.currencies ul li', function () {
$(".currencies>li").appendTo(".currencies>ul");
$(this).appendTo(".currencies");
$.ajax({
type: "POST",
url: path + "currency/",
data: {
currency: $(this).children("img").attr('id'),
csrfmiddlewaretoken: $('meta[name=csrfmiddlewaretoken]').attr("content")
},
success: function () {
window.location.reload();
}
});
});
// ! Search bar
$(document).on("input", '.search-input', function (e) {
e.preventDefault();
if ($(this).val().length > 1) {
$(".search-result").empty().append("").css("display", "grid");
search_form = $(this).parent();
search_url = search_form.attr('action');
$.ajax({
type: "POST",
url: search_url,
data: search_form.serialize(),
dataType: 'html',
success: function (html) {
$(".search-result").empty().append(html);
}
});
} else {
$(".search-result").css("display", "none");
}
});
$(document).on("click", '#cart-img', function () {
// Does not work on Cart and Checkout pages
if (document.location.href.indexOf('checkout') === -1 && document.location.href.indexOf('cart') === -1) {
// Show or Hide side bar
if (dropDownCartStatus === false) {
// Close Mobile toggle menu case opened
if (toggleNavStatus === true) {
$("#toggle_icon").trigger("click");
}
if ($('html').attr("lang") === "ar") {
// Cart css
$("#cart-img").css({
'transform': 'scaleX(1) rotate(20deg)'
});
$(".cart-items-number-overlay").css({
"right": "-13px",
"top": "-26px"
});
} else {
// Cart css
$("#cart-img").css({
'transform': 'scaleX(-1) rotate(20deg)'
});
$(".cart-items-number-overlay").css({
"right": "20px",
"top": "-26px"
});
}
$(".nav_sidebar .menu2").css({
"visibility": "visible",
"width": "272px"
});
$(".cart-form-overlay").css("opacity", "1");
dropDownCartStatus = true;
} else if (dropDownCartStatus === true) {
if ($('html').attr("lang") === "ar") {
// Cart css
$("#cart-img").css({
'transform': 'scaleX(1) rotate(00deg)'
});
$(".cart-items-number-overlay").css({
"right": "2px",
"top": "-30px"
});
} else {
// Cart css
$("#cart-img").css({
'transform': 'scaleX(-1) rotate(0deg)'
});
$(".cart-items-number-overlay").css({
"right": "3px",
"top": "-30px"
});
}
$(".nav_sidebar .menu2").css({
"visibility": "hidden",
"width": "0"
});
dropDownCartStatus = false;
}
}
});
// ! update add to cart sum
let addToCart = $(".product_page .secondary_btn").text() + " "
sumItems = function () {
sumItem = 0.0;
itemQuantity = $(".product_page .quantity").val();
itemPrice = Number(parseFloat($(".product_page .red-color").text()));
addOnsPrice = 0.0
$($("#id_product_add_on input:checkbox:checked")).each(function () {
addOnsPrice += Number(parseFloat($(this).parent().attr("pricing")));
});
sumItem += itemQuantity * (itemPrice + addOnsPrice)
if (!isNaN(sumItem)) {
$(".product_page .secondary_btn").text(addToCart + sumItem.toFixed(3) + " " + currencyLang)
}
}
$(document).on("click", '.product_page .quantity-div, .container #id_product_add_on input', function () {
sumItems();
});
sumItems();
// ! Sync cart items
// Increment and decrement clicks
$(document).on("click", '.operator', function (event) {
event.preventDefault();
// Operator value to get button clicked
let $operator = $(this).attr('name').split(" ")[0];
// Display Update Button
$(this).parent().parent().parent().find('.cart-btns .update:first').css({
"display": "unset",
"visibility": "visible"
});
// Get Button Clicked
let $getValue;
if ($operator == "add") {
// Get input value
$getValue = parseInt($(this).prev().val());
// Set New input value
$(this).prev().val($getValue + 1);
} else if ($operator == "remove") {
// Get input value
$getValue = parseInt($(this).next().val());
if ($getValue === 1) {
return;
}
// Set New input value
$(this).next().val($getValue - 1);
}
});
$(document).on("click", '.item_form .update-button', function (event) {
event.preventDefault();
// Get button clicked
$clickedBtn = $(this).attr('name').split(" ")[0];
$clickedForm = $(this).parent().parent().parent().attr('class').split(' ')[1];
$clickedFormTag = $(this);
// Starts animation
$(this).empty().append("");
$(this).parent().parent().find(".operator").val($clickedBtn);
// Get Form and its data
$submittedForm = $(this).parent().parent().parent();
$getFormData = $submittedForm.serializeArray();
updateCart = true;
if ($(this).parent().hasClass("cart_items")) {
cartLoad = true;
}
// Run Form Submission Function
itemFormSubmission($getFormData);
});
$(document).on("click", '.as_ref', function (event) {
event.preventDefault();
window.location.href = $(this).closest(".product-img").attr("href");
});
$(document).on("submit", '.item_form', function (event) {
// Starts form submission and continue in other function
event.preventDefault();
itemFormSubmission($(this).serializeArray());
});
let loadVariablesOnce = false;
itemFormSubmission = function ($getData) {
$(".error").remove();
$("input, select, .code-color").removeClass("red-border");
if (loadVariablesOnce === false) {
addProduct = "";
if ($('html').attr("lang") === "ar") {
updateText = "تحديث";
buyNow = "شراء سريع";
} else if ($('html').attr("lang") === "en") {
updateText = "Update";
buyNow = "Buy Now";
}
}
if (updateCart === true) {
cartURL = path + "update_cart/";
} else {
cartURL = path + "cart/"
}
$.ajax({
method: "POST",
url: cartURL,
data: $getData,
dataType: 'json',
success: function (data) {
updateCart = false;
if (data.success) {
if (cartLoad === true) {
$(".cart-items").load(path + "cart-items/", function () {
if ($('.cart-items').children().length < 1) {
window.location.reload();
}
});
} else {
$(".cart-form-overlay").load(path + "cart-overlay/", function () {
// Change cart quantity number
syncPriceQuantity();
});
}
cartLoad = false;
// Display cart
if (dropDownCartStatus === false) {
$("#cart-img").trigger("click");
}
// Show success animation for Update/Remove buttons
$($submittedForm).find(".update").empty().append("").css({
"min-width": "110px",
"background": "var(--success-color)"
}).delay(800).queue(
function () {
// Return to previous css state
$(this).css({
"background": "rgb(42 162 117)",
"visibility": "hidden",
"display": "none",
}).text(updateText)
$(".operator").attr("disabled", false);
$(this).dequeue();
});
if (quickBuy === true) {
window.location.href = path + 'checkout/';
}
} else {
let json;
let headerHeight = $("header").height();
$.each(data, function (key, item) {
json = $.parseJSON(item);
if (!json.hasOwnProperty('__all__') && !json.hasOwnProperty('sku')) {
// Add-ons input error
$($clickedFormTag).after(
"* " + json[Object.keys(json)[0]][0].message +
"");
$($clickedFormTag).parent().find('[name=' + Object.keys(json)[0] + ']').addClass("red-border");
}
});
if ($($clickedFormTag).parent().hasClass("item_form") && !$($clickedFormTag).parent().hasClass("quick-add")) {
$([document.documentElement, document.body]).animate({
scrollTop: $(".container").offset().top - (headerHeight)
}, 1000);
}
// Form error
if (json.hasOwnProperty('__all__')) {
$($clickedFormTag).after(
"* " + json
.__all__[0]
.message +
"");
}
// Product color or size error
if (json.hasOwnProperty('sku')) {
$($clickedFormTag).after(
"* " + json
.sku[0]
.message +
"");
// Red borders for empty selections
if ($($clickedFormTag).parent().find(".variant_size").val() === null) {
$($clickedFormTag).parent().find(".variant_size").addClass("red-border");
}
if ($($clickedFormTag).parent().find("#variant-color").val() === "") {
$($clickedFormTag).parent().find(".code-color").addClass("red-border");
}
}
// Show success animation for Update/Remove button
$($submittedForm).find(".update").empty().append("").css({
"min-width": "110px",
"background": "var(--error-color)"
}).delay(800).queue(
function () {
// Return to previous css state
$(this).css({
"background": "rgb(42 162 117)",
"visibility": "hidden",
"display": "none",
}).text(updateText);
$(".operator").attr("disabled", false);
$(this).dequeue();
});
quickBuy = false;
}
$(".add-to-cart i").removeClass('fa-spinner fa-spin').addClass('fa-cart-plus');
$(".add-product").prop("disabled", false).html(addProduct);
$("#buy_now").text(buyNow);
sumItems();
}
});
};
// ! Scroll effect
// Upon Scroll key
$(window).scroll(function () {
let st = $(this).scrollTop();
// Scroll down
if (st > 0) {
// Header
$('header').css({
"background-color": "#fff"
});
}
// If at very top
if (st === 0) {
// Header
$('header').css({
"background-color": "#fff"
});
}
});
// ! Check active anchor
checkActiveMenu();
// ! Toggle Menu function / Mobile
$(document).on("click", '#toggle_icon', function () {
if (toggleNavStatus === false) {
// Close Cart if opened
if (dropDownCartStatus === true) {
$("#cart-img").trigger("click");
}
// Menu css
$(".nav_sidebar .menu").css({
"visibility": "visible",
"width": "272px"
});
$("#toggle_icon").css({
"transform": "rotate(360deg)",
"color": "var(--error-color)"
}).removeClass("fa-bars").addClass("fa-times");
$('.divider-long').css({
"opacity": "1"
});
toggleNavStatus = true;
} else if (toggleNavStatus === true) {
$('.divider-long').css({
"opacity": "0"
});
$("#toggle_icon").css({
"transform": "rotate(0deg)",
"color": "#373737"
}).removeClass("fa-times").addClass("fa-bars");
$(".nav_sidebar .menu").css({
"visibility": "hidden",
"width": "0"
});
toggleNavStatus = false;
}
})
// ! Drop Down Menu function / Desktop
$(document).on("click", '.account_desktop>a', function () {
// Show or Hide side bar
ulDropDown(this, true);
});
$(document).on("click", '.discount_btn', function () {
$(".inside-input").remove();
$(".id_code").css("border-color", "");
$.ajax({
method: "POST",
url: path + "discount_view/",
data: {
code: $(this).parent().find(".id_code").val(),
csrfmiddlewaretoken: $('meta[name=csrfmiddlewaretoken]').attr("content")
},
dataType: 'json',
success: function (data) {
if (data.success) {
window.location.replace(path + "cart/");
} else {
$.each(data, function (key, item) {
json = $.parseJSON(item);
});
if (json.hasOwnProperty('__all__')) {
$(".as_flex").prepend(
"");
}
$(".id_code").css("border-color", "red").val("");
}
}
});
});
let checkResize = function () {
if (getDimensions != window.innerWidth) {
getDimensions = window.innerWidth;
if (window.innerWidth >= 1051) {
$(".nav_menu").appendTo(".lower");
$(".product--blue").css({
"flex": ""
});
$(".view-controls .fa-th").removeClass("active-view-control");
$(".view-controls .fa-square").addClass("active-view-control");
$(".lang").prependTo(".upper");
$(".currencies").insertAfter(".upper .lang");
} else {
$(".nav_menu").appendTo(".sub-menu");
$(".fa-th").trigger("click");
$(".lang").appendTo(".sub-menu");
$(".currencies").appendTo(".sub-menu");
}
}
}
checkResize();
$(window).resize(function () {
checkResize();
});
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
if (scroll > 600) {
$(".go-up").css("opacity", 1);
} else {
$(".go-up").css("opacity", 0);
}
});
$(document).on("click", '.go-up', function () {
$('html,body').animate({
scrollTop: 0
}, 'slow');
});
// ! Subscribe form
$(document).on("submit", '#subscribe_form', function (event) {
event.preventDefault();
$("#subscribe_button").html("");
$(".error").remove();
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
if (data.success) {
$("#subscribe_form input").remove()
$("#subscribe_button").html("").css({
"background": "green",
"color": "#fff",
"font-size": "26px"
}).prop("disabled", true);
}
if (data.message) {
$.each(data, function (key, item) {
json = $.parseJSON(item);
// Add-ons input error
$("#subscribe_form label").after(
"* " + json[Object.keys(json)[0]][0].message +
"");
$("#subscribe_form label").parent().find('[name=' + Object.keys(json)[0] + ']').addClass("red-border");
});
$("#subscribe_button").html("");
}
}
});
});
$(document).on("click", '.popup i', function () {
$(this).parent().remove();
});
$(document).on("click", '.cookie-consent button', function () {
$(this).parent().remove();
Cookies.set('consent', '1', {
expires: 14
})
});
// ! Popup slide
var slideIndex = 0;
popupSlides();
function popupSlides() {
var i;
var slides = document.getElementsByClassName("mypopups");
var dots = document.getElementsByClassName("popup-dot");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {
slideIndex = 1
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
if (slides[slideIndex - 1] !== undefined) {
slides[slideIndex - 1].style.display = "block";
}
if (dots[slideIndex - 1] !== undefined) {
dots[slideIndex - 1].className += " active-popup";
}
setTimeout(popupSlides, 5000);
}
});
// Service worker
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/sw.js');
});
}