var irCounter = 1;

var irDoc = document;
var irLoc = irDoc.location;

function irBlocksCount() {
    var blocks = document.getElementsByTagName("IRBLOCK");
    if (blocks == null) return 0;
    return blocks.length;
}

function irNavInfo() {
    var sc = "",ul = "",cs = "",je = 0;
    var n = navigator;
    if (self.screen) {
        sc = screen.width + "*" + screen.height + "*" + (screen.colorDepth ? screen.colorDepth : screen.pixelDepth);
    } else if (self.java) {
        var j = java.awt.Toolkit.getDefaultToolkit();
        var s = j.getScreenSize();
        sc = s.width + "*" + s.height;
    }

    je = n.javaEnabled() ? 1 : 0;

    if (n.language) ul = n.language.toLowerCase();
    else if (n.browserLanguage) ul = n.browserLanguage.toLowerCase();

    if (irDoc.characterSet) cs = irEnc(irDoc.characterSet);
    else if (irDoc.charset) cs = irEnc(irDoc.charset);

    return "&cs=" + cs + "&sc=" + sc + "&ul=" + ul + "&je=" + je + "&fl=" + irFlash();
}

function irFlash() {
    var f = "", n = navigator;
    if (n.plugins && n.plugins.length) {
        for (var ii = 0; ii < n.plugins.length; ii++) {
            if (n.plugins[ii].name.indexOf('Shockwave Flash') != -1) {
                f = n.plugins[ii].description.split('Shockwave Flash ')[1];
                break;
            }
        }
    } else if (window.ActiveXObject) {
        for (var ii = 10; ii >= 2; ii--) {
            try {
                var fl = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + ii + "');");
                if (fl) {
                    f = ii + '.0';
                    break;
                }
            }
            catch(e) {
            }
        }
    }
    return f;
}


function irEnc(s, u) {
    if (typeof(encodeURIComponent) == 'function') {
        if (u) return encodeURI(s);
        else return encodeURIComponent(s);
    } else {
        return escape(s);
    }
}

function irDec(s) {
    if (typeof(decodeURIComponent) == 'function') {
        return decodeURIComponent(s);
    } else {
        return unescape(s);
    }
}

function irVoid() {
    return;
}

/* sid - sessionID
 * NavInf: ul-userLang, cs-charSet, sc-screenRes*colorDepth, je-javaEnabled, fl-flashVersion;
 * bc - blocksCount
 * r,q - request, query
 * t - title
 */
function irVisit() {
    if (irLoc.protocol == "file:") return;
    var cntUrl = irURL + "counter.gif?sid=" + irID +
                 irNavInfo() +
                 "&bc=" + irBlocksCount() +
                 "&r=" + irEnc(irDoc.referrer) +
                 "&q=" + irEnc(irLoc.href) +
                 "&t=" + irEnc(irDoc.title.substring(0, 100)) +
                 "&rnd=" + Math.round(Math.random() * 2147483647);

    var i = new Image(1, 1);
    i.src = cntUrl;
    i.onload = function() {
        irVoid();
    }
}
//-------------- SINLESS EYE LIVES HERE --------------
function SinlessEye(did, quiet) {
    /**
     * JSON Utils
     */
    this.toJson = function(obj) {
        var txt = "";
        var first = true;
        for (var i in obj) {
            if (!first) txt += ",";
            //            txt += "'" + i + "':";
            txt += i + ":";

            var vtype = typeof(obj[i]);
            if (vtype == 'object') {
                txt += this.toJson(obj[i]);
            } else if (vtype == 'number') {
               txt += obj[i];
            } else txt += "'" +  (obj[i]+"").replace(/\'/g, "\\'").replace(/(\r\n|[\r\n])/g, " ")+ "'";
            first = false;
        }
        return "{" + txt + "}";
    };

    this.fromJson = function(str) {
        try {
             return eval(str);
        } catch (e) {
             return null;
        }
    };

   /**
     * Какая-то непонятная херня
     */
    this.enc = function(s) {
        var u = arguments[1];
        return typeof(encodeURIComponent) == 'function' ? u ? encodeURI(s) : encodeURIComponent(s) : escape(s);
    };

    this.dec = function(s) { return typeof(decodeURIComponent) == 'function' ? decodeURIComponent(s) : unescape(s); };



    /**
     * COOKIES Utils
     */
    this.writeCookie = function(name, value, mins) {
        var expires = "";
        if (mins) {
            var date = new Date();
            date.setTime(date.getTime() + (mins * 60000));
            expires = "; expires=" + date.toGMTString();
        }
        document.cookie = name + "=(" + this.toJson(value) + ")" + expires + "; path=" + this.cookiePath;
    };

    this.readCookie = function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split('; ');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            if (c.indexOf(nameEQ) == 0) return this.fromJson(c.substring(nameEQ.length, c.length));
        }
        return null;
    };

    /**
     * pid, i  = package ID
     * sid, s  = source ID
     *      d  = data
     *      e  = event
     * @param event
     * @param data
     */
    this.send = function(event, data) {
        data.quiet = this.quiet == true;

        var scr = document.createElement("script");

        //        var t = this;
        //        // такая лажа, если сервер ничего не отвечает, то эта функа продолжает болттатся. делатьпроверки и не плодить функи, чтоле?
        var pid = Math.floor(Math.random() * 100001);
        //        window['cb' + pid] = function(arg) {
        //            if(!t[event]) {if(console )console.log("'"+event+"' handler undefined"); }else t[event](arg);
        //            window['cb' + pid] = null;
        //            scr.parentNode.removeChild(scr);
        //        };
        // '&i=' + pid + '&p=' + this.cookieParty +
        // todo:  контролировать длину запроса, следить за тем, чтобы она не превышала допустимые пределы
        var tail = '&i=' + pid + '&e=' + event + "&v="+ this.patchLevel + "&d=" + this.enc(this.toJson(data));

        // todo вынести протокол, ведь ssl имеет место быть. возможно следует переходишь в режим и сейчас, но не слать пакеты совсем
        if (this.cookieParty == 3) {
            scr.src = "http://" + this.domainID + "." + this.eyeUrl + tail;
        } else {
            scr.src = "http://" + this.eyeUrl + "s=" + this.domainID + tail;
        }
        document.getElementsByTagName("head")[0].appendChild(scr);
    };

    this.moveDays = function(dm, a, b) {
        a = Math.floor(a / 86400000);
        b = Math.floor(b / 86400000);
        var r = Math.max(a,b) - Math.min(a,b);

           odm = dm; // todo remove

        if(r > 31) dm = 1;
        else dm= ((dm<<r) & 0x7FFFFFFF) | 1;
//        if(console) console.log("daydiff: "+r+" mask was: "+this.toBin(odm)+", now: "+this.toBin(dm));
        return dm;
    }

    this.toBin = function(num) {
        return (num<=0) ? "" : this.toBin(num>>1)+(num&1);
    }

    this.initalize = function () {
        var now = Math.floor(new Date().getTime() / 1000);
        if (this.cookieParty == 1) {
            var dd = this.domainData = this.readCookie(this.domainDataCookie);
            if (null == dd) {
                dd = this.domainData = {
                    firstVisit: now,
                    prevVisit: 0,
                    lastVisit: now,
                    sessions: 0,
                    lastVisit: 0,
                    dayMap: 0
                }
            }

            var sd = this.sessionData = this.readCookie(this.sessionDataCookie);
            if (null == sd) {
                sd = this.sessionData = {
                    sessionStart: now,
                    lastHit: now,
                    prevHit: now,
                    referrer: document.referrer,
                    hits: 0,
                    referrerHits: 0,
                    referrerTime: now
                };
                dd.sessions++;
                dd.dayMap = this.moveDays(dd.dayMap, dd.lastVisit, now);
                dd.prevVisit = dd.lastVisit;
                dd.lastVisit = sd.sessionStart;


                this.writeCookie(this.domainDataCookie, dd, 0x7FFFFFFF - (now/60));
                this.send("session", this.agentInfo(dd));
            }
            sd.hits++;
            sd.prevHit = sd.lastHit;
            sd.lastHit = now;

            if(document.referrer.host !== document.location.host) {
                sd.referrer = document.referrer;
                sd.referrerHits = 0;
                sd.referrerTime = now;
            } 
            sd.referrerHits ++;

            this.writeCookie(this.sessionDataCookie, sd, this.sessionTime);
        }

        this.initalized = true;
    };

    /**
     * Data gathering
     */
    this.flashInfo = function() {
        var f = "", n = navigator, ii;
        if (n.plugins && n.plugins.length) {
            for (ii = 0; ii < n.plugins.length; ii++) {
                if (n.plugins[ii].name.indexOf('Shockwave Flash') != -1) {
                    return n.plugins[ii].description.split('Shockwave Flash ')[1];
                }
            }
        } else if (window.ActiveXObject) {
            for (ii = 10; ii >= 2; ii--) {
                try {
                    var fl = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + ii + "');");
                    if (fl) return ii + '.0';
                } catch(e) {}
            }
        }
        return "";
    };

    this.agentInfo = function(info) {
        var n = navigator;
        if (self.screen) {
            info.screen = screen.width + "," + screen.height + ",";
            info.depth = (screen.colorDepth ? screen.colorDepth : screen.pixelDepth);
            //            info.screen = (screen.width << 18) | (screen.height << 2) | (screen.colorDepth ? screen.colorDepth : screen.pixelDepth) / 8;
        }

        info.java = n.javaEnabled() ? 1 : 0;

        //        if (n.language) info.ul = n.language.toLowerCase();
        //        else if (n.browserLanguage) info.ul = n.browserLanguage.toLowerCase();
        //
        //        if (document.characterSet) info.cs = this.enc(document.characterSet);
        //        else if (document.charset) info.cs = this.enc(document.charset);
        info.flash = this.flashInfo();
        return info;
    };

    this.hitInfo = function (info) {
//        info.query = document.location.href;
//        info.referrer = document.referrer.href -- я не знаю будет ли оно тут, пока мы не делаем карт, оно не особо нужно, а траф экономит
        info.title = document.title.substring(0, 100);
        return info;
    };


    this.track = function(event, data) {
        if (!this.initalized) this.initalize();
        this.send(event, data);
    };


    this.trackHit = function() {
        if (!this.initalized) this.initalize();
        if (this.cookieParty == 3)
            this.track("raw", this.agentInfo(this.hitInfo({})));
        else
            this.track("hit", this.hitInfo(this.sessionData));
        var me = this;
        setTimeout(function() { me.track("news", me.hitInfo(me.sessionData)); }, 10000);
    };

    this.quiet = quiet;
    this.patchLevel = '20110829-1228';
    this.domainID = did;
    this.domainData = null;
    this.domainDataCookie = "irD";
    this.sessionData = null;
    this.sessionDataCookie = "irS";
    this.sessionTime = 15;
    this.baseUrl = 'stat.inforotor.ru/';
    this.eyeUrl = this.baseUrl + 'eye.js?';
    this.cookieParty = 1;
    this.cookiePath = "/";
    this.sessionID = false;
    this.initalized = false;
}

