var inline = {
	/* local private defines */
	_asyncPrefix : 'mlph',
	_sepPrefix : 'medialand_adland_div_',
	_inlinePrefix : 'medialand_adland_inline_div_',
	_pnames : ['link1','clickTAG'],
	_defaultPlaceDir : 'global',
	_clickServerUrl : 'http://content.rbc.medialand.ru/',
	_useReferer : true,

	/* trying to guess a type of code. First tryed async, then separated, last inline
	return value is an object with a link to banner document, placeholder, window and type: 'async', 'separate', 'inline'
	makeph is used in inline variant. If true it document.write placeholder and take it's hanle, otherwise placeholder is undefined. Mind that it is extremey dangerous to use this option!
	*/
	codeVariant : function(pid){
		var r = new Object();
		try {
		var pd = parent.document;
		if (pd != document){
			r.placeholder = pd.getElementById(this._asyncPrefix+pid);
			if (r.placeholder){ // placeholder found. Wow! We're in async code.
				r.document = pd;
				r.window = parent;
				r.type = 'async';
				return r;
			}
		}
		} catch(e) {}
		r.document = document;
		r.window = window;
		r.placeholder = document.getElementById(this._sepPrefix+pid);
		r.type = (r.placeholder ? 'separate' : 'inline');
		if (r.type == 'inline'){
			r.placeholder = document.getElementById(this._inlinePrefix+pid);
		}
		return r;
	},

	/* returns flash version as an array [main,major,minor] */
	flver : function(){
		var d, n = navigator, f = 'Shockwave Flash';
		if((n = n.plugins) && n[f]){d = n[f].description}
		else if (window.ActiveXObject) { try { d = (new ActiveXObject((f+'.'+f).replace(/ /g,''))).GetVariable('$version');} catch (e) { try { new ActiveXObject((f+'.'+f+'.6').replace(/ /g,'')); d='WIN 6,0,21,0';} catch (e) {} }}
		return d ? d.replace(/\D+/,'').split(/\D+/) : [0,0];
	},
	
	isIE: function(){
		return '\v'=='v';
	},
	
	/* check cookie */
	cookie_enabled : function (ph) {
		var is_enabled = false;

		if (!ph.window.opera && !navigator.cookieEnabled){
			return is_enabled;
		}
		if (typeof ph.document.cookie == 'string'){
			if (ph.document.cookie.length==0) {
				ph.document.cookie = "test";
				is_enabled = ph.document.cookie == 'test';
				ph.document.cookie = '';
			} else {
				is_enabled = true;
			}
		}
		
		return is_enabled;
	},

	/* find a current position of the object */
	FindPos : function(doc, obj) {
		var res = new Object();
		res.left = 0; res.top = 0;
		if (obj) {
			var hideAgain = false;
			if ('none' == obj.style.display){obj.style.display = 'block'; hideAgain = true;}
			if (obj.offsetParent) {
				res.left = obj.offsetLeft;
				res.top = obj.offsetTop;
				while ((obj = obj.offsetParent) && (obj.style.position != 'absolute')) {
					res.left += obj.offsetLeft;
					res.top += obj.offsetTop;
				}
			}
			if (hideAgain) obj.style.display = 'none';
		}
		return res;
	},

	/* window size funcs */
	getBodyScrollTop : function (win,doc) {
		return win.pageYOffset || (doc.documentElement && doc.documentElement.scrollTop) || (doc.body && doc.body.scrollTop);
	},

	getBodyScrollLeft : function (win,doc) {
		return win.pageXOffset || (doc.documentElement && doc.documentElement.scrollLeft) || (doc.body && doc.body.scrollLeft);
	},

	winsize : function(win, doc) {
		var g = new Object();
		g.width = 0;
		g.height = 0;
		var db = doc.body;
		de = doc.documentElement;
		try { 
			if (win.innerWidth == undefined) {
				throw(new Error(-22,"IE must die"));
			}
			g.width = win.innerWidth; // check for netscape and compatible
			g.height = win.innerHeight;
			if (self.outerWidth == g.cw || db.clientWidth == db.scrollWidth) {
				g.width = db.clientWidth; 
			} // fix for firefox
		} catch(e) {
			try {
				if (de && de.clientHeight) {   // Explorer 6 Strict Mode &&de.scrollTop
					g.width = de.clientWidth;
					g.height = de.clientHeight;
				} else {          // other IE
					g.width = db.clientWidth;
					g.height = db.clientHeight;
				}
			} catch(e) {}
		}
		g.scrollX = this.getBodyScrollLeft(win, doc);
		g.scrollY = this.getBodyScrollTop(win, doc);
		return g;
	},


	/*
	 * event functions
	 */
	addEvent : function(ePtr, eventType, eventFunc) {
		if (ePtr.addEventListener){
			ePtr.addEventListener(eventType, eventFunc, false);
		}
		if (ePtr.attachEvent){
			ePtr.attachEvent('on' + eventType, eventFunc);
		}
	},

	removeEvent : function(ePtr, eventType, eventFunc) {
		if (ePtr.addEventListener) {
			ePtr.removeEventListener(eventType, eventFunc, false);
			return;
		}
		ePtr.detachEvent('on' + eventType, eventFunc);
	},

	/* returns a complete swf object. No check is performed on this level */
	_swf : function(file, w, h, link, bgc, wmode, more_links, no_hit_url){
		var fv = '';
		
		if(!no_hit_url){
			fv = no_hit_url ? '' : (this._pnames[0] + '=' + escape(link));
			for (i = 1; i < this._pnames.length; ++i) fv += '&' + this._pnames[i] + "=" + escape(link);
		}
		
		if(typeof(more_links) != 'undefined'){
			if(/^http:\/\/[^\/]+\/reference\?/.test(link)) { // links for engine
				for(i = 0; i < more_links.length; i++){
					if(more_links[i].toUpperCase().indexOf("HTTP://") == 0){
						fv += '&link' + (i+2) + "=" + escape(link + '&reference=' + escape(more_links[i]));
					}
				}
			}
			else { // links for interface
				for(i = 0; i < more_links.length; i++){
					if(more_links[i].toUpperCase().indexOf("HTTP://") == 0){
						fv += '&link' + (i+2) + "=" +(escape(more_links[i]));
					}
				}
			}
		}
		var src = file + (( -1 == file.indexOf('?')) ? '?' : '&') + fv;
		if ('undefined' == bgc) bgc = '#FFFFFF';
		if ('undefined' == wmode) wmode = 'opaque';
		var s = '';
		if (this.isIE()) {
		    s += '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH='+w+' HEIGHT='+h+'>';
		    s += '<PARAM NAME=movie VALUE="'+src+'">';
		    s += '<PARAM NAME=flashvars VALUE="'+fv+'">';
		    s += '<PARAM NAME=wmode VALUE="'+wmode+'">';
		    s += '<PARAM NAME=quality VALUE=high>';
		    s += '<PARAM NAME=menu VALUE=false>';
		    s += '<PARAM NAME=play VALUE=true>';
		    s += '<PARAM NAME=loop VALUE=true>';
		}
		s += '<EMBED src="'+src+'" menu=false flashvars="'+fv+'" wmode="'+wmode+'" quality=high swLiveConnect=FALSE play=true loop=true WIDTH='+w+' height='+h+' TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash">';
		s += '</EMBED>';
		if (this.isIE()) s += '</OBJECT>';
		s += '<BR/>';
		return s;
	},
	_gif : function(file, w, h, link, no_hit_url){
		s = '';
		s += no_hit_url ? '' : '<a href="'+link+'" target=_blank>';
		s += '<img src="'+file+'" width='+w+' height='+h+' alt="" border=0>';
		s += '<br />';
		s += no_hit_url ? '' : '</a>';
		return s;
	},

	/* Now perform checks and return a table with content OR nothing */
	obj : function(swf, gif, w, h, link, fv, bgc, wmode, more_links, gif_w, gif_h, b_center, no_hit_url){
		var s = '<table border="0" cellpadding="0" cellspacing="0" style="margin: 0; padding: 0;'+((typeof(b_center) != "undefined" && b_center) ? 'text-align:center;' : '')+' border:none; width: 100%;"><tr style="margin: 0; padding: 0; border:none"><td style="margin: 0; padding: 0; border:none;'+((typeof(b_center) != "undefined" && b_center) ? 'text-align:center;' : '')+'">';
		if ((fv <= parseInt(this.flver()[0])) && (0 == swf.toUpperCase().indexOf('HTTP://'))) {
			s+= this._swf(swf, w, h, link, bgc, wmode, more_links, no_hit_url); 
		} else {
			if (0 != gif.toUpperCase().indexOf('HTTP://')) return '';
			if(typeof(gif_w) != "undefined" && typeof(gif_h) != "undefined") {
				s += this._gif(gif, gif_w, gif_h, link, no_hit_url);
			}
			else {
				s += this._gif(gif, w, h, link, no_hit_url);
			}
		}
		s += '</td></tr></table>';
		return s;
	},

	inject : function(pid, swf, gif, w, h, link, fv, bgc, wmode, more_links, div_style, gif_w, gif_h, b_center, no_hit_url){
		var o = this.obj(swf, gif, w, h, link, fv, bgc, wmode, more_links, gif_w, gif_h, b_center, no_hit_url);
		if ('' == o) return null;
		var p = this.codeVariant(pid);
		p.placeholder.innerHTML = o;
		with(p.placeholder.style) {
			display = 'block';
			visibility = 'visible';
			width = (w == "" ? "0px" : (w + ((w.indexOf('%') > -1) ? '' : 'px')));
		}
		if(typeof(div_style) == "object") {
			div_style.width = (div_style.width == "" || div_style.width == "100%") ? (document.compatMode == "BackCompat" ? "100%" : "auto") : (div_style.width.indexOf('%') == -1 ? div_style.width + 'px' : div_style.width);

			for(prop in div_style) {
				with(p.placeholder.style) {
					try{
						eval(prop + '="' + div_style[prop] + '"');
					}catch(e){}
				}
			}
		}
		if (p.type == 'async') setTimeout('document.close()', 1000);
		return p;
	},

	callevent : function(z, rand_url, ph) {
		var imgHandle;
			
		if(!this.cookie_enabled(ph)){
			return;
		}
			
		for (var i in z) {
			if (!z.hasOwnProperty(i)) continue;
			if(z[i].toUpperCase().indexOf("HTTP://") == 0) {
				imgHandle = ph.document.createElement("img");
				imgHandle.style.display = "none";
				imgHandle.style.width = "0px";
				imgHandle.style.height = "0px";
				if(typeof(rand_url) != 'undefined') {
					imgHandle.src = (z[i].indexOf('?') > 0) ? z[i] + '&' + rand_url : z[i] + '?' + rand_url;
				}
				else {
					imgHandle.src = z[i];
				}

				ph.placeholder.appendChild(imgHandle);		
			}
		}	
	},

	listener : function(b){
		var g = inline.winsize(b.ph.window, b.ph.document);
		var h = inline.FindPos(b.ph.document, b.ph.placeholder).top+b.h/2; // banner middle
			if (Math.abs(g.scrollY+g.height/2-h)<=g.height/2){ // banner middle is visible
				inline.callevent(b.zeropixel, b.rand_url, b.ph);
				inline.removeEvent(b.ph.window, 'scroll', b.listener);
				inline.removeEvent(b.ph.window, 'resize', b.listener);
			}
	},

	init : function(b){
		/*validate*/
		b.w = b.w.toString();
		b.h = b.h.toString();
		
		if(this._useReferer) {
			b.place_dir = ((typeof(b.place_dir) != 'undefined' && b.place_dir.length) ? escape(b.place_dir) : this._defaultPlaceDir);
			b.link = this._clickServerUrl + b.place_dir + '/?' + escape(b.link);	
		}
		
		b.ph = this.inject(b.pid, b.swf, b.gif, b.w, b.h, b.link, b.fv, b.bgc, b.wmode, b.more_links, b.div_style, b.gif_w, b.gif_h, b.banner_align_center, b.no_hit_url);
		if (null != b.ph) {
			if (b.eshows) {
				b.listener = new Function('inline.listener('+b.name+')');
				this.addEvent(b.ph.window, 'scroll', b.listener);
				this.addEvent(b.ph.window, 'resize', b.listener);
				b.listener(); // forse check, banner maight be already visible
			} else {
				inline.callevent(b.zeropixel, b.rand_url, b.ph);
			}
		}
	}
}
