var VIDEOCLICK=false;

VideoclickRun();

function VideoclickRun() {
    if (!_rbn.v.ad || _rbn.v.ad.length == 0) {
        setTimeout(VideoclickRun, 100);
        return;
    }
    if (typeof(window._vc_run)!='undefined') {
        return;
    }
    window._vc_run = true;
    VIDEOCLICK = new Videoclick(_rbn.v.ad);
    if (_rbn != null && _rbn.v != null) {
        if (_rbn.v.inline_color != null) {
            VIDEOCLICK.w_style.color = _rbn.v.inline_color;
        }
        if (_rbn.v.is_use_marked != null) {
            VIDEOCLICK.params.use_marked = _rbn.v.is_use_marked;
        }
        if (_rbn.v.autostart_video != null) {
            VIDEOCLICK.params.autostart_video = _rbn.v.autostart_video;
        }
        if (_rbn.v.inline_count_max != null) {
            VIDEOCLICK.params.inline_limit = _rbn.v.inline_count_max;
        }
        VIDEOCLICK.params.inline_limit = 10;
    }
    VIDEOCLICK.run();
}

function _rbn_close() {
    _rbn_ev('close');
}

function _rbn_ev(ev) {
    switch (ev) {
        case 'click':
        case 'close':
            setTimeout(function () {
                if (VIDEOCLICK.show_id > -1) {
                    VIDEOCLICK.hideBanner(VIDEOCLICK.show_id);
                }
            }, 0);
            break;
    }
}

function Videoclick(ads) {
    this.ads = ads;
    this.params = {
        'use_marked'   : false,
        'inline_limit' : 10,
        'info_url' : 'http://videoclick.ru/',
        'show_timeout' : 100,
        'hide_timeout' : 700,
        'autostart_video': true
    };
    this.skip = {
        'SCRIPT': 1,'NOSCRIPT': 1,'H1': 1,'H2': 1,'H3': 1,'H4': 1,'H5': 1,'H6': 1,'BIG': 1,'A': 1,'TH': 1,'FIELDSET': 1,'TEXTAREA': 1,'SELECT': 1,'LEGEND': 1,'ACRONYM': 1,'ADDRESS': 1,'LABEL': 1
    }
    this.w_bounds = '(^|$|[^0-9a-zA-Zа-яА-Я_])';
    this.neg = [];
    this.negr = [];
    this.blocks = [];
    this.w_style = {
        'cursor'            : 'pointer',
        'color'             : '#009900',
        'textDecoration'    : 'none',
        'borderStyle'       : 'solid',
        'borderWidth'       : '0 0 1px 0'
    };
    this.inline_count = 0;
    this.showTimer = false;
    this.hideTime = false;
    this.show_id = -1;
    this.location = escape(window.location.href);
    
    this.run = function() {
        var n = document.getElementsByTagName("body")[0];
        this.prepareRegexp();
        this.scanBlocks(n);
        if (this.scanNeg()) {
            return;
        }
        this.scanWords();
        this.setEvents();
    }
    
    this.prepareRegexp = function() {
        var i, j, n;
        this.ads.sort(function(){return (Math.round(Math.random())-0.5);});
        for (i = 0; i < this.ads.length; i++) {
            this.ads[i].words = this.ads[i].keyword.split(";");
            this.ads[i].words.sort(function(){return (Math.round(Math.random())-0.5);});
            this.ads[i].regexp = new Array();
            this.ads[i].negr = new Array();
            this.ads[i].inlined = new Array();
            this.ads[i].word = new Array();
            this.ads[i].skip = false;
            for (j = 0; j < this.ads[i].words.length; j++) {
                this.ads[i].regexp[j] = new RegExp(this.w_bounds + '(' + this.ads[i].words[j] + ')' + this.w_bounds, 'ig');
                this.ads[i].inlined[j] = false;
            }
            n = this.ads[i].negative.split(";");
            for (j = 0; j < n.length; j++) {
                if (n[j] != "") {
                    this.ads[i].negr.push(new RegExp(this.w_bounds + '(' + n[j] + ')' + this.w_bounds, 'ig'));
                }
            }
        }
        for (i = 0; i < this.neg.length; i++) {
            this.negr[i]= new RegExp(this.w_bounds + '(' + this.neg[i] + ')' + this.w_bounds,'ig');
        }
    }
    
    this.scanBlocks = function(n, b) {
        if (n.nodeType == 3) {
            if (this.params.use_marked && !b) {
                return;
            }
            if (n.data.replace(/\s+/g, "")) {
                this.blocks.push(n);
            }
        } else {
            for (var i = n.firstChild; i != null; i = i.nextSibling) {
                if (this.inline_count >= this.params.inline_limit) {
                    break;
                }
                if (this.skip[i.nodeName.toUpperCase()] == 1) {
                    continue;
                }
                if (i.className) {
                    if (i.className.indexOf("_noreachbanner_") != -1) {
                        continue;
                    }
                    if (typeof(i.id)=="string" && i.id.indexOf("y5_direct") != -1) {
                        continue;
                    }
                    if (i.className.indexOf("_reachbanner_") != -1) {
                        this.scanBlocks(i, true);
                        continue;
                    }
                }
                this.scanBlocks(i, b);
            }
        }
    }

    this.scanNeg = function() {
        var i, j, k, r, n;
        for (k = 0; k < this.blocks.length; k++) {
            n = this.blocks[k];
            for (i = 0; i < this.negr.length; i++) {
                r = this.negr[i].exec(n.data);
                if (r != null) {
                    return true;
                }
            }
            for (i = 0; i < this.ads.length; i++) {
                for (j = 0; j < this.ads[i].negr.length; j++) {
                    r = this.ads[i].negr[j].exec(n.data);
                    if (r != null) {
                        this.ads[i].skip = true;
                        break;
                    }
                }
            }
        }
        return false;
    }
        
    this.scanWords = function() {
        var i, j, k, r, nn;
        for (k = 0; k < this.blocks.length; k++) {
            n = this.blocks[k];
            for (i = 0; i < this.ads.length; i++) {
                if (this.ads[i].skip) {
                    continue;
                }
                if (this.inline_count >= this.params.inline_limit) {
                    break;
                }
                for (j = 0; j < this.ads[i].words.length; j++) {
                    if (this.ads[i].inlined[j]) {
                        continue;
                    }
                    r = this.ads[i].regexp[j].exec(n.data);
                    if (r != null) {
                        nn = this.inlineWord(n, i, j, r.index + r[1].length, r[2].length);
                        if (nn) {
                            n = nn;
                        }
                        if (this.inline_count >= this.params.inline_limit) {
                            break;
                        }
                    }
                }
            }
        }
    }
    
    this.inlineWord = function(n, i, j, b, l) {
        var pn = n.parentNode;
        if (pn) {
            var ic = this.makeIconHTML(i);
            var wn = this.makeWordHTML(i, j, n.data.substr(b, l));
            var bn = b > 0 ? document.createTextNode(n.data.substr(0, b)) : document.createTextNode("");
            var an = (b + l) < n.data.length ? document.createTextNode(n.data.substr(b + l, n.data.length - (b + l))) : document.createTextNode("");
            pn.replaceChild(an, n);
            if (ic != null) {
                pn.insertBefore(ic, an);
                pn.insertBefore(wn, ic);
            } else {
                pn.insertBefore(wn, an);
            }
            pn.insertBefore(bn, wn);
            this.ads[i].inlined[j] = true;
            this.inline_count++;
            return an;
        }
        return null;
    }
    
    this.makeWordHTML = function(i, j, w) {
        var n = document.createElement("A");
        n.appendChild(document.createTextNode(w));
        n.href = 'javascript://';
        for (var p in this.w_style) {
            n.style[p] = this.w_style[p];
        }
        this.ads[i].word[j] = n;
        return n;
    }

    this.makeIconHTML = function(i) {
        if (typeof(this.ads[i].icon) == "undefined" || this.ads[i].icon == '') {
            return null;
        }
        var n = document.createElement("IMG");
        n.src = this.ads[i].icon;
        n.style.borderWidth = '0';
        n.style.margin = '0 0 0 3px';
        n.style.padding = '0';
        return n;
    }

    this.makeBannerHTML = function(i) {
        var o, v, n, m;
        if (typeof(this.ads[i].ver) != 'undefined' && this.ads[i].ver == "2") {
            v =  'clickTAG=' + escape(this.ads[i].click_url + '&ul=' + this.location) + '&fileURL=' + escape(this.ads[i].video_url) + '&statScript=' + escape("javascript:_rbn_ev('{event}')");
            if (!this.params.autostart_video) {
                v += "&autoPlay=false";
            }
            v += "&fullScreen=false";
        } else {
            v =  'clickTAG=' + escape(this.ads[i].click_url + '&ul=' + this.location) + '&fileURL=' + escape(this.ads[i].video_url) + '&infoURL=' + escape(this.params.info_url);
            if (typeof(this.ads[i].xml) != 'undefined' && this.ads[i].xml != '') {
                v += "&tags="+this.ads[i].xml;
            }
            if (typeof(this.ads[i].banner) != 'undefined' && this.ads[i].banner != '') {
                v += "&banner="+this.ads[i].banner;
            }
            for (var k in this.ads[i].flash_vars) {
    	        v += "&"+k+"="+escape(this.ads[i].flash_vars[k]);
            }
            if (!this.params.autostart_video) {
                v += "&jsPause=PAUSE_ON";
            }
        }
        if (typeof(this.ads[i].internalClick) != 'undefined' && this.ads[i].internalClick == "1") {
            v += "&internalClick=true";
        }
        o = '<object id="_vc_flash_' + i + '" width="' + this.ads[i].width + '"  height="' + this.ads[i].height + '" data="' + this.ads[i].flash_url + '" type="application/x-shockwave-flash">';
        o += '<param name="movie" value="' + this.ads[i].flash_url + '"/>';
        o += '<param name="quality" value="high"/>';
        o += '<param name="wmode" value="'+((typeof(this.ads[i].wmode) != 'undefined' && this.ads[i].wmode != '') ? this.ads[i].wmode : 'transparent')+'"/>';
        o += '<param name="bgcolor" value="#ffdddd"/>';
        o += '<param name="scale" value="exactfit"/>';
        o += '<param name="swliveconnect" value="true"/>';
        o += '<param name="allowscriptaccess" value="always"/>';
        o += '<param name="allowFullScreen" value="true"/>';
        o += '<param name="flashvars" value="' + v + '">';
        o += '</object>';
        n = document.createElement("DIV");
        n.className = '_noreachbanner_';
        n.innerHTML = o;
        n.style.display = 'none';
        n.style.position = 'absolute';
        n.style.zIndex = 99999;
        n.style.width = this.ads[i].width + 'px';
        n.style.height = this.ads[i].height + 'px';
        return n;
    }
    
    this.showBanner = function(i, j) {
        this.createBanner(i, j);
        var b = this.ads[i].banner;
        if (b == null) {
            return;
        }
        var w = this.getPageWidth();
        var h = this.getPageHeight();
        var sy = this.getScrollY();
        var x = this.getPosX(this.ads[i].word[j]);
        var y = this.getPosY(this.ads[i].word[j]);
        var kw = this.ads[i].word[j].offsetWidth;
        var kh = this.ads[i].word[j].offsetHeight;
        var bx, by;
        var body = document.getElementsByTagName("body")[0];
        if (x < (w / 2)) {
            bx = x;
        } else {
            bx = x - this.ads[i].width + 30;
        }
        if ((y - sy) < (h / 2)) {
            by = y + kh + 3;
        } else {
            by = y - this.ads[i].height - 3;
        }
        b.style.top = by + 'px';
        b.style.left = bx + 'px';
        b.style.display = 'block';
        if (!this.ads[i].trace) {
            if (this.ads[i].trace_url) {
                this.cacheFile(this.ads[i].trace_url+'&ul='+this.location);
            }
            if (this.ads[i].trace_url2 && this.ads[i].trace_url2.length > 0) {
                this.cacheFile(this.ads[i].trace_url2);
            }
            this.ads[i].trace = true;
        }
        if (body) {
            body.appendChild(b);
        }
        VIDEOCLICK.show_id = i;
        VIDEOCLICK.showTimer = false;
    }
    
    this.hideBanner = function(i) {
        var n = this.ads[i].banner;
        if (n) {
            var body = document.getElementsByTagName("body")[0];
            n.style.display = 'none';
            if (body) {
                body.removeChild(n);
            }
        }
        VIDEOCLICK.show_id = -1;
        VIDEOCLICK.hideTimer = false;
    }
    
    this.createBanner = function(i, j) {
        if (this.ads[i].word[j]) {
            this.ads[i].banner = this.makeBannerHTML(i, j);
            this.ads[i].banner.onmouseover = new Function('VIDEOCLICK.eventBannerMouseOver('+i+','+j+')');
            this.ads[i].banner.onmouseout = new Function('VIDEOCLICK.eventBannerMouseOut('+i+','+j+')');
        }
    }
    
    this.setEvents = function() {
        var i, j;
        for (i = 0; i < this.ads.length; i++) {
            for (j = 0; j < this.ads[i].word.length; j++) {
                if (this.ads[i].word[j]) {
                    this.ads[i].word[j].onmouseover = new Function('VIDEOCLICK.eventWordMouseOver('+i+','+j+')');
                    this.ads[i].word[j].onmouseout = new Function('VIDEOCLICK.eventWordMouseOut('+i+','+j+')');
                }
            }
        }
    }
    
    this.eventWordMouseOver = function(i, j) {
        this.ads[i].word[j].style.borderWidth = '0 0 2px 0';
        if (VIDEOCLICK.show_id > -1) {
            if (VIDEOCLICK.show_id == i) {
                if (VIDEOCLICK.hideTimer) {
                    clearTimeout(VIDEOCLICK.hideTimer);
                    VIDEOCLICK.hideTimer = false;
                }
                return;
            } else {
                VIDEOCLICK.hideBanner(VIDEOCLICK.show_id);
            }
        }
        VIDEOCLICK.showTimer = setTimeout('VIDEOCLICK.showBanner('+i+','+j+')', VIDEOCLICK.params.show_timeout);
    }

    this.eventWordMouseOut = function(i, j) {
        this.ads[i].word[j].style.borderWidth = this.w_style['borderWidth'];
        if (VIDEOCLICK.showTimer) {
            clearTimeout(VIDEOCLICK.showTimer);
            VIDEOCLICK.showTimer = false;
        }
        if (VIDEOCLICK.show_id > -1) {
            VIDEOCLICK.hideTimer = setTimeout('VIDEOCLICK.hideBanner('+i+')', VIDEOCLICK.params.hide_timeout);
        }
    }

    this.eventBannerMouseOver = function(i, j) {
        if (VIDEOCLICK.hideTimer) {
            clearTimeout(VIDEOCLICK.hideTimer);
            VIDEOCLICK.hideTimer = false;
        }
    }

    this.eventBannerMouseOut = function(i, j) {
        VIDEOCLICK.hideTimer = setTimeout('VIDEOCLICK.hideBanner('+i+')', VIDEOCLICK.params.hide_timeout);
    }
    
    this.cacheFile = function(u) {
        (new Image(10, 10)).src = u.replace("{rid}", Math.random()); 
    }
    
    this.getPosX = function(o) {
        var x = 0;
        if (o.offsetParent) {
            while (o) {
                x += o.offsetLeft;
                o = o.offsetParent;
            }
        } else {
            if (o.x) {
                x = o.x;
            }
        }
        return x;
    }
    
    this.getPosY = function(o) {
        var y = 0;
        if (o.offsetParent) {
            while (o) {
                y += o.offsetTop;
                o = o.offsetParent;
            }
        } else {
            if (o.y) {
                y = o.y;
            }
        }
        return y;
    }
    this.getPageWidth = function() {
        var x = 0;
        if (typeof(window.innerWidth) == 'number') {
            x = window.innerWidth;
        } else if (document.documentElement && document.documentElement.clientWidth) {
            x = document.documentElement.clientWidth;
        } else if (document.body && document.body.clientWidth) {
            x = document.body.clientWidth;
        }
        return x;
    }
    this.getPageHeight = function() {
        var y;
        if (typeof(window.innerHeight) == 'number') {
            y = window.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) {
            y = document.documentElement.clientHeight;
        } else if (document.body.clientHeight) {
            y = document.body.clientHeight;
        }
        return y;
    }
    this.getScrollX = function() {
        var x = 0;
        if (typeof(window.pageXOffset) == 'number') {
            x = window.pageXOffset;
        } else if (document.body && document.body.scrollLeft) {
            x = document.body.scrollLeft;
        } else if (document.documentElement && document.documentElement.scrollLeft) {
            x = document.documentElement.scrollLeft;
        }
        return x;
    }
    this.getScrollY = function() {
        var y = 0;
        if (typeof(window.pageYOffset) == 'number') {
            y = window.pageYOffset;
        } else if (document.body && document.body.scrollTop) {
            y = document.body.scrollTop;
        } else if (document.documentElement && document.documentElement.scrollTop) {
            y = document.documentElement.scrollTop;
        }
        return y;
    }    
}

function test2() {
    var ob=document.getElementsByTagName("body")[0];
    var os=document.createElement('script'),loaded=false;
    os.setAttribute('type','text/javascript');
    os.setAttribute('charset','utf-8');
    os.setAttribute('src','http://drive2.videoclik.ru/code?pid=1&rid='+Math.floor(Math.random()));
    os.onload=os.onreadystatechange=function() {
        var st=this.readyState;
        if (loaded || (st && st!='complete' && st!='loaded')) {
            return;
        }
        ob.removeChild(os);
    }
    ob.appendChild(os);
}
