/**
 * Subsys_JsHttpRequest_Js: JavaScript DHTML data loader. (C) 2005 Dmitry
 * Koterov, http://forum.dklab.ru/users/DmitryKoterov/
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version. See http://www.gnu.org/copyleft/lesser.html
 *
 * Do not remove this comment if you want to use script!
 * Не удаляйте данный комментарий, если вы хотите использовать скрипт!
 * Что то на русском языке
 *
 * This library tries to use XMLHttpRequest (if available), and on failure - use
 * dynamically created <script> elements. Backend code is the same for both
 * cases.
 *
 * @author Dmitry Koterov
 * @version 3.26
 */

function Subsys_JsHttpRequest_Js(){this._construct();}(function(){var COUNT=0;var PENDING={};var CACHE={};Subsys_JsHttpRequest_Js.dataReady=function(id,text,js){var undef;var th=PENDING[id];delete PENDING[id];if(th){delete th._xmlReq;if(th.caching){CACHE[th.hash]=[text,js];}th._dataReady(text,js);}else{if(typeof(th)!=typeof(undef)){alert("ScriptLoader: unknown pending id: "+id);}}};Subsys_JsHttpRequest_Js.prototype={onreadystatechange:null,readyState:0,responseText:null,responseXML:null,status:200,statusText:"OK",session_name:"PHPSESSID",responseJS:null,caching:false,_span:null,_id:null,_xmlReq:null,_openArg:null,_reqHeaders:null,abort:function(){if(this._xmlReq){return this._xmlReq.abort();}if(this._span){this.readyState=0;if(this.onreadystatechange){this.onreadystatechange();}this._cleanupScript();}},open:function(method,url,asyncFlag,username,password){this._openArg={method:method,url:url,asyncFlag:asyncFlag,username:username,password:password};this._id=null;this._xmlReq=null;this._reqHeaders=[];return true;},send:function(content,id){if(!id){id=(new Date().getTime())+""+COUNT++;}var query=this._hash2query(content);var url=this._openArg.url;var sid=this._getSid();if(sid){url+=(url.indexOf("?")>=0?"&":"?")+this.session_name+"="+this.escape(sid);}var hash=this.hash=url+"?"+query;if(this.caching&&CACHE[hash]){var c=CACHE[hash];this._dataReady(c[0],c[1]);return false;}this._xmlReq=this._obtainXmlReq(id,url);var hasSetHeader=this._xmlReq&&(window.ActiveXObject||this._xmlReq.setRequestHeader);var href,body;if(this._xmlReq&&hasSetHeader&&(""+this._openArg.method).toUpperCase()=="POST"){this._openArg.method="POST";href=url;body=query;}else{this._openArg.method="GET";href=url+(url.indexOf("?")>=0?"&":"?")+query;body=null;}href=href+(href.indexOf("?")>=0?"&":"?")+"id="+id+"&"+id;PENDING[id]=this;if(this._xmlReq){var a=this._openArg;this._xmlReq.open(a.method,href+"-xml",a.asyncFlag,a.username,a.password);if(hasSetHeader){for(var i=0;i<this._reqHeaders.length;i++){this._xmlReq.setRequestHeader(this._reqHeaders[i][0],this._reqHeaders[i][1]);}this._xmlReq.setRequestHeader("Content-Type","application/octet-stream");}return this._xmlReq.send(body);}else{this._obtainScript(id,href);return true;}},getAllResponseHeaders:function(){if(this._xmlReq){return this._xmlReq.getAllResponseHeaders();}return"";},getResponseHeader:function(label){if(this._xmlReq){return this._xmlReq.getResponseHeader(label);}return"";},setRequestHeader:function(label,value){this._reqHeaders[this._reqHeaders.length]=[label,value];},_construct:function(){},_dataReady:function(text,js){with(this){if(text!==null||js!==null){readyState=4;responseText=responseXML=text;responseJS=js;}else{readyState=0;responseText=responseXML=responseJS=null;}if(onreadystatechange){onreadystatechange();}_cleanupScript();}},_obtainXmlReq:function(id,url){if(url.match(new RegExp("^[a-z]+://","i"))){return null;}var req=null;if(window.XMLHttpRequest){try{req=new XMLHttpRequest();}catch(e){}}else{if(window.ActiveXObject){try{req=new ActiveXObject("Microsoft.XMLHTTP");}catch(e){}if(!req){try{req=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){}}}}if(req){var th=this;req.onreadystatechange=function(){if(req.readyState==4){var responseText=req.responseText;try{eval(responseText);}catch(e){Subsys_JsHttpRequest_Js.dataReady(id,"JavaScript code generated by backend is invalid!\n"+responseText,null);}}else{th.readyState=req.readyState;if(th.onreadystatechange){th.onreadystatechange();}}};this._id=id;}return req;},_obtainScript:function(id,href){with(document){var span=null;span=body.appendChild(createElement("SPAN"));span.style.display="none";span.innerHTML="Text for stupid IE.<script><\/script>";setTimeout(function(){var s=span.getElementsByTagName("script")[0];s.language="JavaScript";if(s.setAttribute){s.setAttribute("src",href);}else{s.src=href;}},10);this._id=id;this._span=span;}},_cleanupScript:function(){var span=this._span;if(span){this._span=null;setTimeout(function(){span.parentNode.removeChild(span);},50);}return false;},_hash2query:function(content,prefix){if(prefix==null){prefix="";}var query=[];if(content instanceof Object){for(var k in content){var v=content[k];if(v.constructor.prototype[k]){continue;}var curPrefix=prefix?prefix+"["+this.escape(k)+"]":this.escape(k);if(v instanceof Object){query[query.length]=this._hash2query(v,curPrefix);}else{query[query.length]=curPrefix+"="+this.escape(v);}}}else{query=[content];}return query.join("&");},_getSid:function(){var m=document.location.search.match(new RegExp("[&?]"+this.session_name+"=([^&?]*)"));var sid=null;if(m){sid=m[1];}else{var m=document.cookie.match(new RegExp(s="(;|^)\\s*"+this.session_name+"=([^;]*)"));if(m){sid=m[2];}}return sid;},escape:function(s){return escape(s).replace(new RegExp("\\+","g"),"%2B");}};})();

var ifolder_adv_iteration_limit = 3;
//var show_ifolder_adv = 0;
//var ifolder_adv_hash_right = new Array();

function is_left_middle_step() {
	var ret = 'exists';
	var td_flash = document.getElementById('td_flash');
	if (!td_flash) {
		var ret = 'not_exists';
	}
	return ret;
}

function is_right_middle_step() {
	var ret = 'exists';
	var ad_ph_1 = document.getElementById('ad_ph_1');
	if (ad_ph_1) {
		var content_div = ad_ph_1.innerHTML;
		var re = /ifolder.ru\/images\/empty\.gif/g;
		var result = content_div.match(re);
		if (result) {
			if (result[0] == 'ifolder.ru/images/empty.gif') {
				var ret = 'not_exists';
			}
		}
	}
	return ret;

}

function top_iframe() {
	$('<div/>').attr('id', 'top-top-banner').css({
		textAlign : 'center'
	}).prependTo('body');

	var topCon = document.getElementById('top-top-banner');
	var iframe = new iFrame(topCon);

	iframe.id = 'fr_top';
	iframe.src = '/top_ads';
	iframe.style.width = '800px';
	iframe.style.height = '1px';
	iframe.doc.close();
}

function top_ads_new() {

	var BannerId = '';
	var BannerText = '';
	var BannerType = '';
	var req = new Subsys_JsHttpRequest_Js();

	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.responseJS) {
				BannerId = req.responseJS.BannerId;
				BannerText = req.responseJS.BannerText;
				BannerType = req.responseJS.BannerType;

				if (typeof(BannerId) != 'undefined' && BannerId != 0 && BannerId != 40)
				{
					if (BannerType == 'script')
					{
						var re = /^<script[^>]*>/ig;
						var m = re.exec(BannerText);
						if( m == null )
						{
							BannerText = '<script type="text/javascript">'+BannerText+'</script>';
						}						
					}
					setTimeout(function(){ doc_write(BannerText, 'top', 100) }, 1000);
					return true;
				}
			}
		}
	}

	var _login = 'ifolder_top.468x60';
	var _options = 'options=X';
	var _random = Math.round(Math.random() * 100000);
	var url = 'http://ad.popup.tbn.ru/cgi-bin/iframe/';
	var src = url + _login + '?' + _random + '&' + _options;
	req.caching = false;
	req.open('GET', src, true);
	var tt = Math.floor(Math.random() * (1000 - 0 + 1)) + 0;
	req.send({}, _random);

	return false;
}

function getAdHash( side, type){
	var hash = new Array();

	if( side == 'left' )
	{
		if( type == 'main')
		{
			hash[0] = {
				url:'http://ad.popup.tbn.ru/cgi-bin/iframe/',
				key:'popup240',
				login:'ifolder_default_left_banner_default.240x400'
			};
			hash[1] = {
				url:'http://ad.agava.tbn.ru/cgi-bin/iframe/',
				key:'agava240',
				login:'ifolder_allpages_left'
			};
			hash[2] = {
				url:'http://ad.240x400-1.adbn.ru/cgi-bin/iframe/',
				key:'adbn240',
				login:'a_ifolder_l'
			};
		}
		else
		{
			hash[0] = {
				url:'http://ad.popup.tbn.ru/cgi-bin/iframe/',
				key:'popup240',
				login:'ifolder_main_left_banner_main.240x400'
			};
			hash[1] = {
				url:'http://ad.agava.tbn.ru/cgi-bin/iframe/',
				key:'agava240',
				login:'ifolder_allpages_left'
			};
			hash[2] = {
				url:'http://ad.240x400-1.adbn.ru/cgi-bin/iframe/',
				key:'adbn240',
				login:'a_ifolder_l'
			};
		}
	}
	else if( side == 'right' )
	{
		if( type == 'main')
		{
			hash[0] = {
				url:'http://ad.popup.tbn.ru/cgi-bin/iframe/',
				key:'agava240',
				'login':'ifolder_main_right_banner_main.240x400'
			};
			hash[1] = {
				url:'http://ad.agava.tbn.ru/cgi-bin/iframe/',
				key:'agava240',
				'login':'ifolder_allpages_right'
			};
			hash[2] = {
				url:'http://ad.240x400-1.adbn.ru/cgi-bin/iframe/',
				key:'adbn240',
				'login':'a_ifolder_r'
			};
		}
		else
		{
			hash[0] = {
				url:'http://ad.popup.tbn.ru/cgi-bin/iframe/',
				key:'agava240',
				login:'ifolder_default_right_banner_default.240x400'
			};
			hash[1] = {
				url:'http://ad.agava.tbn.ru/cgi-bin/iframe/',
				key:'agava240',
				login:'ifolder_allpages_right'
			};
			hash[2] = {
				url:'http://ad.240x400-1.adbn.ru/cgi-bin/iframe/',
				key:'adbn240',
				login:'a_ifolder_r'
			};
		}
	}

	return hash;
}

function manipulate( pos, size ){

	if( pos == 'top' )
	{
		$('#fr_top').css({
			height: '100px'
		});
		return true;
	}

	var ifr = $('#fr_'+pos);
	var ibr_id = parseInt(ifr.contents().find('body').attr('id'));

	if( ibr_id > 0 )
	{
		ifr.css({
			width: ibr_id+'px',
			height: ((ibr_id == 240 ) ? 420 : 260)+'px'
		});
	}

	return true;
}

function doc_write( BannerText, pos, size ){

	BannerText = '<html><head></head><body id="'+size+'">'+ BannerText + '<style type="text/css">body{margin:0px;padding:0px;background:transparent;}</style>';
	if( size )
	{
		BannerText = BannerText + '<script type="text/javascript">parent.manipulate("'+pos+'", "'+size+'");</script>';
	}
	BannerText = BannerText+'</body></html>';

	document.write(BannerText);
	document.close();
}

function iframe_ads(side, type, mstep){
	
	
	if( side == 'left' && mstep == 1 )
	{
		if (is_left_middle_step() == 'exists') {
			return false;
		}
	}
	else if( side == 'right' && mstep == 1 )
	{
		if (is_right_middle_step() == 'exists') {
			return false;
		}
	}	
		

	var cont_id = ( side == 'left' ) ? 'avi_left_banner' : 'avi_right_banner';
	var cont = document.getElementById(cont_id);
	var iframe = new iFrame(cont);

	iframe.id = 'fr_'+side;
	iframe.src = '/iframe_ads?type='+type+'&amp;side='+side+( mstep ? '&amp;mstep='+ mstep : '');
	iframe.style.width = '1px';
	iframe.style.height = '1px';

	iframe.doc.close();
}

function print_iframe_ads(iteration, ifolder_adv_hash, use_middle_step, side, type)
{
	if (use_middle_step == 'right_middle_step') {
		if (is_right_middle_step() == 'exists') {
			return false;
		}
	} else {
		if (use_middle_step == 'left_middle_step') {
			if (is_left_middle_step() == 'exists') {
				return false;
			}
		}
	}	

	if( ifolder_adv_hash == '' )
	{
		var ifolder_adv_hash = getAdHash(side, type);
	}

	var req = new Subsys_JsHttpRequest_Js();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.responseJS) {
				BannerId = req.responseJS.BannerId;
				BannerText = req.responseJS.BannerText;
				BannerType = req.responseJS.BannerType;

				if (typeof(BannerId) != 'undefined' && BannerId != 0 && BannerId != 40)
				{
					if(BannerText)
					{
						if (BannerType == 'script')
						{
							var re = /^<script[^>]*>/ig;
							var m = re.exec(BannerText);
							if( m == null )
							{
								BannerText = '<script type="text/javascript">'+BannerText+'</script>';
							}
						}
						setTimeout(function(){ doc_write(BannerText, side, 240) }, 1000);
						return true;
					}
					else
					{
						++iteration;
						if (iteration < ifolder_adv_iteration_limit)
						{
							print_iframe_ads(iteration, ifolder_adv_hash, use_middle_step, side, type)
						}
						else
						{
							print_partner_iframe(side, type, use_middle_step);
							return true;
						}
					}
				}
				else
				{
					++iteration;
					if (iteration < ifolder_adv_iteration_limit) {
						print_iframe_ads(iteration, ifolder_adv_hash, use_middle_step, side, type)
					}
					else
					{
						print_partner_iframe(side, type, use_middle_step);
						return true;
					}
				}
			}
		}
	}

	var _login = ifolder_adv_hash[iteration].login;
	var _options = 'options=X';
	var _random = Math.round(Math.random() * 100000);
	var url = ifolder_adv_hash[iteration].url;
	var key = ifolder_adv_hash[iteration].key;
	var src = url + _login + '?' + _random + '&' + _options;
	req.caching = false;
	req.open('GET', src, true);
	var tt = Math.floor(Math.random() * (1000 - 0 + 1)) + 0;
	req.send({}, _random);
	return true;
}


function print_ads(iteration, ifolder_adv_hash, ifolder_adv_container,use_middle_step, side, type) {

	var BannerId = '';
	var BannerText = '';
	var BannerType = '';
	if (use_middle_step == 'right_middle_step') {
		if (is_right_middle_step() == 'exists') {
			return false;
		}
	} else {
		if (use_middle_step == 'left_middle_step') {
			if (is_left_middle_step() == 'exists') {
				return false;
			}
		}
	}

	if( ifolder_adv_hash == '' )
	{
		var ifolder_adv_hash = getAdHash(side, type);
	}

	var container = document.getElementById(ifolder_adv_container);
	var req = new Subsys_JsHttpRequest_Js();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.responseJS) {
				BannerId = req.responseJS.BannerId;
				BannerText = req.responseJS.BannerText;
				BannerType = req.responseJS.BannerType;
				if (typeof(BannerId) != 'undefined' && BannerId != 0 && BannerId != 40) {
					if (BannerType == 'script' && BannerText) {
						var iframe = new iFrame(container);
						iframe.style.width = '250px';
						iframe.style.height = '450px';
						BannerText = '<scr'+'ipt type="text/javascript">'+BannerText+'<\/scr'+'ipt>';
						iframe.doc.write(BannerText);
						iframe.doc.close();
						return true;
					} else {
						$('#' + ifolder_adv_container).append(BannerText);
					}
				} else {
					++iteration;
					if (iteration < ifolder_adv_iteration_limit) {
						print_ads(iteration, ifolder_adv_hash,
								ifolder_adv_container, use_middle_step, side,
								type);
					} else {
						print_partner(side, type, ifolder_adv_container,
								use_middle_step);
						return true;
					}
				}
			}
		}
	};
	
	var _login = ifolder_adv_hash[iteration].login;
	var _options = 'options=X';
	var _random = Math.round(Math.random() * 100000);
	var url = ifolder_adv_hash[iteration].url;
	var key = ifolder_adv_hash[iteration].key;
	var src = url + _login + '?' + _random + '&' + _options;
	req.caching = false;
	req.open('GET', src, true);
	var tt = Math.floor(Math.random() * (1000 - 0 + 1)) + 0;
	req.send({}, _random);
	
	return;
}


function print_partner_iframe(side, type, use_middle_step)
{
	if (use_middle_step == 'right_middle_step') {
		if (is_right_middle_step() == 'exists') {
			return false;
		}
	} else {
		if (use_middle_step == 'left_middle_step') {
			if (is_left_middle_step() == 'exists') {
				return false;
			}
		}
	}
	if (type == 'default')
	{
		var partner_code = ( side == 'left' ) ? 'partner_adv_left' : 'partner_adv_right';
		var BannerText = document.getElementById(partner_code).value;

		setTimeout(function(){ doc_write(BannerText, side, 120) }, 1000);
	}


	return false;
}

function print_partner(side, type, conteiner_id, use_middle_step){

	var container = document.getElementById(conteiner_id);

	var BannerText = '';

	if (use_middle_step == 'right_middle_step') {
		if (is_right_middle_step() == 'exists') {
			return false;
		}
	} else {
		if (use_middle_step == 'left_middle_step') {
			if (is_left_middle_step() == 'exists') {
				return false;
			}
		}
	}

	if (!container)
	{
		return false;
	}
	else
	{
		if (container.innerHTML == '' && type == 'default') {
				var partner_code = ( side == 'left' ) ? 'partner_adv_left' : 'partner_adv_right';
				var BannerText = document.getElementById(partner_code).value;
				//var BannerText = $('#' + partner_code).val();

//				alert('partner_code - '+partner_code+"\n\n"+BannerText);

				var iframe = new iFrame(container);

				iframe.style.width = '125px';
				iframe.style.height = '255px';
				iframe.doc.write(BannerText);

				iframe.doc.close();
		} else {
			return false;
		}
	}
	return;
}

function iFrame(parentElement) {

	var iframe = document.createElement('iframe');

	if (parentElement == null) {
		return false;
	}

	var id = 'fr_' + rand();

	iframe.name = id;
	iframe.scrolling = 'no';
	iframe.frameBorder = 'no';

	iframe.style.width = '1px';
	iframe.style.height = '1px';

	iframe.allowTransparency = "true";

	parentElement.appendChild(iframe);

	iframe.doc = null;

	if (iframe.contentDocument) {
		iframe.doc = iframe.contentDocument;
	} else {
		if (iframe.contentWindow) {
			iframe.doc = iframe.contentWindow.document;
		} else {
			if (iframe.document) {
				iframe.doc = iframe.document;
			}
		}
	}
	if (iframe.doc == null) {
		throw 'Document not found, append the parent element to the DOM before creating the IFrame';
	}

	iframe.doc.open();
	return iframe;
}

function rand() {
	return Math.ceil(10000 * Math.random());
}
