var initialTab = "";window.addEvent('domready', function(){	var i=0;	$$('a[rel=\'external\']').setProperty('target','_blank'); // Добавляем таргет всем ссылкам где стоит рел екстернал	if ($$('table tr')[0]) $$('table tr')[0].addClass('firsttr');	$$('table tr').each(function(element) { // Нечетным элементам таблиц добавляем класс		if (i++%2 == 0)		  {		  element.addClass('odd');		  }	});	init_vartags_parse('var');	init_tooltips($$('.tooltip'));    init_lightbox($$('.lightbox'));    if (function_exists('template_domready')) { template_domready(); }    if ($('CommentForm'))      {      $('CommentForm').addEvent('submit', function(e) {		e.stop();		var info = JSON.decode($('mid').innerHTML);		var log = $('CommentFormResult').empty().addClass('ajax-loading');		this.set('send', {url: '/ajax/addcomment.php?id='+info.id, evalScripts: true, onComplete: function(response) {			log.removeClass('ajax-loading');			log.set('html', response);		}});		this.send();	  });      }	if($('search')) // Если на странице есть форма поиска	  {	  $('search').addEvent('submit', function(event){ document.location = $('search').action+$$('form#search input[name="search"]')[0].value; return false; });	  }	init_ishuman($$('form'));	if ($('register'))	  {	  $('register').addEvent('submit', function(e) {		e.stop();		var log = $('rezultdiv').empty().addClass('ajax-loading');		this.set('send', {url: '/modules/users/ajax/register.php', evalScripts: true, onComplete: function(response) {			log.removeClass('ajax-loading');			log.set('html', response);		}});		this.send();	  });	  }	$$('#register input').addEvent('keydown', function(e) {		$(this.getProperty('id')+'_div').removeClass('formerr');	});	initStateFromURL();	setInterval(initStateFromURL, 1000);	//focus = new Element('input', {'id':'focus','type':'text'}); // Чтоб убирать фокус на этот элемент	//$$('body').adopt(focus);	fader = new Element('div', {'id':'fader'});	$$('body').adopt(fader);	fader.addEvent('click', function(e) {		showbox('hide');	});	lightbox = new Element('div', {'id':'lightbox'});	inlightbox = new Element('div', {'id':'inlightbox'});	headlightbox = new Element('div', {'id':'headlightbox'});	$$('body').adopt(lightbox.adopt(headlightbox));	$$('body').adopt(lightbox.adopt(inlightbox));	make_lightbox_draggable();	ajaxinit($$('a,form'));	find_selected();});function centerlightbox()  {  // Смещаем блок на половину чтоб отображался поцентру  $('lightbox').style.width = '';  $('lightbox').style.height = '';  lightboxSize = $('lightbox').getSize();  offsetX = Math.floor(lightboxSize.x/2);  $('lightbox').style.width = lightboxSize.x+'px';  $('lightbox').style.marginLeft = -offsetX+'px';  offsetY = Math.floor(lightboxSize.y/2);  $('lightbox').style.height = lightboxSize.y+'px';  $('lightbox').style.marginTop = -offsetY+'px';  }function init_lightbox(elems)  {  elems.each(function(element) {		element.addEvent('click', function(e) {			$('lightbox').className = (element.getProperty('id'))?element.getProperty('id'):''; // Если у ссылки есть id, то он становится классом лайтбокса			picregexp = /.+(\.png|\.jpg|\.jpeg|\.gif)/i;			if(picregexp.test(element.getProperty('href'))) // По этому регулярному выражению определяется картинка			  {			  image = new Element('img', {'src':element.getProperty('href')});			  $('inlightbox').empty();			  $('inlightbox').adopt(image);			  $('headlightbox').hide();			  image.addEvent('load', function(e) {			  		centerlightbox();			  	});			  }			else // Если мы загружаем в лайтбокс файл			  {			  $('inlightbox').empty();			  $('inlightbox').addClass('ajax-loading');			  $('headlightbox').set('text',' ');			  var myRequest = new Request({url: element.getProperty('href'), method: 'post', evalScripts: true, onSuccess: function(html) {    				$('inlightbox').removeClass('ajax-loading');    				$('inlightbox').set('html',html);    				centerlightbox();    				$$('#lightbox var').each(function(element) { // Обрабатываем полученные элементы var  			        var lightboxinfo = JSON.decode(element.innerHTML);				    if (lightboxinfo.title) // title		  		      {		  		      $('headlightbox').set('text',lightboxinfo.title);		  		      $('headlightbox').show();		  		      }  			  	    });  			  	    ajaxinit($$('#lightbox form'));		  		    init_ishuman($$('#lightbox form'));		  		    init_lightbox($$('#lightbox .lightbox'));  			    }}).send('ajax=1');			  }			showbox('show');			e.stop();		});	});  }function init_ishuman(elem) // Ставим всем формам невидимое поле для того чтобы потом скриптом проверять его наличие чтоб определять что это был человек а не бот  {  var inputElement;  elem.each(function(element) {  		inputElement = new Element('input', {id: 'ishuman', 'type':'hidden', 'name':'ishuman','value':'1'}); 		element.adopt(inputElement);	});  }function make_lightbox_draggable()  {  var myDrag = new Drag('lightbox', {  	handle: $('headlightbox'),    snap: 0,    onSnap: function(el){        el.addClass('dragging');    },    onComplete: function(el){        el.removeClass('dragging');    }  });  }function init_vartags_parse(tag)  {  $$(tag).each(function(element) { // Для всех элементов информации		var info = JSON.decode(element.innerHTML);		if (info.preload) // Предподгрузка картинок		  {		  if ($type(info.preload) == 'string')		    {		    preload(info.preload)		    }		  else if($type(info.preload) == 'array')		    {		    info.preload.each(function(element){		    	preload(element);		    	});		    }		  }		if (info.pagename !== false)		  {		  if ($('pagename'))		    {            if (!info.pagename)              {              $('pagename').addClass('displaynone');		      }		    else		      {		      $('pagename').removeClass('displaynone');		      info.pagename = info.pagename.replace(/\[a=([^\]]+)\]([^\[]+)?\[\/a\]/ig,'<a href="$1">$2</a>');		      info.pagename = info.pagename.replace(/\{quote\}/ig,'"');		      $('pagename').set('html',info.pagename);		      }		    }		  }		if (info.mname && info.id) // Если есть название модуля и id, то это страница просмотра материала		  {		  new Request({method: 'post', url: '/ajax/count.php'}).send('id='+info.id+'&mname='+info.mname);		  }		if (info.title)		  {		  document.title = info.title.replace(/\{quote\}/ig,'"');		  }	});  }function showbox(act)  {  if (act == 'show')    {    $('lightbox').style.visibility = 'visible';    $('lightbox').style.display = 'block';	$('fader').style.visibility = 'visible';    $('fader').style.display = 'block';    }  else    {    $('lightbox').style.visibility = 'hidden';    $('lightbox').style.display = 'none';	$('fader').style.visibility = 'hidden';    $('fader').style.display = 'none';    }  }function initStateFromURL() {		if (window.location.hash==initialTab) {      		 return; // Nothing's changed since last polled.     	}        regexp = /\/p([0-9]+)\/?/i; // По этому регулярному выражению определяется является ли строка партнерской ссылкой		if(regexp.test(window.location.hash)) // Обрабатываем партнера		  {		  var once;		  if (!once)		    {		    rez = regexp.exec(window.location.hash);    		window.location.hash = '';    		initialTab = window.location.hash;		    var myCookie = Cookie.write('partner', rez[1], {duration: 30}); // Ставим куку о том кто привел		    var myRequest = new Request({url: '/modules/partners/ajax/partners.php', method: 'post', evalScripts: true, onSuccess: function(responseText, responseXML) {		    	// Успешно посчитали    		}}).send('ref='+escape(document.referrer));		    once = 1;		    }	      }	    else	      {     	  var loadhref = '';		  initialTab = window.location.hash;		  for(i=1;i<initialTab.length;i++)	  	    {	  		loadhref += initialTab[i];	  	    }		  if (loadhref) ajaxload(loadhref);		  if (!loadhref) ajaxload('/',false,1); // Если перешли обратно на главную	      }   }function find_selected()  {  var findhref = initialTab;  if(!findhref) // Если зашли по прямой ссылке не используя ajax, то получаем путь    {    var myURI = new URI(document.location);    var findhref = myURI.get('directory');    }  var atags = $$('a');  var ini = findhref.replace(/\#/i,'').replace(/\/$/i,'');  atags.each( function(element) {    var href = (element.getProperty('href'))?element.getProperty('href').replace(/\/$/i,''):'';    if (href == ini)      {      element.addClass('selectedlink');      }    else      {      element.removeClass('selectedlink');      }  	});  }function ajaxinit(elems) { // Для всех elems ставим события чтобы они грузились через ajax	elems.each( function(element) {	if (element.getProperty('href')) // Для ссылок	  {		element.addEvent('click', function(e){			var href = element.getProperty('href');			if (href[0] == '/' && element.hasClass('ajax'))			  {			  ajaxload(href);			  //$('focus').focus();			  e.stop();			  }			else			  {			  return true;			  }		});	  }	else if (element.getProperty('action')) // Для форм	  {	  var action = element.getProperty('action');	  if (action[0] == '/' && element.hasClass('ajax')) // Если использует абсолютный путь и имеет класс ajax и не иммет события onSubmit		{		  element.addEvent('submit', function(e) {		  ajaxfield = new Element('input', {'name':'ajax','type':'hidden','value':'1'});	      $(element.getProperty('id')).adopt(ajaxfield);		  e.stop();		  var log = $(element.getProperty('id')).addClass('ajax-loading');		  if ($$('#lightbox #'+element.getProperty('id'))[0]) { $('lightbox').addClass('ajax-loading'); }  // Если форма находится внутри лайтбокса		  log.set('send', {url: action, method: 'post', evalScripts: true, onComplete: function(response) {					log.removeClass('ajax-loading');					$('lightbox').removeClass('ajax-loading');					log.set('html', response.replace(/<\/?form.+?>/i, ''));					init_ishuman($$('#'+element.getProperty('id')+' form'));					init_lightbox($$('#'+element.getProperty('id')+' .lightbox'));					}});		    log.send();	        });	    }	  }	});}function ajaxload(href,elemid,nohash) { // elemid - это куда грузиться	var elemid = (elemid)?elemid:'moduleinfo';  // если не указан elemid, то грузимся в moduleinfo	var sizes = $(elemid).getScrollSize();	var loading = $$('body').addClass('ajax-loading');	$(elemid).setProperty('style','height:'+sizes.y+'px;');	var container = $(elemid).empty();	var myRequest = new Request({url: href, method: 'post', evalScripts: true, onSuccess: function(responseText, responseXML) {    	container.innerHTML = responseText;    	loading.removeClass('ajax-loading');    	ajaxinit($$('#'+elemid+' a, #'+elemid+' form')); // Для загруженных элементов a и form    	init_tooltips($$('.tooltip'));    	init_vartags_parse('#'+elemid+' var');    	init_ishuman($$('#'+elemid+' form'));    	init_lightbox($$('#'+elemid+' .lightbox'));    	if (function_exists('template_domready')) { template_domready(elemid); }    	$(elemid).setProperty('style','height:auto;');    	if (!nohash)    	  {    	  initialTab = '#'+href;    	  window.location.hash = href;    	  }    	find_selected();    }}).send('ajax=1');}function make_error() {	this.length = arguments.length;  	for (var i = 0; i < this.length; i++)  	  {      $(arguments[i]+'_div').addClass('formerr');      }}function init_tooltips(elems)  {  toolTips = new Tips(elems);  }function preload(src)  {  var img = new Image();  img.src = src;  }function Poll_SetVote()  {  var myHTMLRequest = new Request.HTML({url:'/modules/poll/ajax/otvetil.php',  		onSuccess: function(html) {			$('pollresults').set('text', '');			$('pollresults').adopt(html);		}  }).post($('pollform'));  return false;  }function Poll_vote_rezults(obj)  {  var myHTMLRequest = new Request.HTML({url:'/modules/poll/ajax/otvetil.php',  		onSuccess: function(html) {			$('pollresults').set('text', '');			$('pollresults').adopt(html);		}  }).post($('pollform'));  return false;  }function Shop_update_cartprice(num)  {  new Request.HTML({url:'/modules/shop/ajax/cartprice.php',		onSuccess: function(html) {              $('cart_price').set('text', '');			  $('cart_price').adopt(html);		      var total_price = parseInt($('cart_price').innerHTML);		      if ($('skidkanum'))		        {		        var skidka = parseInt($('skidkanum').innerHTML);                $('cart_skidka_price').innerHTML = total_price-total_price*skidka/100;                }              $('cart_kolvo').innerHTML = num;		      $('cart_total_price').innerHTML = total_price;		}	,evalScripts: true}).get();  }function shop_addToCart (id){ // Добавление товара в корзину	var kolvo = $('_kolvo').value;	var size = $('_size').value;	if ($('size2') && !$('_size').value) // Если есть вторая ссылка для выбора размера и размер не выбран, то сообщение	  {	  alert('Выберите размер');	  return false;	  }	var loading = $('addbutton').value = 'Добавление...';	var container = $('addToCart_rez').addClass('ajax-loading');	loading.disabled = 'true';	var myRequest = new Request({url: '/modules/shop/ajax/to_cart.php', method: 'get', evalScripts: true, onSuccess: function(responseText, responseXML) {    	container.removeClass('ajax-loading');    }}).send('id='+id+'&kolvo='+kolvo+'&size='+size);    //$('focus').focus();}function shop_to_cart_rez(code,txt) { // Обработка результата добавления в корзину	var rezdiv = $('addToCart_rez').empty();	switch(code)	  {	  case 'netu':	     elem = new Element('div', {'class': 'bad'});	  	 rezdiv.adopt(elem.set('text',txt));	  break;	  case 'ok':	  	elem = new Element('div', {'class': 'good'});	  	rezdiv.adopt(elem.set('html',txt));	  break;	  }    ajaxinit($$('#addToCart_rez a'));}function shop_change_size(num,j)  {  $('_size').value = num;  for (var i=1;;i++)    {    if (!$('size'+i))      {      break;      }    $('size'+i).removeClass('sel_size_selected');    }  $('size'+j).addClass('sel_size_selected');  }var total_price;function shop_check_dostavka(sposob)  {  var sposoby = new Array();  if (!sposob) return;  if (!total_price)    {    total_price = parseInt($('koplate').innerHTML);    }   $$('var').each(function(element) { // Для всех элементов информации		info = JSON.decode(element.innerHTML);		if (info.sposobyoplaty)		  {		  sposoby['np'] = info.sposobyoplaty.np;		  sposoby['bank'] = info.sposobyoplaty.bank;		  sposoby['wm'] = info.sposobyoplaty.wm;		  }   });    sposobvalue = sposob;    if(/\%$/.test(sposoby[sposobvalue])) // Проверяем в процентах ли указан      {      izmenenie = Math.floor(parseInt(sposoby[sposobvalue])*total_price/100);      }    else      {      izmenenie = parseInt(sposoby[sposobvalue]);      }    if (izmenenie < 0) // Даем скидку      {      $('slovo_sposoba_oplaty').innerHTML = 'Скидка за предоплату';      $('koplate').innerHTML = total_price+izmenenie;      $('stoimost_dostavki').innerHTML = Math.abs (izmenenie);      }    else      {      $('slovo_sposoba_oplaty').innerHTML = 'Стоимость доставки';      $('koplate').innerHTML = total_price+izmenenie;      $('stoimost_dostavki').innerHTML = izmenenie;      }    $('stoimost_dostavki_div').style.display = 'block';    $(sposobvalue+'input').checked = true;  }function shop_last_step()  {  var i = $$('.inp_posob_oplati');  var sposob_oplati_vibran;  i.each(function(el) { if(el.checked) { sposob_oplati_vibran = 1; } });  if (!sposob_oplati_vibran)    {    alert('Необходимо выбрать способ оплаты');    err = 1;    }  else    {    err = 0;    }  if (!err)    {    $('last_step_form').submit();    }  return false;  }function shop_sel_country(){	$('region').disabled=true;	$('city').disabled=true;	new Request.HTML({url:'/modules/shop/ajax/sel_country.php?id_country='+$('country').value,		onSuccess: function(html) {              $('div_region').empty();			  $('div_region').adopt(html);		      shop_after_sel_country();		}	,evalScripts: true}).get();}function shop_after_sel_country(num){	if($('xer_region').value==1){		shop_sel_region();	}else{		$('div_city').innerHTML='<select style="width:180px;" id="city" name="city"><option value="0">Выберите регион</option></select>';		$('city').disabled=true;	}}function shop_sel_region(){	if($('region').value==-1){		if(!$('other_region')){			$('div_region').innerHTML+='<div id="other_region"><input class="inp" type="text" style="width:180px;" name="other_region" value=""></div>';		}		$('region').value=-1;	}else{		if($('other_region'))$('div_region').removeChild($('other_region'));	}	if($('region').value!=0){		$('city').disabled=true;		new Request({url:'/modules/shop/ajax/sel_region.php?id_country='+$('country').value+'&id_region='+$('region').value,		 onSuccess: function(responseText, responseXML) {              $('div_city').empty();			  $('div_city').innerHTML = responseText;		      shop_after_sel_region();		}	,evalScripts: true}).get();	}else{		$('div_city').innerHTML='<select style="width:180px;" id="city" name="city"><option value="0">Выберите регион</option></select>';		$('city').disabled=true;	}}function shop_after_sel_region(){}function shop_delFromCart(id,size) // Удаление товара из корзины  {  if (confirm('Убрать товар из корзины?'))    {    new Fx.Morph('cart_item'+id+size, {duration: 300, transition: Fx.Transitions.Sine.easeOut }).start({'opacity': 0}).chain(  	  function() { this.set({'display': 'none'}); }  	);    new Request.HTML({url:'/modules/shop/ajax/delcartitem.php',evalScripts: true}).get({'id': id,'size': size});    }  return false;  }function shop_update_cart()  {  ajaxload('/modules/shop/ajax/update_ajaxcart.php','korzina',1);  }function shop_sel_city(){	if($('city').value==-1){		if(!$('other_city')){			$('div_city').innerHTML+='<div id="other_city" ><input class="inp" type="text" style="width:180px;" name="other_city" value=""></div>';		}		$('city').value=-1;	}else{		if($('other_city'))$('div_city').removeChild($('other_city'));	}}function shop_full_form_check()  {  var i = $$('.inp_posob_oplati');  var sposob_oplati_vibran;  i.each(function(el) { if(el.checked) { sposob_oplati_vibran = 1; } });  if (!sposob_oplati_vibran)    {    alert('Необходимо выбрать способ оплаты');    err = 1;    }  else    {    err = 0;    if (!$('country').value)      {      alert('Необходимо выбрать страну');      err = 1;      }    else      {      err = 0;      if (!$('region').value && !$('other_region').value)        {        alert('Необходимо указать регион');        err = 1;        }      else        {        err = 0;        if (!$('city').value && !$('city').value)          {          alert('Необходимо указать город');          err = 1;          }        else          {          err = 0;          }        }      }    }  if (!err)    {    $('last_step_form').submit();    }  return false;  }function users_login()  {  $('loginform').submit();  }function users_update_userbar()  {  ajaxload('/modules/users/ajax/update_userbar.php','userbar',1);  showbox('hide')  }function addmark(mark)  {  toolTips.hide();  info = JSON.decode($$('var')[0].innerHTML.toString());  $('rateinfo').empty();  var loading = $('ratingdiv').addClass('ajax-loading');  var myRequest = new Request({url: '/ajax/vote.php', method: 'post', evalScripts: true, onSuccess: function(responseText, responseXML) {    	loading.removeClass('ajax-loading');  }}).send('id='+info['id']+'&mark='+parseInt(mark));  }function redirect(url)  {  var myRequest = new Request({url: '/ajax/redirect.php', method: 'post', evalScripts: true, onSuccess: function(responseText, responseXML) {  }}).send('path='+url);  }function function_exists (function_name) {    if (typeof function_name == 'string'){        return (typeof this.window[function_name] == 'function');    } else{        return (function_name instanceof Function);    }}