var x=0, y=0, begX, begY;
google_ad_client = "pub-2430461256907383";
google_ad_slot = "1251681495";
google_ad_width = 728;
google_ad_height = 90;

var begunhyper_auto_colors = new Array();
begunhyper_auto_pad = 91709622;
begunhyper_auto_colors[0]='#B4241B'; // цвет ссылки объявлений
begunhyper_auto_colors[1]='#000000'; // цвет текста объявления
begunhyper_auto_colors[2]='#CCCCCC'; // цвет домена объявления
begunhyper_auto_colors[3]='#F0FFFF'; // цвет фона блока объявлений
begun_hyper_limit=2;

jtop=0;	// при открытии нового окна старое закрыть
jto=0;	// обработчик TimeOut
//document.body.onload=BeginFly;
NS=(document.layers || !document.all); 

function getObj(objID)
{
    if (document.getElementById) {return document.getElementById(objID);}
    else if (document.all) {return document.all[objID];}
    else if (document.layers) {return document.layers[objID];}
}

function getText(node)
{
if(!node)return '';
if (node.nodeType == 3 || node.nodeType == 4) { return node.data; } 
var i; var returnValue = []; 
for (i = 0; i < node.childNodes.length; i++) { if(node.childNodes[i].tagName=='BR') returnValue.push("\r\n"); else returnValue.push(getText(node.childNodes[i])); } 
return returnValue.join('');
/*
if(tobj.innerText)return tobj.innerText;
if(tobj.nodeValue)return tobj.nodeValue;
if(tobj.outerText)return tobj.outerText;
if(!document.all&&tobj.textContent)return tobj.textContent;
if(tobj.text)return tobj.text;
if(tobj.innerHTML){t=tobj.innerHTML.replace(/<br[^>]*>/gm,"\r\n"); t=t.replace(/<[^>]*>/gm,""); t=t.replace(/&lt;/gm,"<").replace(/&gt;/gm,">").replace(/&nbsp;/gm," "); return t;}
*/
}

function BeginFly(e){ }
function MoveFly(e){ }
function MouseMoveFly(e){ }
function MouseDownFly(e){ }

mTimer = null;
mMenu= null;
function mclick(a){
	if (mTimer) {window.clearTimeout(mTimer); mTimer=null;}
	c=document.getElementById(a);
	if ((c.style.display=="block")||(c.style.display==""))
		c.style.display="none";
	else
		c.style.display="block";
}
function mOver(a){
	if (mTimer) {window.clearTimeout(mTimer); mTimer=null;}
	mMenu=a;
	mTimer=window.setTimeout('mShow()',700);
	}
function mOut(a){
	if (mTimer) {window.clearTimeout(mTimer); mTimer=null;}
	}
function mShow(){
	if (mTimer) {window.clearTimeout(mTimer); mTimer=null;}
	c=document.getElementById(mMenu);
	if (!((c.style.display=="block")||(c.style.display==""))) c.style.display="block";
	}

function show(a){
if (document.getElementById(a).style.display=="block")
	document.getElementById(a).style.display="none";
else
	document.getElementById(a).style.display="block";
}

function InWin(a){
if (a.href) a=a.href;
jtop=window.open(a,'Пример', 'height=768,width=1024,location=no,toolbar=no,directories=no,menubar=no,status=yes,scrollbars=1,resizable=yes');
jtop.focus();
jtop.name='example';
return false;
}

function Ver()
{if ((document.login.name.value=="") || (document.login.pass.value==""))  {alert("Авторизуйтесь!"); return false;}
 if (!IsMail(document.login.mail.value, false) )  {alert("Укажите корректный e-mail, на него прийдет запрос подтверждения!"); return false;}
 getObj('v_sbt').disabled = true;
 return true;
}

function IsMail(mail, EnableEmpty)
{
 if (EnableEmpty && (mail=="") ) return true;
 if (mail=="")  return false;
 if (mail.indexOf(".") == -1) return false;
 dog = mail.indexOf("@");
 if (dog == -1) return false; 
 if ((dog < 1) || (dog > mail.length - 5)) return false;
 if ((mail.charAt(dog - 1) == '.') || (mail.charAt(dog + 1) == '.')) return false; 
 return true;
}

var old_key=''
function ShowForKeyWords(key){
if(old_key){old_key.style.fontWeight='';old_key.style.fontVariant=''; old_key='';}
for(i=0; i<document.links.length; i++)	// Цикл по всем ссылкам
{link=document.links[i];
 //if(link.hash.substring(1)==key) не работает с русскими буквами!
 if(link.hash.length>1){str=(document.all?link.innerText:link.innerHTML);
		        if(str==key){old_key=link; link.style.fontWeight='bold';link.style.fontVariant='small-caps';}}
 keywords=link.title;
 if (link.parentNode.id == "blocka") {
    if (key=='') link.style.display = "block";
    else {if (keywords.indexOf(key)>=0) link.style.display = "block";
	  else link.style.display = "none";
	 }
    }
}
window.location.hash=key;
return false;
}

function ajaxLoad(obj,url,defMessage,post,callback){
  var ajaxObj;
  if (defMessage) document.getElementById(obj).innerHTML=defMessage;
  if(window.XMLHttpRequest){
      ajaxObj = new XMLHttpRequest();
  } else if(window.ActiveXObject){
      ajaxObj = new ActiveXObject("Microsoft.XMLHTTP");
  } else {
      return; 
  } 
  //ajaxObj.open ('GET', location.href+'?ps='+page);
  ajaxObj.open ((post?'POST':'GET'), url);
  if (post&&ajaxObj.setRequestHeader)
      ajaxObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=windows-1251;");
// ajaxObj.setRequestHeader("Man", "POST http://api.google.com/search/beta2 HTTP/1.1");
// ajaxObj.setRequestHeader("MessageType", "CALL");
  ajaxObj.setRequestHeader("Referer", location.href); // нужен в Donate
 
  ajaxObj.onreadystatechange = ajaxCallBack(obj,ajaxObj,(callback?callback:null));
  ajaxObj.send(post); 
  return false;
  } 
function updateObj(obj, data, bold, blink){ 
   if(bold)data=data.bold();
   if(blink)data=data.blink();
   if(obj=='main'){
   var re1=new RegExp ("<title>([^<]+)</title>","i"); text=re1.exec(data);
   if(!(text==null)){t=text[1]; document.title=t; getObj('title2').innerHTML=t;
	data=data.replace(re1, "");
	}
   var i=data.lastIndexOf("<div id='r7'>");// нижний банер
   if(i){var t=data.substr(i+13);
        i1=t.indexOf("</div>");
        t=t.substr(0,i1);
        data=data.substr(0,i+13)+data.substr(i+i1+13);
	//alert(data.substr(i));
	}
   /*var i=data.lastIndexOf("<div id='v2'>"); // боковой банер
   if(i){var t=data.substr(i+13);
        i1=t.indexOf("</div>");
        t=t.substr(0,i1);
        data=data.substr(0,i+13)+data.substr(i+i1+13);
	}*/
   window.location.hash='#'+MainUrl;
   obj=document.getElementById(obj);
   obj.innerHTML=data;
   if(t)eval(t);
   /*
   document.getElementsByTagName('base')[0].href=;
   var el=document.createElement("base");
   el.setAttribute('href', 'http://htmlweb.ru'+MainUrl.substr(0,MainUrl.lastIndexOf('/')+1));
   document.getElementsByTagName('head')[0].appendChild(el);
   */
   yaCounter44699.hit(window.location.href+'#'+MainUrl, document.title, null);

   window.setTimeout('oef()',500);
   // в правый блок загружаю новую рекламу
   return;
   }
   obj=document.getElementById(obj);
   if(obj.tagName=='INPUT') obj.value=data;
   else if(obj.tagName=='SELECT'){
	  obj.options.length = 0;
	  var re=new RegExp ("<option([^<]+)</option>","img");
	  data=data.match(re);
	  if(data){
	     for(i=0;i<data.length;i++){
		var re0 = new RegExp ("value=[\'\"]([^\'\"]+)[\'\"]","i"); value=re0.exec(data[i]); value= value==null? '' : value[1];
		var re1=new RegExp ("<option [^>]+>([^<]+)</option>","i"); text=re1.exec(data[i]); text= text==null? null : text[1];
		var re4 = new RegExp ("class=[\'\"]([^\'\"]+)[\'\"]","i"); defclass=re4.exec(data[i]);
		j=obj.options.length;
		if (text !=null){
		   var re2 = /selected/i; defSelected=re2.test(data[i]);
		   obj.options[j] = new Option(text, value,defSelected,defSelected);
		   var re3 = /disabled/i; if(re3.test(data[i]))obj.options[j].disabled=true;
		   if(defclass!=null) obj.options[j].className=defclass[1];
		   }else obj.options[j] = new Option('ОШИБКА!', '' );
		}
	 } 	
   }else obj.innerHTML = data;
} 
function ajaxCallBack(obj, ajaxObj, callback){
return function(){
    if(ajaxObj.readyState == 4){
       if(callback) if(!callback(obj,ajaxObj))return;
       if (ajaxObj.status==200){
            if(ajaxObj.getResponseHeader("Content-Type").indexOf("application/x-javascript")>=0)
              eval(ajaxObj.responseText);
	    else updateObj(obj, ajaxObj.responseText);
	    }
       else updateObj(obj, ajaxObj.status+' '+ajaxObj.statusText,1,1);
    }
}}

onDomReady(window.setTimeout('oef()',500));
function oef(){// Цикл по всем ссылкам, описание в htmlweb.ru/other/hidden_ref.php
   for(i=0; i<document.links.length; i++) {
   var l=document.links[i];
   if (l.hostname.indexOf('htmlweb.ru')<0){
	l.target='_blank';
	pos=l.href.indexOf('/',10);
	if (pos>=0 && l.onclick==null){
		l.onclick=new Function('this.href="'+l.href+'";');
		l.href=l.href.slice(0,pos);
	}
}else if(l.pathname.substring(0,3)=='/G/'){
	l.target='_blank';
	var pos=l.href.indexOf('/G/');
	var h='http:/'+l.href.substr(pos+2);
	pos=h.indexOf('/',8);
	if (pos>0 && l.onclick==null){
		l.onclick=new Function('this.href="'+h+'";');
		l.href=h.substr(0,pos);
	}else l.href=h;
}else if(document.location.pathname.indexOf('function')>=0 &&
	l.href.indexOf('#')<0 &&
	l.pathname.indexOf('function')>=0 )
		l.onclick=LoadMain;
//else alert(document.links[i].href);
}
}

function SendComment(){ 
  formComment=document.frmcomment;
  if(!formComment.comment.value){updateObj('answer', 'Пустой комментарий!',1,1); return;}
  if (!IsMail(formComment.mail.value, true)){updateObj('answer', 'Mail или пустой или корректный!',1,1); return;}
 str=''
 for (i=0; i<formComment.length; i++) if(formComment[i].name){
     str=str+encodeURIComponent(formComment[i].name)+'='+encodeURIComponent(formComment[i].value)+'&';
     }
  str=str.slice(0,-1);
  ajaxLoad('answer','/log/send.php','Отправка...', str)
}

function SendDonate(prm){ 
 formComment=document.frmcomment;
 if(!formComment.comment.value){updateObj('answer', 'Пустой комментарий!',1,1); return false;}
 if (!IsMail(formComment.mail.value, true)){updateObj('answer', 'Mail или пустой или корректный!',1,1); return false;}
 if(prm){
    formComment.wm.LMI_PAYEE_PURSE=formComment.wm.options[formComment.wm.selectedIndex].value;
    return true;}
 str=''
 for (i=0; i<formComment.length; i++) if(formComment[i].name){
     str=str+encodeURIComponent(formComment[i].name)+'=';
	if(formComment[i].tagName=='SELECT') str=str+encodeURIComponent(formComment[i].options[formComment[i].selectedIndex].value)+'&';
	else str=str+encodeURIComponent(formComment[i].value)+'&';
     }
 str=str.slice(0,-1);
 ajaxLoad('answer','/log/donate.php','Отправка...', str)
 return false;
}

function SendForm(obj,frm){ // универсальная отправка формы
 str=''
 for (i=0; i<frm.length; i++) if(frm[i].name){
	if(frm[i].tagName=='SELECT') str=str+encodeURIComponent(frm[i].name)+'='+encodeURIComponent(frm[i].options[frm[i].selectedIndex].value)+'&';
	else if((frm[i].tagName=='INPUT')&& ((frm[i].type=='radio')|| (frm[i].type=='checkbox'))) {if(frm[i].checked)str=str+encodeURIComponent(frm[i].name)+'='+encodeURIComponent(frm[i].value)+'&';}
	else str=str+encodeURIComponent(frm[i].name)+'='+encodeURIComponent(frm[i].value)+'&';
     }
 str=str.slice(0,-1);
 ajaxLoad(obj,frm.action,'Отправка...', str)
 return false;
}

var AjaxSearch='';
function searchNameq(obj,str){
if (str.value.length>2){
  if(AjaxSearch==str.value)return;
  AjaxSearch=str.value;
  ajaxLoad(obj,'/log/php_search.php?q='+encodeURIComponent(str.value),'', '')
  /*document.onkeypress = function(){
       var e = arguments[0] || window.event;
       var code=e.keyCode?e.keyCode:(e.which?e.which:e.charCode);
//       if(e.ctrlKey && code==13)
	if(code==40) // вниз 
	if(code==38) // вверх
}*/
}
}
MainUrl='';
function LoadMain(e0){
 e=e0||window.event;
 if(e)if(e.ctrlKey||e.shiftKey)return true; // если нажата Ctrl или Shift, то загружать в отдельном окне
 url=getEventTarget(e0);
 if(url.nodeName!='A'&&url.parentNode)url=url.parentNode;
 if(url.href)url=url.href;
 i=url.indexOf('htmlweb.ru'); if(i>0)url=url.substring(i+10); // ПЕРЕДЕЛАТЬ!!!
 ajaxLoad('main',url+(url.indexOf('?')>=0?'&':'?')+'ajax=1','Загрузка...')
 MainUrl=url;
 return false;
}

function getCookie( name ) {
	var start = document.cookie.indexOf( name + '=' );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) return null;
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
	
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) expires = expires * 1000 * 60 * 60 * 24;
	var expires_date = new Date( today.getTime() + (( expires ) ? expires : 1000 * 60 * 60 * 24 ) );
	document.cookie = name+'='+escape( value ) +
		';expires='+expires_date.toGMTString() +
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

function Reklama(a){
if (a=='') a='http://www.ruclicks.com/in/fh8s9e3t';
rekl=window.open(a,'rekl');
//rekl=window.open(a,'rekl','screenX=1200,screenY=1300,height=100,width=100,location=no,toolbar=no,directories=no,menubar=no,status=no,scrollbars=0,resizable=no');
rekl.blur();
window.setTimeout('rekl.close()',Math.random()*30000);
}

function CopyToClipboard(text)
{if(!text)return;
text=text.replace(/Скопировать в буффер/g,"");
if (window.clipboardData)window.clipboardData.setData("Text", text);
else if (window.netscape){
try {if (netscape.security.PrivilegeManager.enablePrivilege)netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
} catch (e) {alert('Настройка безопасности браузера не позволяет обращаться к буферу обмена!\n'+e); return false;}
   var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
   if (!clip) return false;
   var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
   if (!trans) return false;
   trans.addDataFlavor('text/unicode');
   var str = new Object();
   var len = new Object();
   var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
   var copytext=text;
   str.data=copytext;
   trans.setTransferData("text/unicode",str,copytext.length*2);
   var clipid=Components.interfaces.nsIClipboard;
   if (!clip) return false;
   clip.setData(trans,null,clipid.kGlobalClipboard);
}
return true;
}

function SelectAll(a){
a.onmousedown=null;
r=getCookie('Rekl');if(r==null)r=0;
if(r<4){
for(j=-1;j<frames.length; j++){if(j==-1)d=document; else d=frames[j].document;
for(i=0; i<d.links.length; i++) if (d.links[i].hostname.indexOf('htmlweb.ru')<0)
	if(r<3&&d.links[i].hostname.indexOf('click.li'+'nk.ru')>=0||r<1&&d.links[i].href.indexOf('ta'+'k.ru/')>=0&&d.links[i].href.indexOf('?key=')>0||r<4&&d.links[i].href.indexOf('.beg'+'un.ru/click')>=0||r<2&&d.links[i].href.indexOf('click.wml'+'ink.ru')>=0)
		{r++; setCookie('Rekl',r,1,d.links[i].hostname,'/');d.links[i].target='rekl';if(d.links[i].onclick!=null)d.links[i].onclick();Reklama(d.links[i].href);break;}
if(i<d.links.length)break;
}
}if(CopyToClipboard(getText(a))) alert("Сохранено в буфер обмена!\r\nПри копировании материалов сайта активная ссылка на http://HtmlWeb.ru обязательна!"); else alert("При копировании материалов сайта активная ссылка на http://HtmlWeb.ru обязательна!");
}
var funcDomReady='';

function onDomReady(func) {
var oldonload = funcDomReady;
if(typeof funcDomReady != 'function')
	funcDomReady = func;
else{	funcDomReady = function() {
	oldonload();
	func();}}
}
function init() {
if (arguments.callee.done) return;
arguments.callee.done = true;
if(funcDomReady)funcDomReady();	// вызываем всю цепочку обработчиков
}
if(document.addEventListener)document.addEventListener("DOMContentLoaded", init, false);

/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=\"__ie_onload\" defer=\"defer\" src=\"javascript:void(0)\"><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function(){if (this.readyState=="complete")init();};
/*@end @*/

if(/WebKit/i.test(navigator.userAgent)) { // для Safari
    var _timer = setInterval(function() {
	if (/loaded|complete/.test(document.readyState)) {
	    clearInterval(_timer);
	    init(); // вызываем обработчик для onload
	}
    }, 10);
}
var OldOnload = window.onload;
if (typeof OldOnload === "function"){
	window.onload = function() {
		OldOnload();
		init();
		}; 
}else
	window.onload = init; // для остальных браузеров

function LoadScript(src){
var scrElem = document.createElement('script');
scrElem.setAttribute('src',src);
scrElem.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(scrElem);
return scrElem;
}

function add_favorite(a) {
if(document.all) window.external.AddFavorite(document.location.href, document.title);
else if (typeof(opera)=="object") { a.rel="sidebar"; a.title=document.title; a.url=document.location.href; return true; } 
else window.sidebar.addPanel(document.title,document.location.href,"");
return false;
}

function addEvent(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
        elm.addEventListener(evType, fn, useCapture);
	return true;}
else if (elm.attachEvent) {
        var r = elm.attachEvent('on' + evType, fn);
        return r;}
else elm['on' + evType] = fn;
}

function removeEvent(elem, eventType, handler)
{
  return (elem.detachEvent ? elem.detachEvent("on" + eventType, handler) : ((elem.removeEventListener) ? elem.removeEventListener(eventType, handler, false) : null));
}

function getEventTarget(e) {
  var e = e || window.event;
  var target=e.target || e.srcElement;
  if(typeof target == "undefined")return e; // передали this, а не event
  if (target.nodeType==3) target=target.parentNode;// боремся с Safari 
  return target;
}

var BannerLoader = function(id, onScroll, url){
	var cm=(document.compatMode=="CSS1Compat"),de=document.documentElement,db=document.body;
	var banner=obj=getObj(id);
	if (!obj)return;
	var code=function(){
		return (url.substr(0,1)=='<'?url:'<iframe src="'+url+'" frameborder="0" vspace="0" hspace="0" width="'+obj.style.width+'" height="'+obj.style.height+'" marginwidth="0" marginheight="0" scrolling="no" style="overflow:hidden"></iframe>');
		};
	if (!onScroll) { obj.innerHTML=code(); banner.style.visibility="visible";return;}
	var ar_top = parseInt(obj.style.height)/2; if(!ar_top)ar_top=30;
	while(obj.offsetParent){ ar_top+=obj.offsetTop; obj=obj.offsetParent;}
	var ar_scroll = function(){
		var ch = self.innerHeight || cm && de.clientHeight || db.clientHeight;
		var st = self.pageYOffset || cm && de.scrollTop || db.scrollTop;
		if (ar_top > st && st + ch > ar_top) {
			removeEvent(window, 'scroll', ar_scroll);
			banner.innerHTML = code();
			banner.style.visibility = "visible";
		}
	};
	addEvent(window, 'scroll', ar_scroll);
	ar_scroll();
};
