//js
var ajaxcounter = 0;
var nitemphotoa='';
var noshowimcenter=0;
var imgcount=0;
var reviewcount=0;
var nInterval = 0;
var bAcceptBg = false;
var searchTimeOut = null;
var umTimeOut = null;
var subTimeOut = null;
var sameTimeOut = null;
var parTimeOut = null;
var zamacta = null;
var alrgetparam = null;
nMenuYPos = 0;
nYDelta = 0;
nPrevScrollPos = 0;
nCurrentBlId = 7;
sDisableSearch = '';
nJabberUser = 0;
var browser = new Browser();
var gotolink = '';
oldstatus = 0;

nCurrentRubId = 0;
sCurrentRub = '';
nCurrentTagId = 0;
sCurrentTag = '';

vldnotb = 1;

SmthChangedInForms = new Array();

function SfindObj(n, d) 
{	//v4.01
	var p, i, x;
	if (!d) d = window.document; 
	if ((p = n.indexOf("?") ) > 0 && parent.frames.length) 
	{
		d = parent.frames [n.substring(p + 1)].document; 
		n = n.substring(0, p);
	}
	if (!(x = d [n]) && d.all) 
		x = d.all [n]; 

	for (i = 0; !x && d.forms && i < d.forms.length; i ++) 
		x = d.forms [i] [n];

	for (i = 0; !x && d.layers && i < d.layers.length; i ++)
		x = SfindObj(n, d.layers [i].document);
	if(!x && d.getElementById) 
		x = d.getElementById(n);
	return x;
}

function showtab(page)
{
	var spage = 'indextab1bm'+page;
	for (var i = 0; i < zakl.length; i++)
	{
		obj=SfindObj(zakl[i]);
		if(spage == zakl[i])
		{
			obj.style.visibility = 'hidden';
			obj.style.position = 'absolute';
		}
		else
		{
			obj.style.visibility = 'visible';
			obj.style.position = 'static';
		}
	}
	obj=SfindObj('indextabcontent');
	obj1=SfindObj('indextab'+page+'content');
	obj.innerHTML = obj1.innerHTML;
	return false;
} 

function ShowProd (wwidth,wheight,isrc,modelid) {
	if(isrc=='/') return;
	
	obj1=SfindObj('preview');
	obj2=SfindObj('previewimg');
	obj3=SfindObj('previewtbl');
	obj4=SfindObj('loading');
	
	//if (modelid >=0 ) {
		objLoad=SfindObj("loaddata");
		objLoad.innerHTML=modelid + '&nbsp;';
		//objLoad.style.display='none';
	//}
	
	obj2.src='/i/dot.gif';
	wheight = wheight*1+20;
	obj1.style.width=wwidth+'px';
	obj1.style.height=wheight+'px';
	
	obj3.style.width=wwidth+'px';
	obj3.style.height=wheight+'px';
	
	obj4.style.width=wwidth+'px';
	obj4.style.height=wheight+'px';

	CenterLayer('preview',wwidth,wheight,window.document);
	obj1.style.visibility='visible';

	obj2.src=isrc;

	CheckScrollers ();
}

function HideProd () {
	obj1=SfindObj('preview');
	obj2=SfindObj('previewimg');
	objLoad=SfindObj("loaddata");
	objLoad.innerHTML='';
	obj2.src='/i/dot.gif';
	obj1.style.visibility='hidden';
	
	CheckScrollers ();
}


function CenterLayer (layer,width,height,target,xoffset,yoffset) {
	if (!target)
		target=window.document;
	
	if(vldnotb)
	{
		LeftX = parseInt(GetCookie('coords_'+layer+'_x'));
		LeftY = parseInt(GetCookie('coords_'+layer+'_y'));
	}
	else LeftX = LeftY = 0;
	
	topLayer=parseInt(target.body.scrollTop);

	if ((LeftX+width) > target.body.clientWidth)
		LeftX = 0;

	if ((LeftY+height) > target.body.clientHeight)
		LeftY = 0;

	if ((LeftX > 0) && (LeftY > 0)) {
		target.getElementById(layer).style.left = LeftX+'px';
		target.getElementById(layer).style.top = LeftY+topLayer+'px';
	}
	else {
		if (!xoffset)
			xoffset = 0;
			
		if (!yoffset)
			yoffset = 0;
	
		leftLayer = ((target.body.clientWidth - width)/2);
		topLayerABS = (target.body.clientHeight - height)/2;
		
		newTop = topLayer + topLayerABS;
		if (newTop < 0)
			newTop=0;
			
		nTop = topLayer + topLayerABS + yoffset;
		nLeft = leftLayer + xoffset;
		
		if (nTop < target.body.scrollTop)
			nTop = target.body.scrollTop + 5;
		
		target.getElementById(layer).style.left = nLeft + 'px';
		target.getElementById(layer).style.top= nTop + 'px';
	}
}

function ShowOrHide (sObject) {
	obj = SfindObj(sObject);
	if (obj) {
		if (obj.style.display != 'block')
			obj.style.display = 'block';
		else
			obj.style.display = 'none';
	}
}

function ShowOrHideV (sObject) {
	obj = SfindObj(sObject);
	
	if (obj) {
		if (obj.style.visibility != 'hidden')
			obj.style.visibility = 'hidden';
		else
			obj.style.visibility = 'visible';
	}
}

function Hide (sObject) {
	obj = SfindObj(sObject);
	if (obj)
		obj.style.display = 'none';
}

function HideClear (sObject) {
	obj = SfindObj(sObject);
	if (obj) {
		obj.innerHTML = '';
		obj.style.visibility = '';
		obj.style.left = '-5000px';
		obj.style.top = '-5000px';
	}
	CheckScrollers ();
	
	if (sObject == 'ajax2')
		HideClear('ajax2_1');
}

function ShowTitleSelector (nRubricId) {
	aThisRubricTitles = aRubricsAndTitles[nRubricId];
	if (aThisRubricTitles.length)
		window.document.forms['formitem'].titleid.disabled = false;
	else
		window.document.forms['formitem'].titleid.disabled = true;

	window.document.forms['formitem'].titleid.options.length = 0;
	for (i = 1; i <= aThisRubricTitles.length; i++) {
		if (aThisRubricTitles[i])
			window.document.forms['formitem'].titleid.options[i] = new Option (aThisRubricTitles[i],aThisRubricTitles[i]);
	}
	
	aThisRubricBrands = aRubricsAndBrands[nRubricId];
	aThisRubricBrandsId = aRubricsAndBrandsId[nRubricId];
	if (aThisRubricBrands.length)
		window.document.forms['formitem'].manufacturerid.disabled = false;
	else
		window.document.forms['formitem'].manufacturerid.disabled = true;

	window.document.forms['formitem'].manufacturerid.options.length = 0;
	for (i = 1; i <= aThisRubricBrands.length; i++) {
		if (aThisRubricBrands[i])
			window.document.forms['formitem'].manufacturerid.options[i] = new Option (aThisRubricBrands[i],aThisRubricBrandsId[i]);
	}
	
	
	
}

function SwitchBookMark(sObjectName,nToSet,nLength) {
	for (i = 1; i <= nLength; i++) {
		obj = SfindObj(sObjectName + i);
		if (obj) {
			obj.style.visibility='hidden';
			obj.style.position='absolute';
		}
		
		obj = SfindObj(sObjectName + 'a' + i);
		if (obj)
			obj.className = 'bmna';
	}
	obj = SfindObj(sObjectName + nToSet);
	if (obj) {
		obj.style.visibility='visible';
		obj.style.position='static';
		obj.style.display = 'block';
	}
	
	obj = SfindObj(sObjectName + 'a' + nToSet);
	if (obj)
		obj.className = 'bma';
}

function ActivateBookMark(sObjectName,nLength) {
	for (i = 1; i <= nLength; i++) {
		obj = SfindObj(sObjectName + i);
		if (obj)
			obj.style.display='block';
	}
	obj = SfindObj('itemform8');
	obj.style.display = 'none';
}

function CreateImageBrowse (imglstobj) {
	place = document.getElementById(imglstobj);
	
	div = document.createElement("div");
	div.setAttribute('id', 'imgbrowsediv_'+imgcount);
	place.appendChild(div);
	
	browse = document.createElement("input");
	browse.setAttribute("type", "file");
	browse.setAttribute("name", "img_"+imgcount);
	browse.className = "file";
	
	httpbrowse = document.createElement("input");
	httpbrowse.setAttribute("type", "text");
	httpbrowse.setAttribute("name", "httpimg_"+imgcount);
	
	comment = document.createElement("input");
	comment.setAttribute("type", "text");
	comment.setAttribute("name", "comment_"+imgcount);
	
	num = document.createElement("div");
	num.setAttribute("className", "imglistnum");
	num.innerHTML = (imgcount+1) + '.';

	div.appendChild(num);
	div.appendChild(browse);
	div.appendChild(httpbrowse);
	div.appendChild(comment);
	
	browse.focus();
	imgcount++;
}

numinvite = 4;
function InviteAdd () {
	place = document.getElementById('invite');
	
	div = document.createElement("div");
	div.style.marginBottom='5px';
	place.appendChild(div);
	
	uname=document.createElement("input");
	uname.setAttribute("class", "linput");
	uname.setAttribute("name", "name["+numinvite+"]");
	div.appendChild(uname);

	uemail=document.createElement("input");
	uemail.setAttribute("class", "linput");
	uemail.setAttribute("name", "email["+numinvite+"]");
	div.appendChild(uemail);
	numinvite++;
}

function CreateReviewInput (imglstobj) {

	var a = document.getElementsByTagName("div");
	j=1;
	for(i=0; i < a.length; i++) {
		if(a[i].className && a[i].className.indexOf("reviewinput") != -1)
			j++;
   }
   if (j > 5)
   	return;
	
	place = document.getElementById(imglstobj);
	
	div = document.createElement("div");
	div.setAttribute('id', 'reviewdiv_'+reviewcount);
	place.appendChild(div);
	
	comment = document.createElement("input");
	comment.setAttribute("name", "review_"+reviewcount);
	comment.className = "vlinput";
	comment.setAttribute("class", "vlinput");

	div.appendChild(comment);
	
	comment.focus();
	reviewcount++;
}


function IsSpaces (sStr) {
	sStr = "" + sStr;
	for (i = 0; i < sStr.length; i ++)
		if (sStr.substring (i, i + 1) != " ")
			return false;
	return true;
}

function WithNumbers (sStr) {
	sStr = '' + sStr;
	for (i = 0; i < sStr.length; i ++)
	{
		ch = sStr.substring (i, i + 1); 
		if (ch >= '0' && ch <= '9')
			return true;
	}
	return false;
}

function msg(msg,title,func)
{
	html = '<table border=0 cellpadding=0 cellspacing=0><tr><td class=test_lt></td><td class=test_t></td><td class=test_rt></td></tr>'+
			'<tr><td class=test_l></td><td class=ajtable>'+
			'<div class=ajaxtitle onmousedown="dragStart(event, \'msg\')"><div class=i><img src=/i/gui/closeb.png'+
			' onclick=HideClear(\'msg\') class=ajaxclose width=9 height=9 title=\'Закрыть\'><div style=margin-right'+
			':30px; id=ajaxim_title>'+title+'</div></div></div>'+
			'<div class=clr><!-- --></div>'+
			'<div class=ajaxi>'+msg+
			'<br><br><div align=center><input type="button" class="redbutton" onclick="HideClear(\'msg\');'+(func?func+'();':'')+
			'" value="OK"/></div>'+
			'</div></td><td class=test_r></td></tr>'+
			'<tr><td class=test_lb></td><td class=test_b></td><td class=test_rb></td></tr>'+
			'</table>';
	m = SfindObj('msg');
	m.style.zIndex = 2000;
	m.innerHTML = html;	
	CenterLayer('msg',300,100,window.document);
}

function echeck(str) {

		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		if (str.indexOf(at)==-1){
		   return false;
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false;
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		   return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		   return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		   return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		   return false;
		 }
		
		 if (str.indexOf(" ")!=-1){
		   return false;
		 }

 		 return true;
}

function ValidateSendForm (formname,aFields) {

	f = window.document.forms['formresponse'];
	try {
		tinyContent = tinyMCE.get('tresponse').getContent();
		if (tinyContent && f.response)
			f.response.value=tinyContent;
	}
	catch(e) {;}
	
	f = window.document.forms[formname];

	if (formname == 'formupload' && f.httpfile) {
		if (!f.imgupl.value && (!f.httpfile.value || (f.httpfile.value == 'http://'))) {
			msg(error_messages[formname]['nofile'],'Ошибка');
			return false;
		}
	}

	if ((formname == 'formitem') && f.datey) {

		datey = trim(f.datey.value,'0');
		datem = trim(f.datem.value,'0');
		dated = trim(f.dated.value,'0');

		datey = parseInt(datey);
		datem = parseInt(datem);
		dated = parseInt(dated);
		
		if (!datey && !datem && !dated) {

			check = true;
			for (i=0;i < f.statusid.length;i++)
				if (f.statusid[i].checked)
					check = false;

			if (check || (f.statusid[4].checked || f.statusid[6].checked || f.statusid[7].checked)) {
				msg(error_messages[formname]['nodata'],'Ошибка');
				return false;
			}
		}
		
	}

	if (formname == 'formoptions') {

		if(f.newpassword.value && !f.oldpassword.value) {
			msg(error_messages[formname]['oldpassword'],'Ошибка')
			return false;
		}

		if(f.newpassword.value && f.newpassword.value!=f.confpassword.value) {
			msg(error_messages[formname]['notequalpasswords'],'Ошибка')
			return false;
		}

		if ((f.email.value != f.emailor.value) && !f.oldpassword.value) {
			msg(error_messages[formname]['oldpassword'],'Ошибка')
			return false;
		}

		if ((f.openid.value != f.openidor.value) && !f.oldpassword.value) {
			msg(error_messages[formname]['oldpassword'],'Ошибка')
			return false;
		}
	}

	if ((formname == 'formregistration') && f.datey && f.datem && f.dated) {
		datey = trim(f.datey.value,'0');
		datem = trim(f.datem.value,'0');
		dated = trim(f.dated.value,'0');

		datey = parseInt(datey);
		datem = parseInt(datem);
		dated = parseInt(dated);

		if (!datey || !datem || !dated) {
			msg(error_messages[formname]['nodata'],'Ошибка');
			return false;
		}
		
	}

	if (formname == 'formopenid') {
		pattern = new RegExp("@", "g");
		if (pattern.test(f.openid_url.value)) {
				msg(error_messages[formname]['openid_url'],'Ошибка');
				f.openid_url.focus();
				return false;
		}
	}

	if (formname == 'formregistration') {
		if (f.login) {
			pattern = new RegExp("^[a-zA-Z0-9]{2,50}$", "g");
			if (!pattern.test(f.login.value)) {
				//alert('В поле "Логин" мало букв или использованы недопустимые символы!');
				msg('В поле "Логин" мало букв или использованы недопустимые символы!','Ошибка');
				f.login.focus();
				return false;
			}
		}

		if (f.email && f.email.value && !echeck(f.email.value)) {
			msg('Введите E-mail правильно','Ошибка');
			f.email.focus();
			return false;
		}

		
		if(f.password && (f.password.value!=f.confpassword.value))
		{
			//alert('Пароли не совпадают!');
			msg('Пароли не совпадают!','Ошибка');
			f.password.focus();
			return false;
		}
	}

	if ((formname == 'formregistration') && f.sex) { //profile
		checkedone = false;
		for (i=0;i<f.sex.length;i++) {
			if (f.sex[i].checked)
				checkedone = true;
		}
		if (!checkedone) {
			msg(error_messages[formname]['sex'],'Ошибка');
			return false;
		}
	}

	bPassZam = false;
	if ('formitem' == formname) 
	{
		if (f.price && f.price.value != '0' && f.price.value != '' && f.currencyid.value <= 0) 
		{
			msg(error_messages['formitem']['currencyid'], 'Ошибка');
			return false;
		}

		f1 = window.document.forms['formresponse'];

		if (!f1.edit && (f1.response.value != '')) {
			if (f1.tag)
				f.zamtagid.value = f1.tag.value;

			if (f1.response)
				f.zamtext.value = f1.response.value;

			bPassZam = true;
		}
		else if (!f.zcount || f.zcount.value <= 0) 
		{
			msg(error_messages['formitem']['zametka'], 'Ошибка');
			return false;
		}
		if (f1.pricebu) {
			f.zamtext.value = f1.response.value;
			f.pricebu.value = f1.pricebu.value;
			f.complect.value = f1.complect.value;
			bPassZam = true;
		}
	}
	
	
	for (i = 0; i < aFields.length; i++) {
		//alert(aFields[i]+'/'.f.elements[aFields[i]].getAttribute('type')+'/'+);
		if (f.elements[aFields[i]]) {
			if (((f.elements[aFields[i]].getAttribute('type') == 'select-one') && (f.elements[aFields[i]].selectedIndex == 0) && (f.elements[aFields[i]].style.display != 'none')) 
			|| 
			((f.elements[aFields[i]].getAttribute('type') == 'text') && (trim(f.elements[aFields[i]].value,' ') == '') && (f.elements[aFields[i]].style.display != 'none'))
			|| 
			((f.elements[aFields[i]].getAttribute('type') == 'password') && (trim(f.elements[aFields[i]].value,' ') == '') && (f.elements[aFields[i]].style.display != 'none'))
			|| 
			((f.elements[aFields[i]].getAttribute('type') == 'textarea') && (trim(f.elements[aFields[i]].value,' ') == '') && (f.elements[aFields[i]].style.display != 'none'))
			|| 
			((f.elements[aFields[i]].getAttribute('type') == 'hidden') && ((trim(f.elements[aFields[i]].value,' ') == '') || (trim(f.elements[aFields[i]].value,' ') == '0')) && (f.elements[aFields[i]].style.display != 'none'))
			|| 
			((f.elements[aFields[i]].getAttribute('type') == 'checkbox') &&  (!f.elements[aFields[i]].checked))
			|| 
			((f.elements[aFields[i]].getAttribute('type') == null) && (trim(f.elements[aFields[i]].value,' ') == '') && (f.elements[aFields[i]].style.display != 'none'))
			) {
				//alert('Не заполнено обязательное поле!');
				
				if(error_messages[formname] && error_messages[formname][aFields[i]])
					msg(error_messages[formname][aFields[i]],'Ошибка');
				else {
					msg('Не заполнено обязательное поле!','Ошибка');
				}
				try {
					f.elements[aFields[i]].focus();
				}
				catch(e) {;}
				return false;
			}
		}
	}

	obj=SfindObj('blinks');
	
	if (obj && (obj.innerHTML == 'Заметок нет') && (formname != 'formzametka')) {
		//alert('Не заполнена ни одна заметка!');
		msg('Не добавлен ни один комментарий!','Ошибка');
		return false;
	}

	if (!bPassZam && (formname != 'formupload') && (formname != 'formresponse') && document.forms['formresponse'] && (document.forms['formresponse'].response.value)) {
		//alert('Не забудьте сохранить заметку!');
		msg('Не забудьте сохранить комментарий!','Ошибка');
		return false;
	}

	//try {
		
	//}
	//catch(e) {;}

	return true;
}

function trim(s,what) {
	while (s.substring(0,1) == what) {
	s = s.substring(1,s.length);
	}
	while (s.substring(s.length-1,s.length) == what) {
	s = s.substring(0,s.length-1);
	}
	return s;
}

function ZeroBefore (nVal) {
	if (nVal < 10)
		nVal='0'+nVal;
	return nVal;
}


function BackGroundPost () {
	
}


function collapseall (objid) {
	if (!objid)
		objid = '';
	obj = document.getElementsByTagName('div');	
	for (var i = 0; i < obj.length; i++) {
		 if (obj[i].id.indexOf("posts_"+objid) != -1)  {
			if ((obj[i].style.display == '') || (obj[i].style.display == 'block'))
				obj[i].style.display = 'none';
			else
				obj[i].style.display = 'block';
		 }
		
	}
}

function autosearch(e, fieldname, fieldvalue, divname) {
	if (!e) e = window.event || null; if (e.altKey || e.ctrlKey) return;
	var n = e.keyCode?e.keyCode:e.charCode;	if (n == 13 || n == 11) return;

	//как стереть признак?
	if (n == 8 || n == 9 || n == 16 || n == 17 || n == 20 || n == 35 || n == 36 || n == 37 || n == 39 || n == 45 || n == 46)
		sDisableSearch = '';
	
	if (sDisableSearch == fieldname)
		return;
		
	clearTimeout(searchTimeOut);
	searchTimeOut = window.setTimeout("autosearchexecute('"+fieldname+"','"+fieldvalue+"','"+divname+"')", 1000);
}

function autosearchexecute (fieldname, formname, divname) {
	AjaxSendRequest('/ajax/' + fieldname + 
				'search/', 
				'field=' + encodeURI(fieldname) + 
				'&title=' + encodeURI(window.document.forms[formname].title.value) + 
				'&fulltitle=' + encodeURI(window.document.forms[formname].fulltitle.value) + 
				'&class=' + window.document.forms[formname].category.value
				, divname, 250, 200, 300);
	obj=SfindObj('autosearch_' + fieldname);
	obj.style.visibility = 'visible';
}

function autosearch1(e, fieldname, fieldvalue, divname, value1) {
	if (!e) e = window.event || null; if (e.altKey || e.ctrlKey) return;
	var n = e.keyCode?e.keyCode:e.charCode;	if (n == 13 || n == 11) return;
	clearTimeout(searchTimeOut);
	searchTimeOut = window.setTimeout("autosearchexecute1('"+fieldname+"','"+fieldvalue+"','"+divname+"','"+value1+"')", 1000);
}

function autosearchexecute1 (fieldname, formname, divname, value1) {
	AjaxSendRequest('/ajax/' + fieldname + 
				'search', 
				'field=' + encodeURI(fieldname) + 
				'&formname=' + encodeURI(formname) + 
				'&value=' + encodeURI(value1)
				, divname, 250, 200, 300);
	if(obj=SfindObj('autosearch_' + fieldname))
		obj.style.visibility = 'visible';
}
function change_onchange (fieldname, formname, divname, value1) {
	AjaxSendRequest('/ajax/' + fieldname + 
				'_return', 
				'field=' + encodeURI(fieldname) + 
				'&formname=' + encodeURI(formname) + 
				'&value=' + encodeURI(value1)
				, divname, 250, 200, 300);
}


function activate (lnk,nUserId) {

	obj=SfindObj('lbn_'+nUserId);if (obj) {obj.style.color='#008cd2';obj.style.borderBottom='1px dashed #008cd2';obj.style.cursor='pointer';}
	obj=SfindObj('ln_'+nUserId);if (obj) {obj.style.color='#008cd2';obj.style.borderBottom='1px dashed #008cd2';obj.style.cursor='pointer';}
	obj=SfindObj('lr_'+nUserId);if (obj) {obj.style.color='#008cd2';obj.style.borderBottom='1px dashed #008cd2';obj.style.cursor='pointer';}
	obj=SfindObj('lg_'+nUserId);if (obj) {obj.style.color='#008cd2';obj.style.borderBottom='1px dashed #008cd2';obj.style.cursor='pointer';}
	obj=SfindObj('lb_'+nUserId);if (obj) {obj.style.color='#008cd2';obj.style.borderBottom='1px dashed #008cd2';obj.style.cursor='pointer';}
	obj=SfindObj('ll_'+nUserId);if (obj) {obj.style.color='#008cd2';obj.style.borderBottom='1px dashed #008cd2';obj.style.cursor='pointer';}
	obj=SfindObj('lf_'+nUserId);if (obj) {obj.style.color='#008cd2';obj.style.borderBottom='1px dashed #008cd2';obj.style.cursor='pointer';}
	obj=SfindObj('lp_'+nUserId);if (obj) {obj.style.color='#008cd2';obj.style.borderBottom='1px dashed #008cd2';obj.style.cursor='pointer';}
	obj=SfindObj(lnk+'_'+nUserId);if (obj) {obj.style.color='#e86e00';obj.style.borderBottom='0px dashed #e86e00';obj.style.cursor='default';}
	
}

/*function deactivate (nUserId) {
	if (bef) {
			bef.style.color='#008cd2';
			bef.style.borderBottom='1px dashed #008cd2';
		}
}*/

function tsw(num, num_ ) 
{
	if ( num_ == null )
	{
		num_=2;
	}
	for (var i = 1; i <= num_; i++)
	{
			
			obj=SfindObj('tsw'+i);
			obj.className = '';
			
			obj=SfindObj('tbm'+i);
			obj.style.display = 'none';
	}
	obj=SfindObj('tsw'+num);
	obj.className = 'a';
	//alert('test');
	try {
		obj.blur();
	}
	catch (error) {}
	
	obj=SfindObj('tbm'+num);
	obj.style.display = 'block';
}

function CheckIfImageFilled () {
	if (window.document.forms['formupload']) {
		if (((window.document.forms['formupload'].httpfile.value != 'http://') && (window.document.forms['formupload'].httpfile.value != '')) || (window.document.forms['formupload'].imgupl && window.document.forms['formupload'].imgupl.value)) {
			if (confirm('Вы не разместили файлы в  фотогалерее. Все равно продолжить?'))
				return true;
			else
				return false;
		}
	}
	return true;
}

function ChangeWindowTitle (sNewTitle) {
	window.document.title = sNewTitle;
	if(obj=SfindObj('ajax1_1_title'))
	{
		sNewTitle = sNewTitle.substring(0,43);
		obj.innerHTML=sNewTitle;
	}
}

function CheckScrollers () {
	if (browser.isIE)
		return;
	sOverflow = 'auto';
	obj=SfindObj('ajax1');x=parseInt(obj.style.left);if (isNaN(x)) x=-5000; if (x > -4000) sOverflow = 'hidden';

	if (sOverflow == 'auto') {obj=SfindObj('ajax1_1');x=parseInt(obj.style.left);if (isNaN(x)) x=-5000; if (x > -4000) sOverflow = 'hidden';}

	if (sOverflow == 'auto') {obj=SfindObj('ajax2');x=parseInt(obj.style.left);if (isNaN(x)) x=-5000; if (x > -4000) sOverflow = 'hidden';}

	if (sOverflow == 'auto') {obj=SfindObj('ajax2_1');x=parseInt(obj.style.left);if (isNaN(x)) x=-5000; if (x > -4000) sOverflow = 'hidden';}

	if (sOverflow == 'auto') {obj=SfindObj('preview');if (obj.style.visibility && (obj.style.visibility != 'hidden')) sOverflow = 'hidden';}
	
	var divs = window.document.getElementsByTagName('div');
	for (var i = 0; i < divs.length; i++) {
		if ((divs[i].className == 'tags') || (divs[i].id == 'photogalleryw')) {
			divs[i].style.overflow = sOverflow;
		}
	}
}

function ShowVPrev(oLink,sObj) {
	x=0;
	y=0;
	x=parseInt(ofindPosX(oLink));
	y=parseInt(ofindPosY(oLink));
	obj=SfindObj(sObj);
	obj.style.left=x-20+'px';
	obj.style.top=y-200+'px';
	ShowLa(sObj);
}

function findPosY(sObj)
{
	obj=SfindObj(sObj);
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function findPosX(sObj)
{
	obj=SfindObj(sObj);
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curtop += obj.x;
	return curtop;
}

function ofindPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function ofindPosX(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curtop += obj.x;
	return curtop;
}

function zamact (obj, num) {
	for (i=1;i < 15; i++) {
		obj=SfindObj('zamtagid_'+i);if (obj) obj.className = 'ajs';
	}

	obj=SfindObj('zamtagid_'+num);if (obj) obj.className = 'ajs active';
	obj.blur();
	//zamacta = obj;
	document.forms['formresponse'].tag.value = num;
}

function owntype (obj, num) {

	for (i=0;i < 15; i++) {
		obj=SfindObj('owntypea_'+i);if (obj) obj.className = 'ajs';
	}

	obj=SfindObj('owntypea_'+num);obj.className = 'ajs active';
	obj.blur();
	document.forms['formresponse'].owner.value = num;
}

function statswf (num) {
	for (i=-1;i<9;i++) {
		obj=SfindObj('statsw_'+i);
		if (obj)
			obj.className = 'ajs';
	}
	obj=SfindObj('statsw_'+num);
	obj.className = 'ajs active';
	obj.blur();
}

function curtype (obj, num) {
	obj=SfindObj('curt_1');obj.className = 'ajs';
	obj=SfindObj('curt_2');obj.className = 'ajs';
	obj=SfindObj('curt_3');obj.className = 'ajs';
	obj=SfindObj('curt_4');obj.className = 'ajs';
	obj=SfindObj('curt_5');obj.className = 'ajs';
	obj=SfindObj('curt_'+num);obj.className = 'ajs active';
	obj.blur();
	document.forms['formoptions'].currency.value = num;
}

function SwitchBlog (id) {
	obj=SfindObj('bl' + nCurrentBlId);
	obj.className='';
	obj=SfindObj('bl' + id);
	obj.className='active';
	nCurrentBlId = id;
	AjaxSendRequest('/ajaxdata/getblog/', 'id='+id, 'blog');
}

function IMGet () {
	
	obj=SfindObj('ajax4');
	if (parseInt(obj.style.left) > -4000)
			return;
	
	if (ajaxcounter > 0)
		return;

	vars = '';
	obj=SfindObj('ajaxim');
	if (parseInt(obj.style.left) > -4000)
		vars = vars + '&list=1';

	obj=SfindObj('ajaximchat');
	if (parseInt(obj.style.left) > -4000)
		vars = vars + '&chat=1&uid='+nJabberUser;

	AjaxSendRequest("/jabberajax/imreceive/", vars, "imind");
}

function AddTag (sForm, field, sValue) {
		f = document.forms[sForm].interests;
		f.value = f.value + ", " + sValue;
		f.value=trim(f.value," ");
		f.value=trim(f.value,",");
		f.value=trim(f.value," ");
}

function ZeroBefore (nVal) {
	if (nVal < 10)
		nVal='0'+nVal;
	return nVal;
}

function InsIMChat () {
	obj=SfindObj('prvmsg');
	time = new Date();

	sYear=time.getFullYear();
	sMonth=ZeroBefore(parseInt(time.getMonth())+1);
	sDay=time.getDate();
	sWeekDay=time.getDay();
	
	sHours=ZeroBefore(time.getHours());
	sMinutes=ZeroBefore(time.getMinutes());
	sSeconds=ZeroBefore(time.getSeconds());

	obj.innerHTML = obj.innerHTML + '<span class=date>'+sDay+'.'+sMonth+'.'+sYear+' '+sHours+':'+sMinutes+':</span> ' + '<span class=from>'+document.forms['imsend'].response.value+'</span><br>';
	document.forms['imsend'].response.value = '';
}

function IMShowDel (nJid) {
	obj=SfindObj('dejid_'+nJid);
	if (obj)
		obj.style.visibility = 'visible';
}

function IMHideDel (nJid) {
	obj=SfindObj('dejid_'+nJid);
	if (obj)
		obj.style.visibility = 'hidden';
}

nTimeOut = 0;
function usrmenu(id)
{
	obj=SfindObj('usrmenu_'+id);
	if ((obj.style.display == '') || (obj.style.display == 'none'))
		obj.style.display = 'block';
	else
		obj.style.display = 'none';
}

function parammenu(id)
{
	obj=SfindObj('paramsvalues_'+id);
	if ((obj.style.display == '') || (obj.style.display == 'none'))
		obj.style.display = 'block';
	else
		obj.style.display = 'none';
}

function complexmenu(id)
{
	obj=SfindObj('complexvalues_'+id);
	if ((obj.style.display == '') || (obj.style.display == 'none'))
		obj.style.display = 'block';
	else
		obj.style.display = 'none';
}

function simmenu(id)
{
	obj=SfindObj('similar_'+id);
	if ((obj.style.display == '') || (obj.style.display == 'none'))
		obj.style.display = 'block';
	else
		obj.style.display = 'none';
}

function mailmenu()
{
	obj=SfindObj('mailblock');
	if ((obj.style.display == '') || (obj.style.display == 'none'))
		obj.style.display = 'block';
	else
		obj.style.display = 'none';
}

function ShowLa(show)
{
	obj = SfindObj(show);
	if (obj)
		obj.style.display = 'block';
}

function HideLa(show)
{
	obj = SfindObj(show);
	if (obj)
		obj.style.display = 'none';
}

function ParClick (parid, valid, value) {
	//document.forms['formitem'].'params['+parid+']'.value=valid;
	obj = SfindObj('params['+parid+']');
	obj.value = valid;

	obj = SfindObj('paramvalue_' + parid);
	obj.innerHTML = value;
	HideLa('paramlayer_' + parid);
}

function in_array (what, where) {
	for (i = 0; i < where.length; i++) {
		if (where[i] == what)
			return i;
	}
	return -1;
}

/*
function CommaList (formelement, rid, newvalue) {
	sCurrentList = formelement.value;
	aCurrentList = sCurrentList.split(',');
	nPos = in_array(newvalue, aCurrentList);
	if (nPos == -1) {
		formelement.value = formelement.value + newvalue + ',';
		obj=SfindObj('friendrub_'+rid);
		obj.className = 'active';
	}
	else {
		aCurrentList.splice(nPos,1);
		sCurrentList = aCurrentList.join(',');
		formelement.value = sCurrentList;
		obj=SfindObj('friendrub_'+rid);
		obj.className = '';
	}
	
}
*/

function changeprofile(formelement,idname,idnamep)
{
	elms = SfindObj(idnamep).getElementsByTagName('a');
	sCurrentList = formelement.value;
	aCurrentList = sCurrentList.split(',');
	for(ui_i=0;ui_i<elms.length;ui_i++)
		if(elms[ui_i].id.indexOf(idname+'_') == 0)
				elms[ui_i].className = in_array(elms[ui_i].id.split('_')[1], aCurrentList)==-1?'':'active';
}

function CommaList (formelement, rid, newvalue,idname)
{
	if(!idname) idname = 'friendrub';
	 
	sCurrentList = formelement.value;
	aCurrentList = sCurrentList.split(',');
	nPos = in_array(newvalue, aCurrentList);
	if (nPos == -1) {
		formelement.value = formelement.value + newvalue + ',';
		if(obj=SfindObj(idname + '_' +rid))	obj.className = 'ajs active';
	}
	else {
		aCurrentList.splice(nPos,1);
		sCurrentList = aCurrentList.join(',');
		formelement.value = sCurrentList;
		if(obj=SfindObj(idname + '_'+rid))	obj.className = 'ajs';
	}
	
}

function SetCookie(name, value) {
   var argv    = SetCookie.arguments;
   var argc    = SetCookie.arguments.length;
   var expires = (argc > 3) ? new Date(argv[3]) : null;
   //var path    = (argc > 4) ? argv[4] : null;
	var path    = '/';
   var domain  = (argc > 5) ? argv[5] : null;
   var secure  = (argc > 6) ? argv[6] : false;
   expires = 'Friday, 01-Jan-2399 00:00:00 GMT';

   document.cookie = name + "=" + escape(value)
      + ((expires == null) ? "" : ("; expires=" + expires))
      + ((path == null) ? "" : ("; path=" + path))
      + ((domain == null) ? "" : ("; domain=" + domain))
      + ((secure == true) ? "; secure" : "");
}

function GetCookie(name) {
   var arg  = name + "=";
   var alen = arg.length;
   var clen = document.cookie.length;
   var i    = 0;

   while(i < clen) {
      var offset = i + alen;

      if(document.cookie.substring(i, offset) == arg) {
         var iEnd  = document.cookie.indexOf(";", offset);

         if(iEnd == -1) {
            iEnd = document.cookie.length;
         }

         return unescape(document.cookie.substring(offset, iEnd));
      }

      i = document.cookie.indexOf(" ", i) + 1;

      if(i == 0) {
         break;
      }
   }

   return null;
}

function AddSnippet(textEl, snippet1, snippet2) 
{
	//IE support
	if (document.selection) 
	{
		textEl.focus();
		sel = document.selection.createRange();
		sel.text =  snippet1 + sel.text + snippet2;
	}
	//GECKO support
	else if (textEl.selectionStart || textEl.selectionStart == '0') 
	{
		var startPos = textEl.selectionStart;
		var endPos = textEl.selectionEnd;
		textEl.value = textEl.value.substring(0, startPos) + snippet1 + textEl.value.substring(startPos, endPos) + snippet2 + textEl.value.substring(endPos, textEl.value.length);
	}
	else 
		textEl.value += snippet1+snippet2;
}

function Spy (sObject) {
		obj=SfindObj(sObject);
		if (obj) {
	
			if ((document.body.scrollTop < nMenuYPos - nYDelta) || ((document.body.scrollTop - nYDelta) < 0))
				nNeededPos = nMenuYPos;
			else
				nNeededPos = document.body.scrollTop + nYDelta;
			nCurrentPos = obj.offsetTop;
	
			if (nNeededPos == nCurrentPos)
				return;
	
			nDelta = (nNeededPos - nCurrentPos) / 6;
			if (nDelta > 0 && nDelta < 0.5)
				nCurrentPos += nNeededPos - nCurrentPos;
			else
				if (nDelta < 0 && nDelta >= -0.5)
					nCurrentPos --;
				else
					nCurrentPos += Math.round (nDelta);
			
			pnt = obj.style;
			pnt.top = nCurrentPos;
		}
}

function ScriptStart (sObject) {
	setInterval("Spy ('"+sObject+"')", 20);
	HideScroller ();
}

function HideScroller () {
	elements=window.document.getElementsByTagName('div');
	noscrolls = parseInt(GetCookie('ns'));

	for(var i = 0; i < elements.length; i++) {
		obj=elements.item(i);
		if (obj.className == 'tags') {
			r=parseInt(obj.offsetHeight);
			if (!noscrolls) {
					scswo = SfindObj('scsw1');
					if (scswo)
						scswo.style.display='inline';
					scswo = SfindObj('scsw2');
					if (scswo)
						scswo.style.display='inline';
			}
			else if (r) {
				if (r <= 305) {
					scswo = SfindObj('scsw1');
					if (scswo)
						scswo.style.display='none';
					scswo = SfindObj('scsw2');
					if (scswo)
						scswo.style.display='none';
				}
				else {
					scswo = SfindObj('scsw1');
					if (scswo)
						scswo.style.display='inline';
					scswo = SfindObj('scsw2');
					if (scswo)
						scswo.style.display='inline';
				}
			}
		}
	}
	
}

function setitemf (year,month,day) {
	if (window.document.forms['formitem'])
		f = window.document.forms['formitem'];
	else
		f = window.document.forms['formregistration'];
	f.datey.value = year;
	f.datem.value = month;
	f.dated.value = day;
	HideClear('ajax2_1');
	obj=SfindObj('choosedate');
	if (!day && !month)
		obj.innerHTML = year;
	else if (!day)
		obj.innerHTML = month + '.' + year;
	else
		obj.innerHTML = day + '.' + month + '.' + year;
}

bScriptLoaded = true;
//ajax

function ajax()
{
    //---------------------
    // Private Declarations
    //---------------------
    var _request = null;
    var _this = null;
    
    //--------------------
    // Public Declarations
    //--------------------
    var nAjaxWidth = 250;
    var nAjaxHeight = 200;
    var nAjaxXOffset = 0;
    var nAjaxYOffset = 0;
    
    this.GetResponseXML = function()
    {
        return (_request) ? _request.responseXML : null;
    };
    
    this.GetResponseText = function()
    {
        return (_request) ? _request.responseText : null;
    };
    
    this.GetRequestObject = function()
    {
        return _request;
    };
    
    this.InitializeRequest = function(Method, Uri)
    {
        _InitializeRequest();
        _this = this;
        
        switch (arguments.length)
        {
            case 2:
                _request.open(Method, Uri);
                break;
                
            case 3:
                _request.open(Method, Uri, arguments[2]);
                break;
        }
        
        if (arguments.length >= 4) 
            _request.open(Method, Uri, arguments[2], arguments[3]);
        this.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    };
    
    this.SetRequestHeader = function(Field, Value)
    {
        if (_request) 
            _request.setRequestHeader(Field, Value);
    };
    
    this.Commit = function(Data)
    {
        if (_request) 
            _request.send(Data);
    };
    
    this.Close = function()
    {
        if (_request) 
            _request.abort();
    };
    
    //---------------------------
    // Public Event Declarations.
    //---------------------------
    this.OnUninitialize = function()
    {
    };
    this.OnLoading = function()
    {
    };
    this.OnLoaded = function()
    {
    };
    this.OnInteractive = function()
    {
    };
    this.OnSuccess = function()
    {
    };
    this.OnFailure = function()
    {
        //alert('AJAX Error. Sorry');
    };
    
    //---------------------------
    // Private Event Declarations
    //---------------------------
    function _OnUninitialize()
    {
        _this.OnUninitialize();
    };
    function _OnLoading()
    {
        _this.OnLoading();
    };
    function _OnLoaded()
    {
        _this.OnLoaded();
    };
    function _OnInteractive()
    {
        _this.OnInteractive();
    };
    function _OnSuccess()
    {
        _this.OnSuccess();
    };
    function _OnFailure()
    {
        _this.OnFailure();
    };
    
    //------------------
    // Private Functions
    //------------------
    function _InitializeRequest()
    {
        _request = _GetRequest();
        _request.onreadystatechange = _StateHandler;
    };
    
    function _StateHandler()
    {
        switch (_request.readyState)
        {
            case 0:
		try { window.setTimeout("void(0)", 100);} catch (error) {}
                _OnUninitialize();
                break;
                
            case 1:
                try { window.setTimeout("void(0)", 100);} catch (error) {}
                _OnLoading();
                break;
                
            case 2:
                try { window.setTimeout("void(0)", 100);} catch (error) {}
                _OnLoaded();
                break;
                
            case 3:
                try { window.setTimeout("void(0)", 100);} catch (error) {}
                _OnInteractive();
                break;
                
            case 4:
		try {rstatus = _request.status;} catch (error) {rstatus='';}
                if ((rstatus == 200) || !rstatus) 
                {
                    	try {
                    		ajaxcounter--;
			}
			catch(e) {;}
                    _OnSuccess();
                    
                }
                else 
                {
			try {
                    		ajaxcounter--;
			}
			catch(e) {;}
                    _OnFailure();
                }
                
                return;                break;
        }
    };
    
    function _GetRequest()
    {
        var obj;
        
        try 
        {
            obj = new XMLHttpRequest();
        } 
        catch (error) 
        {
            try 
            {
                obj = new ActiveXObject("Microsoft.XMLHTTP");
            } 
            catch (error) 
            {
                try 
                {
                    obj = new ActiveXObject('Msxml2.XMLHTTP');
                } 
                catch (error) 
                {
                    return null;
                }
            }
        }
        
        return obj;
    };
};

function ShowAjaxIndicator()
{
    obj = SfindObj('ajloading');
    if (obj) 
    {
        obj.style.visibility = 'visible';
        obj.style.left = document.body.clientWidth - 63 + 'px';
        ntop = document.body.scrollTop + document.body.clientHeight - 63;
        obj.style.top = ntop + 'px';
    }
}

function HideAjaxIndicator()
{
    obj = SfindObj('ajloading');
    if (obj) 
    {
        obj.style.visibility = 'hidden';
        obj.style.left = document.body.clientWidth - 63 + 'px';
        //ntop = document.body.scrollTop+document.body.clientHeight-63;
        obj.style.top = 10 + 'px';
    }
}


function apply_responce(xmldoc, nAjaxWidth, nAjaxHeight, nV, nAjaxXOffset, nAjaxYOffset)
{
    root = xmldoc.getElementsByTagName('root')[0];

    if (root) 
    {
        /*xml response*/
        //var root = xmldoc.getElementsByTagName('root')[0];
        if (root) 
        {
            for (var iNode = 0; iNode < root.childNodes.length; iNode++) 
            {
                if (root.childNodes[iNode].nodeType == 1) 
                {

                    if (root.childNodes[iNode].tagName == 'errmsg') 
					{
						msg(root.childNodes[iNode].firstChild.nodeValue,'Ошибка')
					}
					else
					if (root.childNodes[iNode].tagName == 'ajax2_1') 
                    {
                        obj = SfindObj('autosearch_title');
                        if (obj) 
                            obj.style.visibility = 'hidden';
                        obj = SfindObj('autosearch_manufacturer');
                        if (obj) 
                            obj.style.visibility = 'hidden';
                        obj = SfindObj('autosearch_model');
                        if (obj) 
                            obj.style.visibility = 'hidden';
                        obj = SfindObj('autosearch_fulltitle');
                        if (obj) 
                            obj.style.visibility = 'hidden';
                    }
                    else 
                        if (root.childNodes[iNode].tagName == 'ajax1_1') 
                        {
                            if (obj = SfindObj('autosearch_country')) 
                                obj.style.visibility = 'hidden';
                            if (obj = SfindObj('autosearch_town')) 
                                obj.style.visibility = 'hidden';
                        }

                    try 
                    {
                        innerH = root.childNodes[iNode].firstChild.nodeValue;
                    } 
                    catch (error) 
                    {
                        innerH = '';
                    }

			SmthChangedInForms[root.childNodes[iNode].tagName]=0;

                    if (obj = SfindObj(root.childNodes[iNode].tagName)) 
                    {
                        if (root.childNodes[iNode].tagName == 'zcount') 
                            obj.value = innerH;
                        else {
                            	obj.innerHTML = innerH;
				scripts_arr = obj.getElementsByTagName("script");
				if (scripts_arr.length > 0)
					for(i in scripts_arr) eval(scripts_arr[i].text);
			}
                    }
                    if (root.childNodes[iNode].tagName == 'shake') 
                        if(vldnotb)
                        	new Effect.Shake(innerH);
                        else 
                            msg('Проверьте введенные данные!','Ошибка');

                    if (root.childNodes[iNode].tagName.indexOf('ajax') != -1) 
                    {
                        /*obj.style.minwidth = nAjaxWidth;*/
                        /*obj.style.height = nAjaxHeight;*/
                        if (innerH) 
                        {
                            CenterLayer(root.childNodes[iNode].tagName, nAjaxWidth, nAjaxHeight, nV, nAjaxXOffset, nAjaxYOffset);
                            tag = root.childNodes[iNode].tagName;
                            wnds = ['ajax1', 'ajax2', 'ajax3', 'ajax4', 'ajaxim', 'ajaximchat'];
                            for (i = 0; i < wnds.length; i++) 
                                if (obj1 = SfindObj(wnds[i])) 
                                {//в 0 если не установлен ордер... надо бы заменить..
                                    z = parseInt(obj1.style.zIndex == undefined ? 10 : obj1.style.zIndex);
                                    if (isNaN(z)) 
                                        z = 10;
                                    else 
                                        if (z >= 1000) 
                                            z -= 1000;
                                    obj1.style.zIndex = tag == wnds[i] ? 1000 + z : z;
                                }
                        }
                    }

                    /*if (root.childNodes[iNode].tagName != 'zametkadiv' && obj && obj.style) 
                     obj.style.visibility = 'visible';*/
      if ((innerH.indexOf('<div class=ajaxi></div>') != -1) || (innerH.indexOf('<!-- begin --><!-- end -->') != -1) || (innerH.indexOf('<!-- begin --><!--') != -1)) 
      	HideClear(root.childNodes[iNode].tagName);
      
      if ((innerH.indexOf('<!-- imchat -->') != -1)) {
      	obj1 = SfindObj('prvmsg');
      	obj1.scrollTop = 10000000;
      }

		if ((root.childNodes[iNode].tagName == 'imind') && (innerH.indexOf('<!-- yes -->') != -1) && !noshowimcenter) {
								obj=SfindObj('imind');
								sText = obj.innerHTML;
                        obj=SfindObj('imcenter');
			obj.innerHTML = '<div style=padding-top:6px>' + sText + '<img src=/i/gui/closew.png class=imclose width=9 height=9 title="Закрыть" onclick=noshowimcenter=1;HideLa("imcenter")></div>';
			obj.style.display = 'block';
		}
		else if (root.childNodes[iNode].tagName == 'imind') {
			obj=SfindObj('imcenter');
			obj.style.display = 'none';
		}
                    
                    
                    if (innerH.indexOf('<!-- fulltitle -->') != -1) 
                        sDisableSearch = 'fulltitle';
                    
                    if (innerH.indexOf('<!-- title -->') != -1) 
                        sDisableSearch = 'title';
                    
                    if (innerH.indexOf('<!-- country -->') != -1) 
                        sDisableSearch = 'country';
                    
                    if (innerH.indexOf('<!-- region -->') != -1) 
                        sDisableSearch = 'region';
                    
                    if (innerH.indexOf('<!-- town -->') != -1) 
                        sDisableSearch = 'town';

		gotolinkc = GetCookie('gotolink');
                if ((root.childNodes[iNode].tagName == 'loginbar') && gotolink) 
                        document.location.href = gotolink;
		else	if ((root.childNodes[iNode].tagName == 'loginbar') && gotolinkc) {
			document.location.href = gotolinkc;
		}

                    
                    CheckScrollers();
                    
                    /*if (root.childNodes[iNode].tagName == 'formresponsecontainer') 
                        AjaxSendRequest('/ajax/blognotessearch/', 'id=' + window.document.forms['formresponse'].id.value + '&gid=' + window.document.forms['formresponse'].gid.value + '', 'ajax2_1', 250, 200, 350);*/
                    if (root.childNodes[iNode].tagName.indexOf('message_') != -1) 
                    {
                        y = findPosY(root.childNodes[iNode].tagName);
                        window.scrollTo(0, y);
                    }

			if (innerH.indexOf('<!-- prvjsvgfrm -->') != -1) {
				obj=SfindObj('prvjsvgfrm');
				if (obj) {
					n = Math.round();
					obj.src = window.document.forms['vidgetjsform'].ihref.value + '&rnd=' + n;
				}
			}

			if (innerH.indexOf('<!-- formitem -->') != -1) {
				if (nCurrentRubId) {
					f=window.document.forms['formitem'];
					if (f.category)
						f.category.value=nCurrentRubId;
					obj=SfindObj('chooserub');
					if (obj && sCurrentRub)
						obj.innerHTML = sCurrentRub;
				}
				if (nCurrentTagId && sCurrentTag) {
					f=window.document.forms['formitem'];
					if (f.title)
						f.title.value=sCurrentTag;
				}
			}

                }
            }
            initctrlenter();
            HideAjaxIndicator();
            
        }
    }
}

AjaxObject = function()
{
    this.OnSuccess = function()
    {
        xmldoc = this.GetResponseXML();
        //alert(http.responseText);
        if (!xmldoc) 
            return;
	if (typeof apply_responce == "function")
        	apply_responce(xmldoc, this.nAjaxWidth, this.nAjaxHeight, 0, this.nAjaxXOffset, this.nAjaxYOffset);
        
    };
    
    this.GetData = function(action, vars, sObject, newWidth, newHeight, newXOffset, newYOffset)
    {
        this.InitializeRequest('POST', action, true);
        vars = vars + '&mdx0n=1';
        this.Commit(vars);
        this.nAjaxWidth = newWidth;
        this.nAjaxHeight = newHeight;
        this.nAjaxXOffset = newXOffset;
        this.nAjaxYOffset = newYOffset;
        ajaxcounter++;
    };
};

function AjaxSendRequest(action, vars, sObject, newWidth, newHeight, newXOffset, newYOffset)
{
    if (vars) 
        vars = vars + '&object=' + sObject;
    else 
        vars = 'object=' + sObject;
	 
    if (!newWidth) 
        newWidth = 347;
    if (!newHeight) 
        newHeight = 210;
    if (!newXOffset) 
        newXOffset = 0;
    if (!newYOffset) 
        newYOffset = 0;
    
    AjaxObject.prototype = new ajax();
    myObject = new AjaxObject();
    myObject.GetData(action, vars, sObject, newWidth, newHeight, newXOffset, newYOffset);
    if (action.indexOf('imreceive') <= 0) 
        ShowAjaxIndicator();
}

function AjaxSendPOST(action, form, sObject, newWidth, newHeight, newXOffset, newYOffset)
{
    vars = '';
    for (i = 0; i < window.document.forms[form].elements.length; i++) 
    {
        elem = window.document.forms[form].elements[i];
        if (((elem.type == 'checkbox') || (elem.type == 'radio')) && elem.checked != true) 
            continue;
        vars = vars + '&' + elem.name + '=' + encodeURIComponent(elem.value);
    }
    if (vars) 
        vars = vars + '&object=' + sObject;
    else 
        vars = 'object=' + sObject;
    
    if (!newWidth) 
        newWidth = 347;
    if (!newHeight) 
        newHeight = 210;
    if (!newXOffset) 
        newXOffset = 0;
    if (!newYOffset) 
        newYOffset = 0;
    ;
    
    AjaxObject.prototype = new ajax();
    myObject = new AjaxObject();
    myObject.GetData(action, vars, sObject, newWidth, newHeight, newXOffset, newYOffset);
    ShowAjaxIndicator();
}
//ru
error_messages = 
{
	'formitem': 
	{
		'category': 'Вы не выбрали &quot;Категорию&quot;',
		'title': 'Заполните поле &quot;Что это&quot;',
		'fulltitle': 'Заполните поле &quot;Название&quot;',
		'currencyid': 'Выберите валюту',
		'zametka': 'Вы не добавили комментарий!',
		'nodata': 'Нужно выбрать дату приобретения!'
	},
	
	'formzametka': 
	{
		'zametka': 'Вы не добавили комментарий!',
		'tag': 'Вы не выбрали &quot;Тэг&quot;'
	},
	
	'formlogin': 
	{
		'login': 'Заполните поле &quot;Логин&quot;',
		'password': 'Введите &quot;Пароль&quot;'
	},
	
	'formregistration': 
	{
		'login': 'Заполните поле &quot;Логин&quot;',
		'password': 'Введите &quot;Пароль&quot;',
		'confpassword': 'Заполните поле &quot;Повторите пароль&quot;',
		'country': 'Заполните поле &quot;Страна&quot;',
		'countrybad': 'Заполните поле &quot;Страна&quot; корректно',
		'town': 'Заполните поле &quot;Населенный пункт&quot;',
		'townbad': 'Заполните поле &quot;Населенный пункт&quot; корректно',
		'captcha': 'Введите код с картинки',
		'email': 'Введите E-mail',
		'agree': 'Не забудьте согласиться с правилами!',
		'interests': 'Не заполнены интересы!',
		'newpassword': 'Заполните поле &quot;Новый пароль&quot;',
		'nodata': 'Нужно ввести дату рождения!',
		'sex': 'Не выбран пол!',
		'edu': 'Не выбрано образование!',
		'interests': 'Не заполнены интересы!'

	},
	
	'formupload': 
	{
		'country': 'Заполните поле &quot;Страна&quot;',
		'login': 'Заполните поле &quot;Логин&quot;',
		'newpassword': 'Заполните поле &quot;Новый пароль&quot;',
		'confpassword': 'Заполните поле &quot;Повторите пароль&quot;',
		'town': 'Заполните поле &quot;Населенный пункт&quot;',
		'nofile': 'Не выбран файл для закачки',
		'nodata': 'Нужно ввести дату рождения!',
		'sex': 'Не выбран пол!',
		'edu': 'Не выбрано образование!',
		'interests': 'Не заполнены интересы!',
		'email': 'Не заполнен E-mail!'
	},

	'formopenid':
	{
		'openid_url': 'OpenID введен неверно!'
	},

	'exportprofile': 
	{
		'title': 'Не введено название профиля'
	},

	'formresponse': 
	{
		'tag': 'Не выбран тег комментария. Например &quot;Вопрос&quot; или &quot;Совет&quot;'
	},

	'formoptions':
	{
		'email': 'Не введен E-mail',
		'notequalpasswords': 'Введенные пароли не совпадают',
		'oldpassword': 'Требуется ввести старый (текущий) пароль'
	}
};
//drag
// Determine browser and version.

function Browser() {

  var ua, s, i;

  this.isIE    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
  
  this.isIE = true;
  this.version = parseFloat(ua.substr(i + s.length));
  return;
  
}

// Global object to hold drag information.

var dragObj = new Object();
dragObj.zIndex = 0;
var dragID = '';

function dragStart(event, id) {

  var el;
  var x, y;

	dragID = id;

  // If an element id was given, find it. Otherwise use the element being
  // clicked on.
  
  obj = SfindObj(id);
  obj.style.cursor = 'move';

  if (id)
    dragObj.elNode = document.getElementById(id);
  else {
    if (browser.isIE)
      dragObj.elNode = window.event.srcElement;
    if (browser.isNS)
      dragObj.elNode = event.target;

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }
  
  

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Save starting positions of cursor and element.

  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;

  // Update element's z-index.

  //dragObj.elNode.style.zIndex = ++dragObj.zIndex;

  // Capture mousemove and mouseup events on the page.

  if (browser.isIE) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS) {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {

  var x, y;

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Move drag element by the same amount the cursor has moved.

  dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";

  if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS)
    event.preventDefault();
}

var coords = new Array();

function dragStop(event) {
	target=window.document;
	nScrollTop = target.body.scrollTop;

	/*obj = SfindObj('ajax1');obj.style.cursor = 'default';
	obj = SfindObj('ajax1_1');obj.style.cursor = 'default';
	obj = SfindObj('ajax2');obj.style.cursor = 'default';
	obj = SfindObj('ajax2_1');obj.style.cursor = 'default';
	obj = SfindObj('ajax3');obj.style.cursor = 'default';
	obj = SfindObj('ajax4');obj.style.cursor = 'default';
	obj = SfindObj('ajaxim');obj.style.cursor = 'default';
	obj = SfindObj('ajaximchat');obj.style.cursor = 'default';*/
	
	//return cursor
	dragObj.elNode.style.cursor = 'default';
	//coords[dragID+'_x'] = dragObj.elNode.style.left;
	//coords[dragID+'_y'] = dragObj.elNode.style.top;
	if(vldnotb)
	{
		SetCookie('coords_'+dragID+'_x', parseInt(dragObj.elNode.style.left));
		SetCookie('coords_'+dragID+'_y', parseInt(dragObj.elNode.style.top) - nScrollTop);
	}
	//alert(coords[dragID+'_x']);

  // Stop capturing mousemove and mouseup events.

  if (browser.isIE) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  if (browser.isNS) {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
}
//ajaxupload
/**
 *
 *  AJAX IFRAME METHOD (AIM)
 *  http://www.webtoolkit.info/
 *
 **/
AIM = 
{

    frame: function(c)
    {
    
        var n = 'f' + Math.floor(Math.random() * 99999);
        var d = document.createElement('DIV');
        d.innerHTML = '<iframe style="position:absolute;visibility:hidden;left:1px;top:1px;width:1px;height:1px;" src="about:blank" id="' + n + '" name="' + n + '" onload="AIM.loaded(\'' + n + '\')"></iframe>';
        document.body.appendChild(d);
        
        var i = document.getElementById(n);
        
        if(!vldnotb) i.addEventListener("load", function(){AIM.loaded(n)}, true);
                
        if (c && typeof(c.onComplete) == 'function') 
        {
            i.onComplete = c.onComplete;
        }
        return n;
    },
    
    form: function(f, name)
    {
        f.setAttribute('target', name);
    },
    
    submit: function(f, c)
    {
        AIM.form(f, AIM.frame(c));
        if (c && typeof(c.onStart) == 'function') 
        {
            return c.onStart();
        }
        else 
        {
            return true;
        }
    },
    
    loaded: function(id)
    {
        var i = document.getElementById(id);
        if (i.contentDocument) 
        {
            var d = i.contentDocument;
        }
        else 
            if (i.contentWindow) 
            {
                var d = i.contentWindow.document;
            }
            else 
            {
                var d = window.frames[id].document;
            }
            
        if (d.location.href == "about:blank") 
        {
            return;
        }
        
        if (typeof(i.onComplete) == 'function') 
        {
					i.onComplete(d.body.innerHTML);
        }
    }
    
};

function startCallback()
{
    // make something useful before submit (onStart)
    if (obj = SfindObj('fileloading')) 
        obj.src = '/i/loading.gif';
    window.document.forms['formupload'].submit.disabled = true;
    window.document.forms['formupload'].submit.value = 'Ждите...';
    return true;
}

function completeCallback(response)
{
    // make something useful after (onComplete)
    //document.getElementById('nr').innerHTML = parseInt(document.getElementById('nr').innerHTML) + 1;
   if (obj = SfindObj('profileavatar')) 
   {
   	 	//HideClear('ajax1_1');
		obj.innerHTML = response;

		obj = SfindObj('ajax1_1');
		obj.innerHTML = '';
		obj.style.visibility = '';
		obj.style.left = '-5000px';
		obj.style.top = '-5000px';

   }
   else 
   {
   	if (obj = SfindObj('photogallery')) 
   	{
   		obj.innerHTML = response;
   		obj.style.display = 'block';

		obj = SfindObj('photogallerycountcopy');
		if (obj) {
			obj1 = SfindObj('photogallerycount');
			if (obj1)
				obj1.innerHTML = obj.innerHTML;
		}

   	}
   	if (obj = SfindObj('fileloading')) 
   		obj.src = '/i/dot.gif';
   	if (obj = SfindObj('addimagehttp')) 
   		obj.value = 'http://';
   	if (obj = SfindObj('addimagecomment')) 
   		obj.value = '';
   	
   	if (element = SfindObj('uploadform')) 
   	{
   		children = element.childNodes;
   		for (var i = 0; i < children.length; i++) 
   		{
   			if (children[i].getAttribute('name') == 'imgupl') 
   				element.removeChild(children[i]);
   		}
   	}
   	
   	browse = window.document.createElement("input");
   	browse.setAttribute("type", "file");
   	browse.setAttribute("name", "imgupl");
   	browse.name = "imgupl";
   	browse.setAttribute("class", "fileinput");
   	browse.className = "fileinput";
   	element.appendChild(browse);
   	
   	window.document.forms['formupload'].submit.disabled = false;
   	window.document.forms['formupload'].submit.value = 'Разместить';
   }
	
}
//ctrlenter
function on_ctrl_enter(e)
{
	
  if(e.ctrlKey && e.keyCode == 13)
  {
	/*e.preventDefault();
	e.stopPropagation();*/
	if (e.target) targ = e.target;
        else if (e.srcElement) targ = e.srcElement;
	var form = targ.form;
	if( form && (!form.onsubmit || form.onsubmit.call( form ) !== false) )
	{
		form.submit();
	}
  }
}

function install_keyhandler(a)
{
	try {
		a.addEventListener("keypress", on_ctrl_enter, false);
	}
	catch (error) {
		try {
			a.attachEvent('onkeyup',on_ctrl_enter);
		}
		catch (error) {
		}
	}
}

function initctrlenter () {
	var a = document.getElementsByTagName("textarea");
	for(i=0; i < a.length; i++) {
		install_keyhandler(a[i]);
	}
	var a = document.getElementsByTagName("input");
	for(i=0; i < a.length; i++) {
		typeis = a[i].getAttribute('type');
		if ((typeis == 'text') || (typeis == 'password'))
			install_keyhandler(a[i]);
	}
}

function CountSymb () {
	mainobj=SfindObj('malobukof');
	if (mainobj) {
		nCurrentTag = document.forms['formresponse'].tag.value;
		//s = elem.value;
		s = document.forms['formresponse'].response.value;
		pattern = new RegExp("[^a-zA-ZА-Яа-я0-9]", "g");
		s = s.replace(pattern, '');
		nLength = s.length;
		nMinLength = 40;
	if (nCurrentTag) {
			aMaxLength = new Array();
			aMaxLength[1] = 0; //вопрос
			aMaxLength[2] = 50; //достоинства
			aMaxLength[3] = 50; //история покупки
			aMaxLength[10] = 35; //критерии выбора
			aMaxLength[11] = 50; //мнение
			aMaxLength[4] = 50; //недостатки
			aMaxLength[9] = 100; //обзор
			aMaxLength[5] = 50; //описание
			aMaxLength[6] = 20; //поломка
			aMaxLength[7] = 50; //ремонт
			aMaxLength[8] = 0; //совет
			nMinLength = aMaxLength[nCurrentTag];
		}
	
		if (nLength >= nMinLength) { //достаточно
			sWarn = '';
			obj=SfindObj('respsubok');
			if (obj)
				obj.className = 'greenbutton';
			obj=SfindObj('respsubadd');
			if (obj)
				obj.className = 'bluebutton';
		}
		else {
			if (nMinLength > 0) {
				sWarn = 'Символов в комментарии ' + nLength + ', а нужно ' + nMinLength+'.';
				obj=SfindObj('respsubok');
				if (obj)
					obj.className = 'graybutton';
				obj=SfindObj('respsubadd');
				if (obj)
					obj.className = 'graybutton';
			}
			else {
				sWarn = '';
			}
		}
		mainobj.innerHTML = sWarn;
		return sWarn;
	}
}

function SwitchScrolls () {
	elements=window.document.getElementsByTagName('div');
	noscrolls = parseInt(GetCookie('ns'));

	if (!noscrolls) {
		SetCookie('ns', 1);
		scswo = SfindObj('scsw1');
		if (scswo) {
			scswo.src='/i/gui/up.png';
			scswo.title='Свернуть';
		}
		scswo = SfindObj('scsw2');
		if (scswo) {
			scswo.src='/i/gui/up.png';
			scswo.title='Свернуть';
		}
	}
	else {
		SetCookie('ns', 0);
		scswo = SfindObj('scsw1');
		if (scswo) {
			scswo.src='/i/gui/down.png';
			scswo.title='Развернуть';
		}
		scswo = SfindObj('scsw2');
		if (scswo) {
			scswo.src='/i/gui/down.png';
			scswo.title='Развернуть';
		}
	}

	for(var i = 0; i < elements.length; i++) {
		obj=elements.item(i);
		if (obj.className == 'tags') {
			if (!noscrolls) {
				try {
					obj.style.overflow = 'none';
				}
				catch(e) {
					obj.style.overflowy = 'none';
				}
				obj.style.height='auto';
			}
			else {
				SetCookie('ns', 0);
				try {
					obj.style.overflow = 'auto';
				}
				catch(e) {
					obj.style.overflowy = 'auto';
				}
				obj.style.height='305px';
			}
		}
	}
}

function ScrollComm(Dir, Val)  {
	scswo = SfindObj('commentsblock');
	scswo.scrollLeft = Dir*Val;
}

function ShowJSVPreview (id) {
	obj=SfindObj('vidc_c');
	nColumns = parseInt(obj.value);if (nColumns <=0) {nColumns=1;obj.value=1;}
	obj=SfindObj('vidc_r');
	nRows = parseInt(obj.value);if (nRows <=0) {nRows=1;obj.value=1;}
	/*AjaxSendRequest('/export/jspreview', 'rows='+nRows+'&cols='+nColumns+'&id='+id, 'exportjspreview');*/
	AjaxSendPOST('/export/vidgetjs', 'vidgetjsform', 'ajaxnull');
}

function FillFT (sData) {
	f=document.forms["formitem"];
	f.fulltitle.value=sData;
	HideClear("ajax2_1");
	v="";
	if(f.fulltitle.value)
		v=" «"+f.fulltitle.value+"»";
	ChangeWindowTitle(f.title.value+v);
}

function GatherParams () {
	sResult = '';
	obj=SfindObj('paramform');
	aAlready = new Array();
	elements=obj.getElementsByTagName('span');
	for(var i = 0; i < elements.length; i++) {
		id=elements[i].getAttribute('id');
		if (id.indexOf('paramvalue_') != -1) {
			aTemp = id.split('_');
			id=aTemp[1];
			sResult = sResult + '!n!' + id + '!=!' + elements[i].innerHTML;
			aAlready[id] = 1;
		}
	}

	elements=obj.getElementsByTagName('input');
	for(var i = 0; i < elements.length; i++) {
		id=elements[i].name;
		if (id.indexOf('params[') != -1) {
			aTemp = id.split('[');
			id=parseInt(aTemp[1]);
			if (elements[i].value && !aAlready[id])
				sResult = sResult + '!n!' + id + '!=!' + elements[i].value;
		}
	}

	window.document.forms['formitem'].paramslistvalues.value = sResult;
}
