var _teststudio = new Object();
_teststudio.init = function() {
    this._init_done = 0;
    this._init_cb = 0;
    this._debug = 0;
    this.height = 800; //default
    this.count = 0;
    this.timer = undefined;
    this.timer2 = undefined;
    this.src = "http://lite.test-studio.ru/";
    this.cookie_name = "ts_teststudio";
    this.cookie_expires = 1000;
    this.callback = 0;
    this.jsonp_delay = 4000;
    this.jsonp_delay2 = 7000;
    this.cookie_delay = 100;
    this.cookie_delay2 = 200;
    this.cookie_delay3 = 800;
    
    if (document.addEventListener) {
        document.addEventListener("DOMContentLoaded", function(){
            _teststudio._init();
        }, false);
        window.addEventListener("load", function() {
            _teststudio._init();
        }, false);
    }
    if (document.attachEvent) {
        document.attachEvent("onreadystatechange", function(){
            if (document.readyState === "complete") {
                _teststudio._init();
            }
        });
        window.attachEvent("onload", function(){
            _teststudio._init();
        });
    }
}
_teststudio.jsonp = function() {
    if (!this._init_done) return;
    if (this.timer) {
        clearTimeout(this.timer);
        this.timer = undefined;
    }
    if (this.timer2) {
        clearTimeout(this.timer2);
        this.timer2 = undefined;
    }
    if (this.head && this.script && this.script.parentNode) {
        this.head.removeChild(this.script);
        this.script = undefined;
    }
    var s = document.createElement("script");
    s.async = "async";
    s.defer = "defer";
    this.count++;
    var sp = [];
    
    s.src = this.src + "lite_api/cb?c=" + this.count + "&f=" + (this.footer ? "1" : "0") + "&nc=" + Math.random();
    
    this.head.appendChild(s);
    this.script = s;
    this.timer2 = setTimeout("_teststudio.jsonp()", this.jsonp_delay2);
}
_teststudio.cb = function(c, h, f) {
    if (!this._init_done) return false;
    if (c != this.count) return false;
    if (this.timer) {
        clearTimeout(this.timer);
        this.timer = undefined;
    }
    if (this.timer2) {
        clearTimeout(this.timer2);
        this.timer2 = undefined;
    }
    if (this.head && this.script && this.script.parentNode) {
        this.head.removeChild(this.script);
        this.script = undefined;
    }
    if (h && h != this.height) {
        this.height = h;
        this.main.style.height = h + "px";
    }
    if (f && this.footer) {
        this.footer.innerHTML = unescape(f);
    }
    this.timer = setTimeout("_teststudio.jsonp()", this.jsonp_delay);
}
_teststudio.cookie = function() {
    if (!this._init_done) return;
    var c = this._cookie_get();
    if (this.script) return setTimeout("_teststudio.cookie()", this.cookie_delay);
    if (c === "ack" || c === "fin") {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = undefined;
        }
        if (this.timer2) {
            clearTimeout(this.timer2);
            this.timer2 = undefined;
        }
        if (c === "fin") {
            this._cookie_set("ok");
            this.jsonp();
            setTimeout("_teststudio.cookie()", this.cookie_delay3);
        } else {
            this._cookie_set("syn");
            setTimeout("_teststudio.cookie()", this.cookie_delay);
        }
    } else {
        if (!this.timer && !this.timer2) {
            this.timer = setTimeout("_teststudio.jsonp()", this.jsonp_delay);
        }
        setTimeout("_teststudio.cookie()", this.cookie_delay2);
    }
}
_teststudio.cookie_cb = function() {
    if (!this._init_cb) return;
    var c = this._cookie_get();
    if (c === "syn" && !this.callback) {
        this._cookie_set("fin");
        this.callback = 1;
    } else if (c !== "ack" && c !== "fin") {
        this._cookie_set("ack");
    }
    setTimeout("_teststudio.cookie_cb()", (this.callback ? this.cookie_delay3 : this.cookie_delay) );
}
_teststudio.debug = function() {
    var arr = [];
    arr.push({n: "init", s: (this._init_done?1:0)});
    arr.push({n: "iframe", s: (this.iframe?1:0)});
    arr.push({n: "footer", s: (this.footer?1:0)});
    arr.push({n: "cb_exists", s: (this.callback?1:0)});
    var c = this._cookie_get();
    arr.push({n: "cb_worked", s: ((c && c.match(/^(ask|syn|fin|ok)$/))?1:0)});
    var r = "";
    var e = 0;
    for (var i=0; i<arr.length; i++) {
        r += arr[i].n+" ";
        if (arr[i].s) {
            r += "OK\n";
        } else {
            r += "FAILED\n";
            e++;
        }
    }
    if (e == 0) {
        r = "DEBUG: OK";
    } else {
        r = "DEBUG: "+e+" ERRORS\n--\n"+r;
    }
    alert(this._debug);
    alert(r);
}
_teststudio._init = function() {
    if (this._init_done || this._init_cb) return;
    var m = document.getElementById("teststudio_main");
    if (!m) {
        m = document.getElementById("teststudio_callback");
        if (!m) return false;
        this._init_cb = 1;
        this.cookie_cb();
        return true;
    }
    this.head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
    if (!this.head) return;
    this._init_done = 1;
    this.main = m;
    this.footer = document.getElementById("teststudio_footer");

    var txt = m.innerHTML.replace(/\<\s*br\s*\/?\>/gi, " ;");
    txt = txt.replace(/\\\;/g, "__#__");
    txt = txt.match(/[^\012\015\;]+/g); // split to ops
    m.innerHTML = "";
    m.style.display = "block";
    m.style.margin = "0";
    m.style.padding = "0";
    m.style.overflow = "hidden";
    m.style.border = "none";
    var cfg = new Object(); // parse config
    if (txt) {
        for (var i=0; i<txt.length; i++) {
            var s = txt[i].replace(/__\#__/g, ";");
            s = s.replace(/\/\*.*?\*\//g, " "); // remove comment
            s = s.replace(/^\s+/, "");
            s = s.replace(/\s+$/, "");
            if (!s) continue;
            var r = s.match(/^([a-z0-9\_]+)\s*\:\s*(.*)$/);
            if (r) {
                cfg[r[1]] = r[2];
            }
        }
    }
    var ip = [];
    if ( ("param" in cfg) && cfg.param && cfg.param.match(/^[a-z0-9\_\.\-]+$/i) ) {
        var re = new RegExp('[\\?\\&]'+cfg.param+'=(\\d+)', "i");
        var s = document.location.search || "";
        var t = s.match(re);
        if (t && t.length && t[1] && !isNaN(t[1]) && t[1] > 0) {
            cfg.t = t[1];
        }
    }
    var debug = "";
    for (var i in cfg) {
        debug += i+"="+cfg[i]+"\n";
        if (i.match(/^(pid|t|tsid|slid|comments|descr_disable)$/)) { // int or nothing
            if (cfg[i].match(/^\d+$/)) {
                ip.push(i+"="+cfg[i]);
            }
        } else if (i.match(/^(acc|style)$/)) {
            if (cfg[i].match(/^.+$/)) {
                ip.push(i+"="+encodeURIComponent(cfg[i]));
            }
        } else if (i === 'callback') {
            var cb = cfg[i];
            cb = cb.replace(/^\/+/, "");
            if (cb) {
                cb = encodeURIComponent("http://"+document.domain+"/"+cb);
                ip.push(i+"="+cb);
                this.callback = 1;
            }
        } else if (i === 'height') {
            if (cfg[i] && cfg[i].match(/^\d+$/)) {
                this.height =  cfg[i];
            }
        } else if (i === 'debug') {
            if (cfg[i]) {
                if (cfg[i].match(/^\d+$/)) cfg[i] = (+cfg[i]);
                if (cfg[i]) this._debug = 1;
            }
        }
    }
    m.style.height = this.height + "px";
    var i = document.createElement("iframe");
    i.src = this.src + "in?" + ip.join('&');
    i.width = "100%";
    i.height = "2000px";
    i.marginwidth = "0";
    i.marginheight = "0";
    i.vspace = "0";
    i.hspace = "0";
    i.frameborder = "0";
    i.allowtransparency = "true";
    i.scrolling = "no";
    i.style.border = "none";
    m.appendChild(i);
    i.style.cssText = "border: none";
    this.iframe = i;
    
    this._cookie_set("no");
    if (this.callback) {
        this.cookie();
    } else {
        this.timer = setTimeout("_teststudio.jsonp()", this.jsonp_delay);
    }
    if (this._debug) {
        this._debug = debug;
        setTimeout("_teststudio.debug()", 5000);
    }
}
_teststudio._cookie_get = function() {
    if (!this._init_done && !this._init_cb) return 0;
    if (document.cookie.length > 0) {
        var i = document.cookie.indexOf(this.cookie_name + '=');
        if (i != -1) {
            i += this.cookie_name.length + 1;
            var j = document.cookie.indexOf(";", i);
            if (j == -1) {
                j = document.cookie.length;
            }
            return unescape(document.cookie.substring(i, j));
        }
    }
    return 0;
}
_teststudio._cookie_set = function(v) {
    if (!this._init_done && !this._init_cb) return false;
    var t = new Date();
    t.setTime(t.getTime()); // magic
    t = new Date( t.getTime() + (this.cookie_expires * 1000) ); // ms
    document.cookie = this.cookie_name+"="+escape(v)+";expires="+t.toGMTString()+";path=/";
    return true;
}

_teststudio.init();
