$(function() {

    var userVisited = userVisitedInLast30Days();

    /** change Zendesk color widget */
    window.zESettings = {
        webWidget: {
            color: { theme: '#6B3788' }
        }
    };

    /** add webpusher */
    window.WonderPush = window.WonderPush || [];
        WonderPush.push(["init", {
        webKey: "de4a3b78000b2c6ff0c06a8729c4b00278b9bbf2c639592c0ffc5f93c8609949",
    }]);

    /** sticky banner popup */
    var stickyBannerLocal = getLocalItemWithExpiry('stickyBanner');

    var stickyBanner = $('#sticky-banner');

    if(!stickyBannerLocal){
        if(stickyBanner.length){
            stickyBanner.show();
        }
    }

    $('#sticky-banner .close-btn').click(function() {
        stickyBanner.hide();
        setLocalStorageWithExpiry('stickyBanner', true, 1440);
    });

    /** "see more" categories on mobile */
    $('#show-category-desktop').on('click', function(){
         $(this).hide();
         $('.hide-category-mobile').toggle('medium');
    });

    /** show tooltip to new users that we have products */
    if(!userVisited) {
        // todo: do something if user visited the site
    }

    // countdown
    $('#countdown').flipper('init');
});

/**
 * Check if user is first time on website
 *
 * @return {boolean}
 */
function userVisitedInLast30Days() {

    if( ! getLocalItemWithExpiry('first-time')){
        setLocalStorageWithExpiry('first-time', true, 43200);
        return false;
    }

    return true;
}

/**
 * Set local storage item with expiring date
 * IE does not support default value in parameters
 *
 * @param key
 * @param value
 * @param minutes
 */
function setLocalStorageWithExpiry(key, value, minutes) {

    const now = new Date();

    const item = {
        value: value,
        expiry: now.getTime() + (minutes * 60000)
    }

    localStorage.setItem(key, JSON.stringify(item));
}

/**
 * Get local storage item
 * @param key
 * @return {null|*}
 */
function getLocalItemWithExpiry(key) {

    var itemString = localStorage.getItem(key);

    // if the item doesn't exist, return null
    if (!itemString) {
        return null;
    }

    var item = JSON.parse(itemString);

    var now = new Date();

    // compare the expiry time of the item with the current time
    if (now.getTime() > item.expiry) {
        // If the item is expired, delete the item from storage
        // and return null
        localStorage.removeItem(key);
        return null;
    }

    return item.value;
}

/**
 * Every request increase page load, we are using this in parts like showing
 * user NL modal after X loads
 */
function getCountOfUserPageLoads() {

    var countPageView = 1;

    var currentPageView = getLocalItemWithExpiry('kupime-pageview');

    countPageView = currentPageView ? parseInt(currentPageView) + countPageView : countPageView;

    setLocalStorageWithExpiry('kupime-pageview', countPageView, 1440);

    return countPageView;
}

/**
 * Add product to favorites/wishlist
 *
 * @param type
 * @param productId
 */
function addProductToFavorites(type, productId){

    $('#add-to-favorites').click(function (e) {

        e.preventDefault();

        $.ajax({
            type: 'POST',
            url: urls.api + 'products/add-to-favorites',
            data: {
                _token : $('meta[name=csrf-token]').attr('content'),
                type: type,
                product_id: productId
            },
            success: function (response) {

                if(response.success) {

                    var wishlistValue = $('.wishlist-icon span');
                    var currentValue = parseInt(wishlistValue.first().text());

                    if(response.added) {

                        var dataLayer = window.dataLayer || [];

                        // FB event - AddToWishlist
                        dataLayer.push({
                            "event": "AddToWishlist",
                            "facebook": {
                                "future_era": {
                                    "content_ids": [productId + '-' + type],
                                    "currency": response.currency,
                                    "value": response.price
                                }
                            }
                        });

                        $('#add-to-favorites i').removeClass('fa-heart-o').addClass('fa-heart');

                        // update wishlist count value
                        wishlistValue.text(currentValue + 1);
                    } else {

                        $('#add-to-favorites i').removeClass('fa-heart').addClass('fa-heart-o');

                        // update wishlist count value
                        wishlistValue.text(currentValue - 1);
                    }

                } else {
                    if(response.redirect) {
                        window.location.href = response.url;
                    }
                }
            }
        });
    });
}

function storeCustomerEmailForExpiredAd(url, csrfToken, adId){
    $('#notify-me').click(function (e) {

        e.preventDefault();

        var email = $('#notify-me-email').val();

        if(email.length < 6 || email.indexOf("@") === -1) {
            $('#notify-me-message').empty().removeClass('alert-success').addClass('alert-danger').css('display', 'block').text('Došlo je do greške. Provjeri unesenu email adresu.');
        } else {
            $.ajax({
                type: 'POST',
                url: url,
                data: {
                    _token : csrfToken,
                    id: adId,
                    email: email
                },
                success: function (response) {
                    $('#notify-me-message').empty().removeClass('alert-danger').addClass('alert-success').css('display', 'block').text(response.message);
                    $('#notify-me-email').val('');
                },
                error: function () {
                    $('#notify-me-message').empty().removeClass('alert-success').addClass('alert-danger').css('display', 'block').text('Došlo je do greške. Osvježi stranicu i probaj ponovno.');
                }
            });
        }
    });
}
