$( document ).ready(function() {

    function sendAction(action) {

        let randValue = Math.floor(Math.random() * 1001)

        fetch("/action?type=" + action + "&hash=" + randValue)
            .then((response) => {
                return response.json();
            })
            .then((data) => {
                console.log(data);
                //alert(data);
            });


    }

    $(document).click(function(e) {
        // Check for left button
        if (e.button == 0) {
            //alert("scrollDown");
            sendAction("click");
        }
    });

    $("a[href^=\"tel\"]").on("click",function(){
        sendAction("call");
    });
    $("a[href^=\"callto\"]").on("click",function(){
        sendAction("call");
    });


    var position = $(window).scrollTop();
    var isScrolling = false;

    // should start at 0

    $(window).scroll(function() {

        var scroll = $(window).scrollTop();
        if(scroll > position) {
            console.log("scrollDown");
            //alert("scrollDown");
            actionScroll();
        } else {
            console.log("scrollUp");
            //alert("scrollDown");
            actionScroll();
        }
        position = scroll;
    });


    function actionScroll() {
        if (isScrolling == true) {
            return false;
        } else {
            isScrolling = true;
            setTimeout(function() {
                sendAction("scroll");
                isScrolling = false;
            }, 1000);
        }
    }


});
