var isloading = false;

/*LOADING FUNCTION*/
/*
 * 
 * graphic detail
 * loading image
 * 
 * @param {type} value
 * @returns {isloading|Boolean|value}
 */
function loading(value) {
    if (typeof (value) == "undefined")
        return isloading;
    isloading = value;
    if (isloading)
        $('body').addClass('loading');
    else
        $('body').removeClass('loading');
}

function addQueryStringToUrl(url) {
    if (!url)
        url = current_url;

    if (novalue(query_string))
        return url;
    return url + '?' + query_string;
}

function showErrorMessage(message) {

    var now = new Date();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    var milsec = now.getMilliseconds()

    var id = hour + '-' + minute + '-' + second + '' + milsec;

    var messageHTML = '<div class="alert alert-danger" id="' + id + '">' + message + '</div>';

    $('.msgHolder').html(messageHTML);

    setTimeout(function () {
        $('#' + id).remove();
    }, 3000);
}

function showSuccessMessage(message) {

    var now = new Date();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    var milsec = now.getMilliseconds()

    var id = hour + '-' + minute + '-' + second + '' + milsec;

    var messageHTML = '<div class="alert alert-success" id="' + id + '">' + message + '</div>';

    $('.msgHolder').html(messageHTML);

    setTimeout(function () {
        $('#' + id).remove();
    }, 3000);
}


function minimizeStoreMessage() {

    var messageElem = $('#store-messages .message');

    var store_message = messageElem.html();
    if (store_message) {
        store_message = store_message.trim();

        var words = store_message.split(" ");

//    console.log(words.length);

        if (words.length > 25) {

            messageElem.html('');

            var short_mess = '';
            for (var i = 0; i < 25; i++) {
                short_mess = short_mess + words[i] + ' ';
//            console.log(words[i]);
            }
            short_mess += '...';
            messageElem.fadeIn(2000).html(short_mess);

            $('.message-open-btn').show();
            $('.message-close-btn').hide();

        }

        $('#store-message-text-buffer').html(store_message);
    }


}

function maximizeStoreMessage() {

    var messageElem = $('#store-messages .message');
    var store_message = $('#store-messages #store-message-text-buffer').html();

    messageElem.html(store_message);

    $('.message-close-btn').show();
    $('.message-open-btn').hide();

}

// Features controlls.
$(document).ready(function () {

    // Set up product page min height.
    if ($('.page-products .products-list').length) {

        var screen_height = screen.height;
        var headerH = $('.ui-header').length > 0 ? $('.ui-header').height() : 0;
        var min_height = screen_height - headerH;

        $('.page-products .products-list').css('min-height', min_height);

    }

    // define showInlineBlock helper function.
    $.fn.showInlineBlock = function () {
        return this.css('display', 'inline-block');
    };
// -----------HAMBURGER BTN -------------------------------------------------
    $('#menu').click(function () {

        var navpanel = $('#navpanel');

        if (navpanel.hasClass('open')) {
            $(this).removeClass('open');
            navpanel.removeClass('open');

        } else {
            navpanel.addClass('open');
            $(this).addClass('open');
        }
    });

// -------SHOW PRODUCT MODAL CONTROLL-------------------------------------------
    $(document).on('click', '.show-product-modal-btn', function () {

        var product_simple_id = $(this).attr('data-product-id');

        showProductDetailModal(product_simple_id, 1);

    });
// -------ADD PRODUCT TO CART --------------------------------------------------
    $(document).on('click', '.pd-add-to-cart-btn', function () {
        add_to_cart(function (response) {

            $('#nrOfProdInCart').html(response.nrOfProdInCart);

        });
    });
    // Minimize store message.
    if ($('body').hasClass('page-categories')) {
        minimizeStoreMessage();
    }

    $('.message-open-btn').click(function () {
        maximizeStoreMessage();
    });

    $('.message-close-btn').click(function () {
        minimizeStoreMessage();
    });

    $(".product-info-holder").click(function () {

        var ps_list = $(this).parent().find('.product-simple-list');
        var accordion_arrow = $(this).find('.product-accordion');

        ps_list.slideToggle(300, function () {
            if (ps_list.hasClass('closed')) {

                ps_list.removeClass('closed');
                ps_list.addClass('open');

                accordion_arrow.removeClass('closed');
                accordion_arrow.addClass('open');

            } else {

                ps_list.removeClass('open');
                ps_list.addClass('closed');

                accordion_arrow.removeClass('open');
                accordion_arrow.addClass('closed');
            }
        });
    });

    $(".menu-activ-lang").click(function () {
        $(".menu-langauge-list").toggle();
    });


    // HOME PAGE / STORE PAGE SEARCH BTN CONTROLL.
    $(document).on('click', '.search-icon.search-btn', function () {

        var header = $('.ui-header');
//
        if (header.hasClass('search-open')) {
            return false;
        }

        header.addClass('search-open');

        $('.menu-btn').hide();
        $('.nav-back-btn').hide();
        $('.ui-title').hide();
        $('.location-holder').hide();
        $('.search-back-btn').showInlineBlock();
        $('.search-icon.search-btn').hide();
        $('.search-holder').show();
        $('.location-wrapper').hide();
        $('.store-type-lable-holder').hide();
        $('.account-ic-holder').hide();

    });

    $(document).on('click', '.search-back-btn', function () {

        var header = $('.ui-header');

        header.removeClass('search-open');

        $('.menu-btn').show();
        $('.nav-back-btn').showInlineBlock();
        $('.ui-title').showInlineBlock();
        $('.location-holder').show();
        $('.search-back-btn').hide();
        $('.search-icon.search-btn').show();
        $('.search-holder').hide();
        $('.store-type-lable-holder').show();
        $('.account-ic-holder').show();

    });


//    $(".location-holder").click(function () {
//
//        var flagElem = $(this).find('.location-selector-status');
//
//        if (flagElem.hasClass('opened')) {
//            flagElem.removeClass('opened');
//        } else {
//            flagElem.addClass('opened');
//        }
//        // Toggle location selector.
//        $(".location-wrapper").toggle();
//    });

    $(".location-holder").click(function () {

        $(".location-wrapper").trigger('open');



//        var flagElem = $(this).find('.location-selector-status');
//
//        if (flagElem.hasClass('opened')) {
//            flagElem.removeClass('opened');
//        } else {
//            flagElem.addClass('opened');
//        }
        // Toggle location selector.
    });

    $('.location-wrapper').on('open', function () {

        var element = $(this);
        // Set up status flag.
        $('.location-selector-status').addClass('opened');

        if (!element.is(':visible')) {

            $(this).fadeIn();
            setTimeout(function () {

                $(document.body).bind("click.closeLocationSelector", function () {

                    element.trigger('close');
                });

            }, 100);
        }

    });

    $('.location-wrapper').on('close', function () {

        $(document.body).unbind("click.closeLocationSelector");

        $(this).fadeOut();

        $('.location-selector-status').removeClass('opened');
    });



    // ---------SEARCH CONTROLLS--------------------------------------------

    $('.search-mobile-suggest-holder').bind('open', function () {
        $(this).show();
    });
    $('.search-mobile-suggest-holder').bind('close', function () {
        $(this).hide();
    });

    $('.fullSearchMobileInput').on('keyup input', function () {

        var searchInput = $(this);
        var search_key = $(this).val();

        var store_id_param = !isNaN(searchInput.attr('store_id')) ? '&store_id=' + searchInput.attr('store_id') : '';

        var url = base_url + 'searchapi/v1/api/web_mobile_suggest?search_key=' + search_key + store_id_param;

        // hide suggest if it is empty.
        if (search_key == '') {
            $('.search-mobile-suggest-holder').trigger('close');
        }

        console.log(search_key);
        // maek search.
        if (search_key.length > 2) {
            $.ajax({
                type: 'GET',
                url: url,
            }).done(function (result) {
                $('.search-mobile-suggest-holder').trigger('open');
                $('.search-mobile-suggest-holder').html(result);
            });
        }

    });


//    $('.fullSearch .fullSearchMobileInput, #restaurants .fullSearchMobileInput').keyup(function (event) {

    // pass ENTER.
//        if (event.which == 13) {
//            alert('passed ENTER');
//            var search_type = $('#search_type').val();
//            search_type = search_type == 'product' || search_type == 'store' ? search_type : 'product';
//
//            var search_key = $(this).val();
//            var search_url = base_url + 'search/' + search_type + '?search_key=' + search_key;
//
//            window.location.href = search_url;

//        }
//    });

//---------------SELECT CUSTOMER ADDRESS--------------------------------------------------------------

    $(document).on('click', '.location-address', function (event) {

        loading(true);
        // add/remove proper classes.
        $('.location-address').removeClass('selected_address');
        $(this).addClass('selected_address');

        var address_id = $(this).attr('address_id')
        var selected_address_text = $(this).find('span').html();
        // repopulate selected address.
        $('.location-selected').html(selected_address_text);
        // hide list of address
        $(".location-wrapper").toggle();

        $.ajax({
            type: 'POST',
            url: addQueryStringToUrl(base_url + 'restaurants/set_address'),
            data: {address_id: address_id},
            dataType: 'json'
        }).done(function (result) {

            loading(false);

            location.reload();

        });

    });
//---------------CHANGE STORE TYPE----------------------------------------------------

    $(document).on('click', '.store-type-lable-holder', function (event) {
        $('.store-type-holder').trigger('open');
    });

    $('.store-type-holder').on('open', function () {
        var element = $(this);
        // Set up status flag.
        $('.store-type-selector-arrow').addClass('isOpen');

        if (!element.is(':visible')) {

            $(this).fadeIn();

            $(document.body).bind("click.closeStoreTypeSelector", function () {

                element.trigger('close');
            });
        }
        // console.log($._data($('body').get(0)));

    });

    $('.store-type-holder').on('close', function () {

        $(this).fadeOut();

        $(document.body).unbind("closeStoreTypeSelector");

        $('.store-type-selector-arrow').removeClass('isOpen');

    });

    $(document).on('click', '.store-type-item', function (event) {

        var store_type = $(this).attr('store_type');

        loading(true);

        $.ajax({
            type: 'POST',
            url: addQueryStringToUrl(base_url + 'restaurants/set_store_type'),
            data: {store_type: store_type},
            dataType: 'json'
        }).done(function (result) {

            loading(false);

            location.reload();

        });

    });

//---------------CHANGE CITY----------------------------------------------------
    $(document).on('click', '.location-city', function (event) {

        var elem = $(this).find('span');
        var city_id = elem.attr('city_id');
        var link = elem.attr('link');

        loading(true);

        $.ajax({
            type: 'POST',
            url: addQueryStringToUrl(base_url + 'restaurants/set_city'),
            data: {
                city_id: city_id
            }
        }).done(function (result) {

            loading(false);

            window.location.replace(link);

        });

    });
//---------------SELECT CUSTOMER ADDRESS----------------------------------------
    $(document).on('click', '.send-contact-form-btn', function () {
        if (loading()) {
            return false;
        }
        var myForm = $('#contactForm');

        loading(true);
        $.ajax({
            type: 'POST',
            url: base_url + 'customer/send_support_feedback',
            data: myForm.serializeArray(),
            dataType: 'json'
        }).done(function (result) {

            loading(false);

            if (result.success) {
                showSuccessMessage(result.message);

                setTimeout(function () {
                    window.location = $("a.back-btn").attr('href');
                }, 2000);
            } else {
                showErrorMessage(result.message);
            }

        });

        return false;
    });
// Password control.--------------------------------------------------------
// Password field control.
    $('.password-control').each(function () {
        $('<i class="toggle-password"></i>').insertAfter($(this));
        $(this).parent().addClass('password-wrapper')
    });

    $(document).on('click', '.toggle-password', function (event) {

        var input = $(this).parent().find('input');
        var toggle = $(this);

        if (toggle.hasClass('eye-off')) {
            toggle.removeClass('eye-off');
            input.attr('type', 'password');
        } else {
            toggle.addClass('eye-off');
            input.attr('type', 'text');
        }

    });


// Thank you page reorder controll -----------------------------------------
    $(document).on('click', '.ty-reorder-btn', function () {

        var order_id = $(this).attr('order_id');

        $.ajax({
            url: addQueryStringToUrl(base_url + 'customer/reordering/' + order_id),
            type: 'POST',
            dataType: 'json',
            data: {
                order_id: order_id,
            },
        }).done(function (result) {

            window.location.href = result.redirect_url;

        }).fail(function (result) {

            window.location.href = result.redirect_url;

        });

    });
// Reorder handling on empty cart ------------------------------------------
    $(document).on('click', '.reorder-customer-last-order-btn', function () {

        $.ajax({
            url: base_url + 'customer/reorder_last_order',
            type: 'POST',
            dataType: 'json',
            data: {},
        }).done(function (result) {

            if (result.success) {
                window.location.href = result.redirect_url;
            } else {
                window.location.href = base_url;
            }

        }).fail(function (result) {

            window.location.href = base_link;

        });
    });

// --------FACEBOOK LOGIN ON CHECKOUT PAGE----------------------------------

    $(document).on('click', '.facebook-login-btn', function () {
        if (loading()) {
            return false;
        }

        loginUser(
                function () {

                    customerLogin(function () {

                        // Success
                        location.reload();

                    }, function (message) {
                        // Fail.                        
                        showErrorMessage(message);
                    });

                },
                function (message) {

                    showErrorMessage('Logare nereusita!');
                },
                'public_profile,email'
                );
        return false;
    });

// --------GOGOLE LOGIN ----------------------------------
    $('.google-login-btn').click(function () {

        googleLogin();

    });

// --------APPLE LOGIN ----------------------------------
    $('.apple-login-btn').click(function () {

        var landing_page = $(this).attr('landing_page');

        appleLogin(landing_page);
    });

// --------TRUSTED USER ----------------------------------

    $('.customer-is-trusted').hover(
            function () {
                $(this).find('.tooltip').show()
            },
            function () {
                $(this).find('.tooltip').hide()
            }
    );


    function customerLogin(callback, failCallback) {

        var app_type = $('body').attr('app_type');

        var payload = {};

        /*AJAX CALL*/
        $.ajax(
                {
                    type: 'POST',
                    url: addQueryStringToUrl(base_url + 'restaurants/rebuild_query_string_urls'),
                    dataType: 'json',
                    data: payload
                }
        ).done(function (result) {
            loading(false);

            if (result.success) {
                if (callback) {
                    callback();
                }
            } else {
                failCallback(result.message);
            }
        }
        ).fail(function (r) {
            if (failCallback) {
                failCallback();
            }
        });
    }

//check if exists footer element
    if ($("#footer").length) {

        var page_content = $('#footer').parent();
        page_content.addClass('page-content');

        let content = document.querySelector('.ui-content').getBoundingClientRect();
        let footer = document.querySelector('.footer').getBoundingClientRect();
        let fullpage = document.querySelector('.footer').parentNode.getBoundingClientRect();
        var overlap = !(content.right < footer.left ||
                content.left > footer.right ||
                content.bottom < footer.top ||
                content.top > footer.bottom)

        // console.log(overlap)
        // var myHeight = window.innerHeight - page_content.height() ;
        if (overlap) {
            var padding = content.bottom - footer.y
            page_content.css("padding-bottom", padding);
        }
    }

//-------MANIOULATE  CUSTOMER AUTH CONTAINER-------------------------------    

    var ui_content = $('.auth-container').parents('.ui-content');

    if (ui_content.length > 0) {
        var elemHeight = ui_content.height();

        if (elemHeight > 600) {
            var diff = (elemHeight - 600) * -1;
            ui_content.css('bottom', diff)
        }
    }

}
);
