$(function() {
    window._trackerB = new TrackerB();
    _trackerB.debug = false;
    _trackerB.useAsyncMethod = false;

    var scrollEnd = new ScrollEndTracker(_trackerB, 'td.foot');
    scrollEnd.eventCategory = 'page_viewing';
    scrollEnd.trackScrollEnd = false;
    scrollEnd.addTimer(30000, 'scroll_end_30');
    scrollEnd.addTimer(60000, 'scroll_end_60');

    var pageView = new PageViewTracker(_trackerB);

    pageView.check('/contact.html', 'contact_view');
    pageView.check('/price.html', 'price_view');

    var referrers = [
        'http://www.ur-c.ru/',
        'http://www.ur-c.ru/uslugi.html',
        'http://www.ur-c.ru/registracia_firm.html',
        'http://www.ur-c.ru/sud_process.html',
        'http://www.ur-c.ru/sud_process_corp.html',
        'http://www.ur-c.ru/famil_spor.html',
        'http://www.ur-c.ru/likvidacia.html'];

    // Переход из страницы "проводника"
    if ($.inArray(document.referrer.toLowerCase(), referrers) >= 0) {
        _trackerB.trackEvent('site_using', 'click_link', window.location.href, 1);
    }
   
    $("#speczn form").submit(function(e) {
        _trackerB.trackEvent('site_using', 'send_order', window.location.href, 1);
    });

    var uid = $.cookie('trackerB_uid');

    if (uid == null) {
        var utma = $.cookie('__utma');
        if (utma != null) {
            var parts = utma.split('.');
            if (parts.length > 0) {
                uid = parseInt(parts[1]).toString(16).toUpperCase();
                uid = uid.replace(/F/g, '0');
                uid = uid.replace(/(E|D)/g, '1');
                uid = uid.replace(/(C|B)/g, '2');
                uid = uid.replace(/A/g, '3');
                uid = uid.replace(/(\d{3})/g, '$1-');
            }
        }

        _trackerB.setCustomVar(1, 'client_id', uid, 2);
        //_trackerB.trackEvent('client_traking', 'call_traking', uid, 1);

        $.cookie('trackerB_uid', uid, { 'path': '/' });
    }

    $('td.foot').append('<div style="float:left; margin:0px 0px 0; color:#eeeeec;">Ваш код: <b>'+uid+'</b></div>');
    //$('td.foot').children('a').before('<span>' + uid + ' </span>');
});

function ScrollEndTracker(tracker, selector) {
    var _selector = selector,
        _selectorOnScreen = false,
        _tracker = tracker,
        _this = this,
        _timers = [];

    this.eventCategory = 'site_using';
    this.pageUrl = window.location.href;
    this.trackScrollEndAverage = true;
    this.trackScrollEnd = true;

    this.close = function() {
        $(window).unbind('resize', onRefresh);
        $(window).unbind('scroll', onRefresh);
        $(window).unbind('unload', onUnload);

        _this.clearTimers();
    }
    this.addTimer = function(interval, eventName) {
        _timers.push(
            setTimeout(function() {
                if (_selectorOnScreen) {
                    _tracker.trackEvent(_this.eventCategory, eventName, _this.pageUrl, 1);
                    _this.clearTimers();
                }
            }, interval));
    }
    this.clearTimers = function() {
        for (var i = 0; i < _timers.length; i++) {
            if (_timers[i] != null) {
                clearTimeout(_timers[i]);
            }
        }
    }

    // initalize
    $(window).resize(onRefresh).scroll(onRefresh).unload(onUnload);

    function onRefresh(e) {
        var obj = $(_selector);
        if (obj.size() > 0 && obj.isOnScreen()) {
            _selectorOnScreen = true;
            $(window).unbind(e);

            if (_this.trackScrollEnd) {
                _tracker.trackEvent(_this.eventCategory, 'scroll_end', _this.pageUrl, 1);
            }
        }
    }
    function onUnload(e) {
        if (_selectorOnScreen && _this.trackScrollEndAverage) {
            _tracker.trackEvent(_this.eventCategory, 'scroll_end_average', _this.pageUrl, _tracker.getTimeDelta());
        }
    }
}
function PageViewTracker(tracker) {
    var _this = this,
        _tracker = tracker,
        _pageUrl = window.location.href;

    this.eventCategory = 'page_viewing';

    this.check = function(pattern, eventName, eventValue) {
        var re = new RegExp(pattern, "i");
        if (re.test(_pageUrl)) {
            eventValue = eventValue == null ? document.referrer : eventValue;
            _tracker.trackEvent(_this.eventCategory, eventName, eventValue, 1);

            return true;
        }
        return false;
    }
}
function TrackerB() {
    // public fields
    this.debug = false;
    this.useAsyncMethod = false;
    // private fields
    var _this = this,
        _startTime = (new Date()).getTime();

    if (window._gaq != null && window._gaq.push != null) {
        _this.useAsyncMethod = true;
    }

    // methods
    this.trackEvent = function(category, action, label, value) {
        var result = _this.useAsyncMethod
            ? window._gaq.push(['_trackEvent', category, action, label, value])
            : window.pageTracker._trackEvent(category, action, label, value);

        _log('_trackEvent('+category+', '+action+', '+label+', '+value+') is completed with result: '+result);
    }
    this.setCustomVar = function(index, name, value, scope) {
        if (scope == null) {
            scope = 3;
        }
        var result = false;
        if (_this.useAsyncMethod) {
            result = window._gaq.push(['_setCustomVar', index, name, value, scope]);
            window._gaq.push(['_trackPageview']);
        }
        else {
            result = window.pageTracker._setCustomVar(index, name, value, scope);
            window.pageTracker._trackPageview();
        }

        _log('_setCustomVar('+index+', '+name+', '+value+', '+scope+') is completed with result: '+result);
    }
    this.getTimeDelta = function() {
        return ((new Date()).getTime() - _startTime) / 1000;
    }

    function _log(message) {
        if (!_this.debug) {
            return;
        }
        if (console != null && console.log != null) {
            console.log(message);
        }
    }
}
