var url = window.location.href ? window.location.href : document.URL,
    plt = /Android|webOS|iPhone|iPad|iPod|Opera Mini/i.test(navigator.userAgent),
    evt = plt ? 'touchmove' : 'scroll',
    actions = [],
    teaser_views = [],
    teaser_clicks = [],
    date = (!Date.now) ? Date.now : new Date().getTime(),
    tmst = Math.floor(date/1000),
    selector = '.featured_article, .abt, .js-tracker',
    timeout = 3000,
    desturl = false,
    timer, triggerTO;

jQuery(document).ready(function($){
// Checkimg image load status
    $(selector).each(function(){
        var block = $(this),
            image = block.find('img');
        if(image[0].complete){
            block.addClass('js-img-loaded');
        }else{
            image.on('load',function(){
                block.addClass('js-img-loaded');
            });
        }

        clearTimeout(triggerTO);

        triggerTO = setTimeout(function(){
            $(document).trigger(evt);
        }, 200);
    });
// Block view
    $(document).on(evt, function(){
        $(selector).each(function(){
            if($(this).hasClass('js-img-loaded') && checkVisible(this)){
                var jt = $(this),
                    id = jt.attr('id').replace(/[^0-9]/g,''),
                    tt = jt.attr('id').replace(/[0-9]/g,'');
                if(!teaser_views[id]){
                    actions.push({'id':id,'view':1,'click':0,'tt':tt});
                    teaser_views[id] = 1;
                    clearTimeout(timer);
                    timer = setTimeout(function(){
                        sendRequest();
                    }, timeout);
                }
            }
        });
    }).trigger(evt);
// Block click
    $(selector).on('click mousedown', function(e){
    // Checking middle mouse button click
        if(e.type=='mousedown' && e.which!=2) return;
    // Proceeding to action
        var jt = $(this),
            id = jt.attr('id').replace(/[^0-9]/g,''),
            tt = jt.attr('id').replace(/[0-9]/g,''),
            desturl = jt.is('a') ? jt.attr('href') : jt.find('a').attr('href');
    // Tracking click
        if(!teaser_clicks[id]){
            actions.push({'id':id,'view':0,'click':1,'tt':tt});
            teaser_clicks[id] = 1;
            clearTimeout(timer);
            sendRequest(desturl);
        // Scrolling to feed
            $('html,body').animate({scrollTop:$('#feed').offset().top},500);
        }
    });
// Tracking link click for stats
    $('#content noindex a').on('click mousedown', function(e){
    // Checking mouse buttons click
        if(e.type=='mousedown' && e.which!=2) return;
    // Defining vars
        var ahref = $(this).attr('href'),
            url = window.location.href,
            url = url ? url : document.URL,
            proceed = (e.type=='mousedown')? false:true;
        $.post('/stat/trackLinkClick',{url:url});
    });
});

function checkVisible(elm){
    var rect = elm.getBoundingClientRect();
    var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
    return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}

function sendRequest(desturl){
    var request = {'teasers': actions, 'desturl': desturl};
        actions = [];
    $.ajax({
        type: 'POST',
        url: '/stat/tracker',
        dataType: 'text',
        data: {data : JSON.stringify(request)}
    });
}