var OK = false;
var remove_func;
var set_focus = '';
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isIE6 = (navigator.userAgent.indexOf("MSIE 6.0") != -1) ? true : false;
var isIE7 = (navigator.userAgent.indexOf("MSIE 7.0") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
var SlideCatalog = false;

eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('u 8(){7 t=5;t.1a=x;t.R=0;t.Q=x;t.1R=x;t.S=3e;t.2h="3f";t.1i=x;t.1j=T;t.F=x;t.1B="3g";t.D=x;t.U=[];t.12=x;t.1k={2i:"3h 1C 2j 3i: L=%, 3j=%",2k:"3k 3l, <E> 1S 2l a 3m 3n 2j 1D 1l 3o.",2m:"1T 3p 3q 3r 3s 1U 3t!\\n%",1E:"V 13 3u 3v 2n O W 2o (3w 1U 3x 3y % 3z)",2p:"3A F: %",2q:"3B 3C 3D 3E 3F, 3G 3H 8.14 3I",2r:"V 3J a F 3K 3L 3M 1l 2o. 3N 1V:\\n%",1W:"3O 1m() 3P 2s 3Q O 1l % F."};t.1n=u(){O(5){6(D&&D.1n){D.1n()}1X();6(R==0){9}6(R==1&&!D){R=0;9}15(4,P)}};t.1Y=u(a,b,c,d,f){O(5){1b{6(1c.2t.3R.1F(I M("[&?]"+1B+"=([^&?]*)"))||1c.3S.1F(I M("(?:;|^)\\\\s*"+1B+"=([^;]*)"))){b+=(b.X("?")>=0?"&":"?")+1B+"="+5.1d(M.$1)}}1e(e){}12={B:(a||"").1G(),y:b,3T:c,1Z:d!=x?d:"",20:f!=x?f:""};D=x;15(1,P);9 P}};t.21=u(a){6(!5.R){9}5.15(1,P);5.D=x;7 b=[];7 c=[];6(!5.22(a,x,b,c)){9}7 d=x;6(5.1j&&!c.A){d=5.12.1Z+":"+5.12.20+"@"+5.12.y+"|"+b+"#"+5.12.B;7 e=8.23[d];6(e){5.24(e[0],e[1]);9 T}}7 f=(5.F||"").25();6(f&&!8.14[f]){9 5.Y("2p",f)}7 g=[];7 h=8.14;J(7 i 1D h){7 j=h[i].F;6(!j){1H}6(f&&i!=f){1H}7 k=I j(5);8.1f(k,5.12);8.1f(k,{N:b.2u("&"),K:c,G:(I 3U().3V())+""+8.2v++,2w:d,Z:x});7 l=k.1o();6(!l){5.D=k;8.1p[k.G]=5;9 P}6(!f){g[g.A]="- "+i.1G()+": "+5.26(l)}C{9 5.Y(l)}}9 i?5.Y("2r",g.2u("\\n")):5.Y("2q")};t.1q=u(){O(5){9 D&&D.1q?D.1q():[]}};t.1r=u(a){O(5){9 D&&D.1r?D.1r():[]}};t.1m=u(a,b){O(5){U[U.A]=[a,b]}};t.24=u(a,b){O(5){6(1j&&D){8.23[D.2w]=[a,b]}6(a!==x||b!==x){S=4;Q=1R=a;1i=b}C{S=3W;Q=1R=1i=x}15(2);15(3);15(4);1X()}};t.26=u(b){7 i=0,p=0,16=5.1k[b[0]];3X((p=16.X("%",p))>=0){7 a=b[++i]+"";16=16.2x(0,p)+a+16.2x(p+1,16.A);p+=1+a.A}9 16};t.Y=u(a){a=5.26(2y(a)=="2z"?3Y:a);a="8: "+a;6(!H.1I){1J a;}C{6((I 1I(1,"2A")).3Z=="2A"){1J I 1I(1,a);}C{1J I 1I(a);}}};t.22=u(a,b,c,d){6(b==x){b=""}6(a 27 2C){7 f=T;J(7 k 1D a){7 v=a[k];6(v 27 40){1H}7 g=b?b+"["+5.1d(k)+"]":5.1d(k);7 h=v&&v.1K&&v.1K.2D&&v.1L;6(h){7 i=v.1L.1G();6(i=="1C"){f=P}C{6(i=="2E"||i=="41"||i=="42"){}C{9 5.Y("2i",(e.L||""),e.1L)}}d[d.A]={L:g,e:v}}C{6(v 27 2C){5.22(v,g,c,d)}C{6(v===x){1H}c[c.A]=g+"="+5.1d(""+v)}}6(f&&d.A>1){9 5.Y("2k")}}}C{c[c.A]=a}9 P};t.1X=u(){7 a=5.D;6(!a){9}8.1p[a.G]=T;7 b=a.Z;6(!b){9}a.Z=x;7 c=u(){b.1K.2F(b)};8.1s(c,50)};t.15=u(s,a){O(5){6(a){S=2h=1i=x;Q=""}R=s;6(1a){1a()}}};t.1d=u(s){9 1d(s).43(I M("\\\\+","g"),"%2B")}}8.2v=0;8.17=44;8.23={};8.1p={};8.14={};8.2G=u(){};8.1g={s:H.1s,c:H.2H};8.1s=u(a,b){H.18=8.1g.s;6(2y(a)=="2z"){c=H.18(a,b)}C{7 c=x;7 d=u(){a();28 8.1g[c]};c=H.18(d,b);8.1g[c]=d}H.18=x;9 c};8.2H=u(a){H.18=8.1g.c;28 8.1g[a];7 r=H.18(a);H.18=x;9 r};8.2n=u(a,b,c,d){7 e=I 5();e.1j=!d;e.1a=u(){6(e.R==4){c(e.1i,e.Q)}};7 f=x;6(a.1F(/^((\\w+)\\.)?(W|19)\\s+(.*)/i)){e.F=M.$2?M.$2:x;f=M.$3;a=M.$4}e.1Y(f,a,P);e.21(b)};8.29=u(d){7 a=5.1p[d.G];28 5.1p[d.G];6(a){a.24(d.45,d.46)}C{6(a!==T){1J"29(): 47 48 G: "+d.G;}}};8.1f=u(a,b){J(7 k 1D b){a[k]=b[k]}};8.14.2I={F:u(d){8.1f(d.1k,{2J:"V 13 1h 2K 2L F: 1t 2M",2N:"V 13 1h 1u 1o 2a 49 2O 4a %",2P:"V 13 1h F 2K 2L F, 19 B: 4b 4c 1U 1t 2M, 4d 1u 2s O 4e 4f",2Q:"V 13 1h F: 2R E 11 2S 2T 2U 1V 1t 2V"});5.1o=u(){6(5.K.A){9["2Q"]}6(5.y.1F(I M("^([a-z]+)://([^\\\\/]+)(.*)","i"))){6(M.$2.25()==1c.2t.4g.25()){5.y=M.$3}C{9["2N",M.$2]}}7 a=x;6(H.1h){1b{a=I 1h()}1e(e){}}C{6(H.1M){1b{a=I 1M("4h.2W")}1e(e){}6(!a){1b{a=I 1M("4i.2W")}1e(e){}}}}6(!a){9["2J"]}7 b=H.1M||a.1m;6(!5.B){5.B=b?"19":"W"}6(5.B=="W"){6(5.N){5.y+=(5.y.X("?")>=0?"&":"?")+5.N}5.N="";6(5.y.A>8.17){9["1E",8.17]}}C{6(5.B=="19"&&!b){9["2P"]}}5.y+=(5.y.X("?")>=0?"&":"?")+"8="+(d.1j?"0":5.G)+"-2I";7 c=5.G;a.1a=u(){6(a.R!=4){9}a.1a=8.2G;d.S=x;1b{d.S=a.S;d.Q=a.Q}1e(e){}6(!d.S){9}1b{4j("8.2b = u(G) { 7 d = "+d.Q+"; d.G = G; 8.29(d); }")}1e(e){9 d.Y("2m",d.Q)}8.2b(c);8.2b=x};a.1Y(5.B,5.y,P,5.1Z,5.20);6(b){J(7 i=0;i<d.U.A;i++){a.1m(d.U[i][0],d.U[i][1])}a.1m("4k-4l","4m/4n-4o")}a.21(5.N);5.Z=x;5.1v=a;9 x};5.1q=u(){9 5.1v.1q()};5.1r=u(a){9 5.1v.1r(a)};5.1n=u(){5.1v.1n();5.1v=x}}};8.14.2c={F:u(e){8.1f(e.1k,{2X:"V 13 1w F: 4p 4q 4r W B",2Y:"V 13 1w F: 2R E 11 2S 2T 2U 1V 1t 2V"});5.1o=u(){6(5.N){5.y+=(5.y.X("?")>=0?"&":"?")+5.N}5.y+=(5.y.X("?")>=0?"&":"?")+"8="+5.G+"-"+"2c";5.N="";6(!5.B){5.B="W"}6(5.B!=="W"){9["2X"]}6(5.K.A){9["2Y"]}6(5.y.A>8.17){9["1E",8.17]}6(e.U.A){9["1W","1w"]}7 a=5,d=1c,s=x,b=d.2d;6(!H.4s){5.Z=s=d.1x("1w");7 c=u(){s.2Z="1T";6(s.1y){s.1y("1N",a.y)}C{s.1N=a.y}b.2e(s,b.1z)}}C{5.Z=s=d.1x("4t");s.1O.4u="30";b.2e(s,b.1z);s.31="4v J 32.<s"+"4w></"+"2c>";7 c=u(){s=s.4x("1w")[0];s.2Z="1T";6(s.1y){s.1y("1N",a.y)}C{s.1N=a.y}}}8.1s(c,10);9 x}}};8.14.E={F:u(t){8.1f(t.1k,{33:"34 \\"%\\" 4y 1t 35 1u 4z E!",36:"34 \\"%\\" 4A 1u a 2O E. 4B 11 1S 35 1u 1l 4C E!",37:"4D \\"1A\\" 4E 1l E 1S 2l \\"%\\" (J 32), \\"%\\" 4F."});5.1o=u(){7 g=5;6(!g.B){g.B="19"}g.y+=(g.y.X("?")>=0?"&":"?")+"8="+g.G+"-"+"E";6(t.U.A){9["1W","1C"]}6(g.B=="W"){6(g.N){g.y+=(g.y.X("?")>=0?"&":"?")+g.N}6(g.y.A>8.17){9["1E",8.17]}7 p=g.y.2f("?",2);g.y=p[0];g.N=p[1]||""}7 h=x;7 j=T;6(g.K.A){6(g.K[0].e.1L.1G()=="1C"){h=g.K[0].e;j=P;g.K=[]}C{h=g.K[0].e.E;J(7 i=0;i<g.K.A;i++){7 e=g.K[i].e;6(!e.E){9["33",e.L]}6(e.E!=h){9["36",e.L]}}}6(g.B=="19"){7 l="38/E-2a";7 m=(h.1P.39&&h.1P.39.4G)||(h.1P.1A&&h.1P.1A.3a)||h.1A;6(m!=l){9["37",l,m]}}}7 d=h&&(h.4H||h.1c)||1c;7 o="4I"+g.G;7 s=g.Z=d.1x("4J");s.1O.4K="4L";s.1O.4M="2g";s.31=(h?"":"<E"+(g.B=="19"?" 1A=\\"38/E-2a\\" B=\\"4N\\"":"")+"></E>")+"<3b L=\\""+o+"\\" G=\\""+o+"\\" 1O=\\"4O:3c; 4P:3c; 4Q:2g; 4R:30\\"></3b>";6(!h){h=g.Z.4S}d.2d.2e(s,d.2d.1z);7 q=u(e,a){7 b=[];7 c=e;6(e.1Q){7 c=d.1x("E");c.1Q(e,T)}J(7 i=0;i<a.A;i++){7 k=a[i][0],v=a[i][1];b[b.A]=[k,c.4T(k)];c.1y(k,v)}6(e.1Q){e.1Q(c,T)}9 b};7 r=u(){4U.4V=8;7 a=[];6(!j){J(7 i=0,n=h.11.A;i<n;i++){a[i]=h.11[i].L;h.11[i].L=""}}7 b=g.N.2f("&");J(7 i=b.A-1;i>=0;i--){7 c=b[i].2f("=",2);7 e=d.1x("2E");e.4W="2g";e.L=3d(c[0]);e.3a=c[1]!=x?3d(c[1]):"";h.2D(e)}J(7 i=0;i<g.K.A;i++){g.K[i].e.L=g.K[i].L}7 f=q(h,[["4X",g.y],["B",g.B],["4Y",x],["4Z",o]]);h.51();q(h,f);J(7 i=0;i<b.A;i++){h.1z.1K.2F(h.1z)}6(!j){J(7 i=0,n=h.11.A;i<n;i++){h.11[i].L=a[i]}}};8.1s(r,52);9 x}}};',62,313,'|||||this|if|var|JsHttpRequest|return|||||||||||||||||||||function|||null|url||length|method|else|_ldObj|form|loader|id|window|new|for|queryElem|name|RegExp|queryText|with|true|responseText|readyState|status|false|_reqHeaders|Cannot|GET|indexOf|_error|span||elements|_openArgs|use|LOADERS|_changeReadyState|msg|MAX_URL_LEN|JsHttpRequest_tmp|POST|onreadystatechange|try|document|escape|catch|extend|TIMEOUTS|XMLHttpRequest|responseJS|caching|_errors|the|setRequestHeader|abort|load|PENDING|getAllResponseHeaders|getResponseHeader|setTimeout|not|to|xr|SCRIPT|createElement|setAttribute|lastChild|enctype|session_name|FORM|in|url_too_long|match|toUpperCase|continue|Error|throw|parentNode|tagName|ActiveXObject|src|style|attributes|mergeAttributes|responseXML|must|JavaScript|is|are|no_headers|_cleanup|open|username|password|send|_hash2query|CACHE|_dataReady|toLowerCase|_l|instanceof|delete|dataReady|data|_tmp|script|body|insertBefore|split|hidden|statusText|inv_form_el|element|must_be_single_el|be|js_invalid|query|request|unk_loader|no_loaders|no_loader_matched|work|location|join|COUNT|hash|substring|typeof|string|test||Object|appendChild|INPUT|removeChild|_dummy|clearTimeout|xml|xml_no|or|ActiveX|supported|xml_no_diffdom|different|xml_no_headers|xml_no_form_upl|direct|using|and|uploading|implemented|XMLHTTP|script_only_get|script_no_form|language|none|innerHTML|IE|form_el_not_belong|Element|belong|form_el_belong_diff|form_el_inv_enctype|multipart|encType|value|iframe|0px|unescape|200|OK|PHPSESSID|Invalid|detected|tag|If|used|single|HTML|list|code|generated|by|backend|invalid|so|long|URL|larger|than|bytes|Unknown|No|loaders|registered|at|all|please|check|array|find|which|may|process|Notices|Method|cannot|together|search|cookie|asyncFlag|Date|getTime|500|while|arguments|description|Function|TEXTAREA|SELECT|replace|2000|text|js|unknown|pending|from|domain|headers|setting|needed|encodings|correctly|hostname|Microsoft|Msxml2|eval|Content|Type|application|octet|stream|it|supports|only|opera|SPAN|display|Workaround|cript|getElementsByTagName|does|any|belongs|All|same|Attribute|of|given|nodeValue|ownerDocument|jshr_i_|DIV|position|absolute|visibility|post|width|height|overflow|border|firstChild|getAttribute|top|JsHttpRequestGlobal|type|action|onsubmit|target||submit|100'.split('|'),0,{}))

function $p(e){ return parent.parent.document.getElementById(e); }
close_win = function(e) {
if ($p('win')) parent.parent.win.close($p('win'));
else parent.parent.location.href = e.href;
}

function $(id){ return document.getElementById(id); }

function _key(event)	{

if (event) {
	 var k = event.keyCode;
	 if(k==0) { k=event.charCode; return false; }
	 if(k==13 && $('loading-box').style.display == 'block')  {		    $('loading-box').style.display = 'none';
		    if (OK==true) remove_func();
		    if (set_focus != '' && set_focus != undefined) {
		    	set_focus.focus();
				if (set_focus!=null && set_focus.className == 'inp_text') set_focus.className = 'inp_text_err';
		    	}
		    return false;
		    }
	 if(k==27) {
		    if ($('loading-box').style.display == 'block') $('loading-box').style.display = 'none';
		    if (set_focus != '' && set_focus != undefined) {
		    	set_focus.focus();
				if (set_focus!=null && set_focus.className == 'inp_text') set_focus.className = 'inp_text_err';
		    	}
		   return false;
		   }
	 if(k==37 && event.ctrlKey && $('prev_page'))  {
		   // left
		    if ($('prev_page').href.length>0 && SlideCatalog === false) location.href = $('prev_page').href;
		    else if (SlideCatalog === true && /\/([0-9]+)\/$/i.test($('prev_page').href)) load_watch(RegExp.$1);
	 }
	 if(k==39 && event.ctrlKey && $('next_page')) {
		   // right
		   if ($('next_page').href.length>0 && SlideCatalog === false) location.href = $('next_page').href;
		   else if (SlideCatalog === true && /\/([0-9]+)\/$/i.test($('next_page').href)) load_watch(RegExp.$1);
	 }
}

}

function show_message(text){
	if (!$('loading-box')) return false;
	if (text==undefined) text = 'Обработка данных';
	var top = (document.body.scrollTop>0) ? document.body.scrollTop : document.documentElement.scrollTop;
	$('loading-box').style.width = '270px';
//	$('loading-box').style.height = '60px';
	$('loading-box').style.height = 'auto';
	$('loading-size').style.paddingRight = '0px';
	$('loading-text').style.backgroundImage = 'none';
	$('loading-text').style.padding = '0px';
	$('loading-box').style.textAlign = 'center';
	$('loading-box').style.display = 'block';
   	$('loading-actions').style.display = 'none';
	if (self.screen) $('loading-box').style.top = (parseInt(top,10)+(screen.height/2)-200)+'px';
	else $('loading-box').style.top = (parseInt(top,10)+(document.body.clientHeight/2)-90)+'px';
	$('loading-box').style.left = ((document.body.clientWidth/2)-100)+'px';
	$('loading-img').style.display = '';
	$('loading-text').innerHTML = text+', пожалуйста подождите...';
}

function close_message(status, text, focus, action){
	if (!$('loading-box')) return false;
	//alert('IE='+isIE+', IE6='+isIE6+', IE7='+isIE7+', WIN='+isWin+', Opera='+isOpera+'; AGENT='+navigator.userAgent)

	if (status==undefined && $('loading-box') && $('loading-box').style.display == 'none') return false;
        OK = false;
	$('loading-box').style.display = 'block';
	$('loading-box').style.textAlign = 'left';

	if (isOpera || isIE) {
		$('loading-box').style.width = '400px';
		$('loading-box').style.height = 'auto';
	}
	else {
		$('loading-box').style.width = 'auto';
		$('loading-box').style.height = 'auto';
	}

	$('loading-actions').innerHTML = '';
   	$('loading-actions').style.display = 'none';
	$('loading-text').style.paddingLeft = '27px';
	$('loading-size').style.paddingRight = '27px';
	$('loading-text').style.paddingTop = (isIE) ? '10px' : '20px';

	if (text==undefined && status!='error') text = 'Информация';
	if (action==undefined) action = '';

	if (status==undefined) {
		$('loading-box').style.display = 'none';
		return false;
		}
	else if (status=='info') {
		$('loading-img').style.display = 'none';
		//if (action) remove_func = new Function(action);
		$('loading-text').style.backgroundImage = '';
		$('loading-text').innerHTML = ''+text+'';
		$('loading-actions').innerHTML = '&nbsp;&nbsp;<a href="#" title="Закрыть (ESC)" onclick="$(\'loading-box\').style.display = \'none\'; if (set_focus != \'\') set_focus.focus(); return false;"><img class="image" src="/js/images/btn_close.png">&nbsp;<b>Закрыть</b></a>';
	    	$('loading-actions').style.display = '';

	} else if (status=='confirm') {
		OK = true;
		if (action) remove_func = new Function(action);
		$('loading-img').style.display = 'none';
		$('loading-text').style.backgroundImage = 'url(/js/images/icons/warning.png)';
		$('loading-text').innerHTML = ''+text+'';
		$('loading-actions').innerHTML = '&nbsp;&nbsp;<a href="#" title="Подтвердить действие (Enter)" onclick="$(\'loading-box\').style.display = \'none\'; if (OK==true) remove_func(); return false;"><img class="image" src="/js/images/btn_apply.png">&nbsp;<b>OK</b></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" title="Отменить действие (ESC)" onclick="$(\'loading-box\').style.display = \'none\'; return false;"><img class="image" src="/js/images/btn_close.png">&nbsp;<b>Отмена</b></a>';
	    	$('loading-actions').style.display = '';

	} else if (status=='basket') {
		$('loading-img').style.display = 'none';
		$('loading-text').style.backgroundImage = '';
		$('loading-text').innerHTML = ''+text+'';
		$('loading-actions').innerHTML = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/shopping_cart/"><img class="image" src="/img/ico/add_basket.gif" alt="Перейти в корзину">&nbsp;<b>Перейти в корзину</b></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" title="Отменить действие (ESC)" onclick="$(\'loading-box\').style.display = \'none\'; return false;"><img class="image" src="/js/images/btn_close.png">&nbsp;<b>Закрыть</b></a>';
	    	$('loading-actions').style.display = '';

	} else if (status=='error') {
		$('loading-img').style.display = 'none';
		if (text==undefined) text = 'Произошла ошибка';
		$('loading-text').style.backgroundImage = 'url(/js/images/icons/error.png)';
		$('loading-text').innerHTML = ''+text+'';
	        $('loading-actions').style.display = '';
		$('loading-actions').innerHTML = '&nbsp;&nbsp;<a href="#" title="Закрыть (ESC)" onclick="$(\'loading-box\').style.display = \'none\'; if (set_focus != \'\') set_focus.focus(); return false;"><img class="image" src="/js/images/btn_close.png">&nbsp;<b>Закрыть</b></a>';
	}else if (status=='actions') {
		$('loading-img').style.display = 'none';
		if (text==undefined) text = 'Произошла ошибка';
		$('loading-text').style.backgroundImage = 'url(/js/images/icons/warning.png)';
		$('loading-text').innerHTML = ''+text+'';
	        $('loading-actions').style.display = '';
		$('loading-actions').innerHTML = '<input type="button" value="Отказаться от скидки" onclick="set_discount(0); $(\'loading-box\').style.display = \'none\';  if (set_focus != \'\') set_focus.focus(); return false;"> &nbsp; <input type="button"  onclick="$(\'loading-box\').style.display = \'none\'; if (set_focus != \'\') set_focus.focus(); return false;" value="Ввести правильный номер телефона">';
	}

	if ($('loading-box').offsetHeight>500){
		$('loading-box').style.height = '500px';
		$('loading-box').style.overflow = 'auto';
		}

	var new_height = $('loading-box').offsetHeight;
	var top = (document.body.scrollTop>0) ? document.body.scrollTop : document.documentElement.scrollTop;
	//$('loading-box').style.top = (parseInt(top,10)+(document.body.clientHeight/2)-(new_height/2)-30)+'px';
	var half_screen_height = document.body.clientHeight/2;
	if (isIE6) { half_screen_height = (screen.height>0) ? (screen.height/2)-parseInt(screen.height/8) : half_screen_height;  }
	$('loading-box').style.top = (parseInt(top,10)+(half_screen_height)-(new_height/2)-30)+'px';

	var new_width = $('loading-box').offsetWidth;
   	$('loading-box').style.left = ((document.body.clientWidth/2)-(new_width/2))+'px';
	if (focus!=undefined && $(focus)!=null) {
		    set_focus = $(focus);
        	if (set_focus!=null && set_focus.className == 'inp_text') set_focus.className = 'inp_text_err';
		}
	else set_focus = '';

	$('loading-box').focus();
	if (isIE) {
		$('loading-text').style.backgroundPosition = '0 12px';
 		reloadPage();
	}

}


// загрузить карточку часов
function load_watch(id) {
	var req = new JsHttpRequest();
	req.open(null, '/js/_ajax/load_watch.php', true);
	var data = { 'id': id };
        req.send(data);

	    show_message();

    	req.onreadystatechange = function() {
	//	if (req.responseText) alert(req.responseText);
		if (req.readyState == 4) {

    		if (req.responseJS.result) {
    			$('watch').innerHTML = req.responseJS.result;
			var watch_id = req.responseJS.watch_id;
	    		SlideCatalog = true;
	    		delCookieValues('lastopen', watch_id);
	    		saveCookieValues('lastopen', watch_id, 10, '/', 6);
	    		load_lastopen();
    			if (req.responseJS.navigation && $('navigation')) $('navigation').innerHTML = req.responseJS.navigation;
    			if (req.responseJS.meta_title) document.title = req.responseJS.meta_title;
    			if (req.responseJS.h1) {
					$('center').getElementsByTagName('h1')[0].innerHTML = req.responseJS.h1;
				   //document.title = req.responseJS.h1;
				}
    			$doc("#news_list").accessNews({headline : "#news_list", speed : "slow", slideBy : 3});
    		}
    		else location.href = location.href.replace(/\/([0-9]+)\/$/,'/'+id+'/');
    		close_message();

		}

   }
}

// ****************************************** //
// **** <<<<<< КОРЗИНА ПОЛЬЗОВАТЕЛЯ    ****** //
// ****************************************** //

function check_basket(){
	var result = true;
	if ($('empty_shopping_cart')!=null) result = ($('empty_shopping_cart').style.display == '') ? false : true;
	if (result == false) close_message('info', '<img class="image" src="/img/ico/add_basket.gif" alt="Корзина"> Ваша корзина пуста');
	return result;
}

// добавить позицию в корзину
function add_product(sid, catalog_id, id, price, action) {

  var req = new JsHttpRequest();
	req.open(null, '/js/_ajax/basket/add.php', true);
	var data = { 'sid': sid, 'catalog_id': catalog_id, 'id': id, 'price' : price };
        req.send(data);

	if (action!='купить') show_message('Добавление товара в корзину');

    	req.onreadystatechange = function() {
		if (req.readyState == 4) {
//		alert(req.responseText);

			var quantity = req.responseJS.quantity;
			var total_price = req.responseJS.total_price;

			if (quantity>0) {
				if ($('divbasket') != null) $('divbasket').style.display = '';
				if ($('empty_shopping_cart') != null) $('empty_shopping_cart').style.display = 'none';
				if ($('shopping_cart') != null) $('shopping_cart').style.display = '';
				if ($('quantity') != null) $('quantity').innerHTML = quantity;
				if ($('total_price') != null) $('total_price').innerHTML = total_price;
				if ($('ending') != null) $('ending').innerHTML = req.responseJS.end;
				//if ($('basket_'+id) != null) $('basket_'+id).src = '/img/buttons/p10.gif';
			}

			if (action == 'купить') window.location.href='/shopping_cart/';
			else close_message('basket','Товар добавлен в корзину<br>&nbsp;Приятных, Вам, покупок');

		}

   }
}

// удаление позиции из корзины
function remove_product(sid, id, catalog_id){
  var req = new JsHttpRequest();
	req.open(null, '/js/_ajax/basket/remove.php', true);
	var data = { 'sid': sid, 'id': id, 'catalog_id': catalog_id };
    req.send(data);

    show_message('Удаление товара');

    req.onreadystatechange = function() {
	if (req.readyState == 4) {

        var parent = $('tr_'+id).parentNode.id;
		removeElement(parent,'tr_'+id);
        if ($(parent)) {
        	var parent_table = $(parent).parentNode.id;
        	var trs = $(parent).getElementsByTagName('tr').length;
        	if (trs-1 == 0 && parent_table) $(parent_table).style.display = 'none';
        	}

			if ($('exist_'+id) && $('all_warning')) {
				$('all_warning').removeChild($('exist_'+id));
				if ($('all_warning').getElementsByTagName('b').length == 0) $('all_warning').style.display = 'none';
			}

			var quantity = req.responseJS.quantity;
			var total_price = req.responseJS.total_price;

			if (quantity>0) {					var ids = req.responseJS.ids;
					if (ids && $('recount_ids')!=null) $('recount_ids').value = ids;
					if ($('delivery_type')!=null) var delivery = $('delivery_type').value;
					if ($('t_price')!=null) $('t_price').innerHTML = total_price;
					if ($('price_delivery')) $('price_delivery').innerHTML = total_price;
					$('empty_shopping_cart').style.display = 'none';
					$('shopping_cart').style.display = '';
					if ($('quantity')!=null) $('quantity').innerHTML = quantity;
					if ($('total_price')!=null) $('total_price').innerHTML = total_price;
					if ($('ending')!=null) $('ending').innerHTML = req.responseJS.end;
					if ($('delivery_type')!=null) choose_delivery_type(delivery);
			}
			else {
					$('empty_shopping_cart').style.display = '';
					$('shopping_cart').style.display = 'none';
					$('whole_basket').innerHTML = '<br>Ваша корзина пуста';
					if ($('order_table')!=null) $('order_table').style.display = 'none';
					if ($('divbasket') != null) $('divbasket').style.display = 'none';
					if ($('whole_basket2') != null) $('whole_basket2').style.display = 'none';
				}

            close_message();
		}

   }
}
// сообщение об удалении
function remove_message(sid, p_id, c_id, name){
	remove_func = new Function("remove_product('"+sid+"', '"+p_id+"', '"+c_id+"');");
	close_message('confirm','Вы действительно хотите удалить "'+name+'" из корзины?');
}

// пересчитать сумму в корзине
function recount(sid){
  var req = new JsHttpRequest();

  var products = new Array();
  if ($('recount_ids')!=null) products = $('recount_ids').value.split(',');

  if (products.length>0) {  var j = 0, k = 0;
  var values = new Array();
  var products_id = new Array();
  var new_prices = new Array();

  for (i = 0; i<products.length; i++) if ($('quantity_'+products[i])!=null) {
	values[j] = $('quantity_'+products[i]).value;
	products_id[j] = products[i];
	j++;
	}

	req.open(null, '/js/_ajax/basket/recount.php', true);
	var data = { 'sid': sid, 'products_id': products_id, 'values': values };
        req.send(data);

  	show_message('Перерасчет количества товаров и суммы заказа');

	req.onreadystatechange = function(){		//$('debug').innerHTML = req.responseText;

		if (req.readyState == 4) {

				var quantity = req.responseJS.quantity;
				var total_price = req.responseJS.total_price;
				var total_prices = req.responseJS.new_prices;
				var product_prices = req.responseJS.product_prices;
				if ($('delivery_type')!=null) var delivery = $('delivery_type').value;

				if (quantity>0) {
					if ($('t_price')!=null) $('t_price').innerHTML = total_price;
					if ($('price_delivery')) $('price_delivery').innerHTML = total_price;
					$('empty_shopping_cart').style.display = 'none';
					$('shopping_cart').style.display = '';
					if ($('quantity')!=null) $('quantity').innerHTML = quantity;
					if ($('total_price')!=null) $('total_price').innerHTML = total_price;
					if ($('ending')!=null) $('ending').innerHTML = req.responseJS.end;
					if (delivery>0) choose_delivery_type(delivery);
					if (products.length>0)
						for (i = 0; i<products.length; i++) if ($('price_'+products[i])!=null && total_prices[k]) {
						if (total_prices[k]>0) $('price_'+products[i]).innerHTML = product_prices[k];
						if ($('summa_'+products[i])!=null) $('summa_'+products[i]).innerHTML = total_prices[k];
						k++;
						}

				}

				close_message();

		}
	 }
   }
}



function load_calendar(id,showtime){
showtime = (showtime == 'no') ? false : true;
var format = (showtime===true) ? "%Y-%m-%d %H:%M" : "%Y-%m-%d";
if ($(id))
	Calendar.setup({
		inputField:  id,
		button:      id,
		ifFormat:    format,
		firstDay:    1,
		timeFormat:  "24",
		showsTime:   showtime,
		weekNumbers: false
	});
}

function checkfio(e){
	e.value = e.value.replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase(); } );
}
function onlyNum(e){
	e.value = e.value.replace(/[^0-9]+/i,"");
}


function checkFields(name){
var errors = new Array();
var text_er = '';
var focus = '';

show_message('Оформление заказа');

if ($('email_'+name)!=null) if ($('email_'+name).value.length>0 && /^[\w\-\.]{1,64}\@[\w\-\.]+\.[a-zA-Z0-9]{2,5}$/i.test($('email_'+name).value)==false) { errors[0] = 'Некорректно введен "Email адрес"'; $('email_'+name).className = 'er_text'; if (focus=='') focus = 'email_'+name; }

if ($('fio_'+name)!=null) {	if ($('fio_'+name).value=='') { errors[1] = 'Не заполнено поле "Контактное лицо"';  $('fio_'+name).className = 'er_text'; if (focus=='') focus = 'fio_'+name; }
	//else if (/^[\w\(\)\ \.\,\+]{2,}$/i.test($('fio_'+name).value)==false) { errors[1] = 'Не корректно заполнено поле "Контактное лицо"';  $('fio_'+name).className = 'er_text'; if (focus=='') focus = 'fio_'+name; }
}
if ($('country_'+name)!=null) if ($('country_'+name).value=='') { errors[2] = 'Не заполнено поле "Cтрана"'; $('country_'+name).className = 'er_text'; if (focus=='') focus = 'country_'+name; }
if ($('phone_'+name)!=null) {			if ($('phone_'+name).value=='') { errors[3] = 'Не заполнено поле "Телефон"'; $('phone_'+name).className = 'er_text'; if (focus=='') focus = 'phone_'+name; }
			else if (/^[\d\-\(\)\ \.\,\+]{4,}$/i.test($('phone_'+name).value)==false) { errors[3] = 'Не корректно введен "Телефон"'; $('phone_'+name).className = 'er_text'; if (focus=='') focus = 'phone_'+name; }
			}
if ($('post_code_'+name)!=null) if ($('post_code_'+name).value=='') { errors[4] = 'Не заполнено поле "Индекс города"'; $('post_code_'+name).className = 'er_text'; if (focus=='') focus = 'post_code_'+name; }
if ($('oblast_'+name)!=null) if ($('oblast_'+name).value=='' && $('oblast_'+name).style.display == '') { errors[5] = 'Не заполнено поле "Область"'; $('oblast_'+name).className = 'er_text'; if (focus=='') focus = 'oblast_'+name; }
if ($('city_'+name)!=null) if ($('city_'+name).value=='' && $('city_'+name).style.display == '') { errors[6] = 'Не заполнено поле "Город"'; $('city_'+name).className = 'er_text'; if (focus=='') focus = 'city_'+name; }

if ($('address_'+name)!=null) if ($('address_'+name).value=='') { errors[7] = 'Не заполнено поле "Адрес"'; $('address_'+name).className = 'er_text'; if (focus=='') focus = 'address_'+name; }
if (name=='2.1' && $('confrim1')!=null && $('confrim2')!=null) if ($('confrim1').checked==false && $('confrim2').checked==false) { errors[8] = 'Не указано подтверждение Вашего заказа по телефону'; }
if (name=='2.2' && $('confrim3')!=null && $('confrim4')!=null) if ($('confrim3').checked==false && $('confrim4').checked==false) { errors[8] = 'Не указано подтверждение Вашего заказа по телефону'; }

if (errors.length>0) for (i = 0; i<errors.length; i++)
	if (errors[i]) text_er += errors[i]+'<br>';

if (text_er!=''){
   close_message('error',text_er,focus);
   return 0;
   }
   else {

	return 1;
   }
}

function choose_delivery_type(name){

   if ($('form_st_1.1')) $('form_st_1.1').style.display = 'none';
   if ($('form_st_2.1')) $('form_st_2.1').style.display = 'none';
   if ($('form_st_2.2')) $('form_st_2.2').style.display = 'none';
   if ($('form_st_3.1')) $('form_st_3.1').style.display = 'none';

   $('form_st_'+name).style.display = '';

   var total_price = $('t_price').innerHTML;
   total_price = parseInt(total_price);

   if (name == '2.2') total_price = Math.ceil((total_price + 500)*1.087);

   $('price_delivery').innerHTML = total_price;
   $('price_value_'+name).value = total_price;
   $('delivery_type').value = name;
   if (isIE6) reloadPage();

}

// проверка на введенное количество
function CheckQuantities(){

	var ids = new Array();
    if ($('recount_ids')!=null) ids = $('recount_ids').value.split(',');

 if (ids.length > 0) {
 	for (var i = 0; i < ids.length; i++) if ($('quantity_'+ids[i])!=null) {

 	    inp = $('quantity_'+ids[i]);
        var value = inp.value;

 		if ((isNaN(parseInt(value, 10)) ) || (parseInt(value,10)<=0)) {
 			close_message('info','Кол-во товара должно быть больше нуля!', 'quantity_'+ids[i]);
 			inp.value = 1;
			return 0;
 			}
	 }
	return 1;
  }
}

// ****************************************** //
// ****** КОРЗИНА ПОЛЬЗОВАТЕЛЯ >>>>>   ****** //
// ****************************************** //



function removeElement(parent_name,child_name) {
  if ($(parent_name) && $(child_name)) {
  var d = $(parent_name);
  var olddiv = $(child_name);
  d.removeChild(olddiv);
  }
}



function load_menu(cat_id, type, brend){  	var req = new JsHttpRequest();

	show_message('Построение меню');

	req.open(null, '/js/_ajax/load_menu.php', true);

	var data = { 'cat_id': cat_id, 'type': type, 'brend': brend };
	req.send(data);

	req.onreadystatechange = function() {
		if (req.readyState == 4) {

		if (req.responseText) close_message('error', req.responseText);

		var html = req.responseJS.html;
		var menu = req.responseJS.menu;
		var h1 = req.responseJS.h1;
		var nav_line = req.responseJS.nav_line;
		var meta_title = req.responseJS.meta_title;
		var new_id = req.responseJS.new_id;
		var sort_link = req.responseJS.sort_link;

		if (h1 && $('cat_h1')!=null) {				$('cat_h1').innerHTML = h1;
				//if ($('zakaz')!=null) $('zakaz').style.display = 'none';
				}
				else if ($('zakaz')!=null) $('zakaz').style.display = '';

		$('menu_catalog').innerHTML = (menu) ? menu : '';
		if (html && $('content')!=null) $('content').innerHTML = (html) ? html : '';
		if (nav_line && $('navigation_line')!=null) $('navigation_line').innerHTML = nav_line;
		if ($('sorting')!=null) $('sorting').style.display = (new_id==11) ? 'none' : '';

		if ($('menu_class')!=null && sort_link) {							$('menu_class').className = ($('menu_class').className == 'zag') ? 'zag2' : 'zag';
							$('menu_class').innerHTML = sort_link;
			}

		close_message();

		////// ЗАГОЛОВОК СТРАНИЦЫ
		document.title = meta_title;

		}


	}

}


function load_catalog(cat_id, page){
  	var req = new JsHttpRequest();
  	//var id = (($('catalog_id')!=null)) ? $('catalog_id').innerHTML : 0;
  	var brend = (($('brend_id')!=null)) ? $('brend_id').innerHTML : 0;
	var num_on_page = $('num_on_page').value;
	var sort_by = $('sort_by').value;
	if (page == undefined) page = 1;

	//if (id>0){
	show_message('Загрузка данных');

	req.open(null, '/js/_ajax/load_catalog.php', true);

	var data = {'sort_by': sort_by, 'nums': num_on_page, 'cat_id': cat_id, 'page': page, 'brend': brend };
	req.send(data);

	req.onreadystatechange = function() {
		if (req.readyState == 4) {

		if (req.responseText) close_message('error', req.responseText);

		var html = req.responseJS.html;
		if (html) $('content').innerHTML = (html) ? html : '';
		else close_message('info', 'Данные, не могут быть получены, выберите сначала раздел каталога');

		//deleteCookie("num_on_page", "/")
		//addCookie("num_on_page", num_on_page, 28, "/");
		if (html) close_message();
		}


	//}
    }

}

////////////////////////////////////
// <<<<<ДИНАМ. ИЗМЕН. СОДЕРЖИМОГО //
////////////////////////////////////

function change_content(id, path, parent_name){
	var content = $(parent_name);

	if (content!=null) {

		show_message('Загрузка данных');

	  	var req = new JsHttpRequest();
		req.open(null, '/js/_ajax/change_content.php', true);
		var data = { 'id': id, 'path': path, 'module': parent_name };
    	req.send(data);

		req.onreadystatechange = function() {
			//if (req.responseText) alert(req.responseText);

			if (req.readyState == 4) {

			//**** СОДЕРЖИМОЕ ****//
			var html = req.responseJS.html;
			content.innerHTML = (html) ? html : '';

			//**** ЗАГОЛОВОК СТРАНИЦЫ ****//
			document.title = req.responseJS.MetaTitle;

			//**** НАВИГАЦИОННАЯ ЛИНИЯ ****//
			//var navigationLine = req.responseJS.navigationLine;
			//if (navigationLine && $('navigation')!=null) $('navigation').innerHTML = navigationLine;
			//**** МЕНЮ САЙТА ****//
			//var menu = req.responseJS.menu;
			//if (menu && $('menu')!=null) $('menu').innerHTML = menu;
			close_message();
			}


		}
	} else if (path) location.href = ''+path+'';
}
////////////////////////////////////
// ДИНАМ. ИЗМЕН. СОДЕРЖИМОГО>>>>> //
////////////////////////////////////




// ЗАГРУЗКА НАЧАЛЬНЫХ ПАРАМЕТРОВ
function load_params(id, url){
	cat_id = id;
	func_back[0] = new Function("getData('"+id+"', '"+url+"');");
	current_page = 0;
}



function getData(id, link){
if ($('goback')!=null) {
if ($('goback').style.cursor == '') {
    	$('goback').src = 'js/images/btn_left_on.png';
    	$('goback').style.cursor = 'pointer';
	}
	current_page++;
    func_back[current_page] = new Function("load_body('"+id+"', '"+link+"');");
}

	if (getCookie('ajax') == 'true') { load_body(id, link); return false; }
	else return true;

}

function load_body(id, path){
  	var req = new JsHttpRequest();
  	var div_body = $('main_body');

	show_message('Загрузка данных');

	req.open(null, '/js/_ajax/load_body.php', true);
	var data = { 'id': id, 'path': path };
    req.send(data);

	req.onreadystatechange = function() {
		if (req.readyState == 4) {

		//$('debug').innerHTML = req.responseText;

		var html = req.responseJS.html;
		var category = req.responseJS.category;
		var MetaTitle = req.responseJS.MetaTitle;
		var navigationLine = req.responseJS.navigationLine;
		var menu = req.responseJS.menu;
		div_body.innerHTML = (html) ? html : '';
		if (category == 'true') {
		////// ВЫДЕЛЕНИЕ ТЕКУЩЕЙ ДИРЕКТОРИИ
		if ($('cat_'+id) != null) $('cat_'+id).className = 'hov';
		if (!before_id && $('cat_'+cat_id) != null && id!=cat_id) $('cat_'+cat_id).className = '';
		if ($('cat_'+before_id) != null && id!=before_id) $('cat_'+before_id).className = '';
		} else {
			//alert('модули');
		}
		////// ЗАГОЛОВОК СТРАНИЦЫ
		document.title = MetaTitle;
		////// НАВИГАЦИОННАЯ ЛИНИЯ
		if (navigationLine && $('navigation')!=null) $('navigation').innerHTML = navigationLine;
		///// МЕНЮ САЙТА
		if (menu && $('menu')!=null) $('menu').innerHTML = menu;

		before_id = id;
		close_message();
		}


	}


}


function menu(id){
if ($('img_'+id)!=null && $('menu_'+id)!=null){
	var img = $('img_'+id);
	var menu = $('menu_'+id);

	img.src = (/p7.gif/.test(img.src)) ? 'img/p6.gif' : 'img/p7.gif';
	menu.className = (menu.className == 'open') ? 'close' : 'open';

   // get_menu();
	}

}


function get_menu(){
	var p_ids = new Array(); var j = 0;

	thisCheckBoxes = $('menu_catalog').getElementsByTagName('div');
			for (i = 1; i < thisCheckBoxes.length; i++)
				if (thisCheckBoxes[i].className == 'open') {
	 				  j++;
                      p_ids[j] = thisCheckBoxes[i].id.substring(5);
				}
        if (p_ids.length>0) {
              for (i = 1; i < p_ids.length; i++)  alert(p_ids[i]);
        }

}


function check_all(e,Name,cookie_name,action,group){
		thisCheckBoxes = e.parentNode.parentNode.parentNode.getElementsByTagName('input');
		var add_values = ''; var del_values = '';
		for (i = 1; i < thisCheckBoxes.length; i++)
			if (thisCheckBoxes[i].name == Name){
				thisCheckBoxes[i].checked = e.checked;
				if (thisCheckBoxes[i].checked==true) add_values += thisCheckBoxes[i].value+',';
				else del_values += thisCheckBoxes[i].value+',';
			}

	if (action == 'save' && cookie_name!=undefined) {		if (group!=undefined) resetCookie(cookie_name,group);		if (add_values) saveCookieValues(cookie_name, add_values.substring(0,add_values.length-1), 1);
		if (del_values) delCookieValues(cookie_name, del_values.substring(0,del_values.length-1), 1);	}
}


function check_one(e,cookie_name,action,group){
	//if ($(e.id.replace('chb','str'))) {e.checked = !e.checked;}
	if (action == 'save' && cookie_name!=undefined){		if (group!=undefined) resetCookie(cookie_name,group);		if (e.checked == true) saveCookieValues(cookie_name, e.value, 1);
		else delCookieValues(cookie_name, e.value, 1);
	}
}



function compare_checked(){	var p_ids = new Array();
	var result = false;

    var compare = getCookie('compare');
    if (compare != null && compare != '') var p_ids = compare.split(',');

    if (p_ids.length>1) result = true;
    else if (p_ids.length==1) close_message('info', 'Для того чтобы сравнить, необходимо выбрать не менее двух товаров!');
    else close_message('info', 'Отметьте позиции, которые Вы хотите сравнить!');

return result;
}



////////////////////////////
// <<<<< РАБОТА С COOKIE  //
////////////////////////////
function addCookie(szName,szValue,dtDaysExpires,cPath)
{
   var dtExpires = new Date();
   var dtExpiryDate = "";

   dtExpires.setTime(dtExpires.getTime() + dtDaysExpires * 24 * 60 * 60 * 1000);
   dtExpiryDate = dtExpires.toGMTString();
   document.cookie = szName + "=" + szValue + "; path=" +cPath+ "; expires=" + dtExpiryDate;
}

function getCookie(name) {
        var prefix = name + "="
        var cookieStartIndex = document.cookie.indexOf(prefix)
        if (cookieStartIndex == -1) return null
        var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
        if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length
        return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}

function deleteCookie(name, path, domain) {		if (path==undefined) path = '/';
        if (getCookie(name)) {
                document.cookie = name + "=" +
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                "; expires=Thu, 01-Jan-70 00:00:01 GMT"
	}
}

function saveCookieValues(cookie_name, new_values, period, path, circle){
        if (!new_values) return false;
        if (period==undefined) period = 1;
        if (path==undefined) path = '/';
        if (circle==undefined) circle = 0;
        else circle = parseInt(circle);

        var checked_values = {};
  		var cookie_value = getCookie(cookie_name);
        if (cookie_value == null || cookie_value == '') addCookie(cookie_name, new_values, period, path);
        else {
            var values = (cookie_value+','+new_values).split(',');
            var save_values = '';
            var from = (circle>0 && values.length>circle) ? values.length-circle : 0;
         	if (values.length > 0) for (var i=from; i<values.length; i++) if (values[i]>0 && !checked_values['id'+values[i]]) {
					save_values += values[i]+',';
					checked_values['id'+values[i]] = 1;
         			}
         if (save_values) {
         	save_values = save_values.substring(0,save_values.length-1);
         	addCookie(cookie_name, save_values, period, path);

         	}
		}
}

function delCookieValues(cookie_name, del_values, period, path){
        if (!del_values) return false;
        if (period==undefined) period = 1;
        if (path==undefined) path = '/';

        var checked_values = {};
  		var cookie_value = getCookie(cookie_name);

        if (cookie_value != null && cookie_value != '') {
        	del_values = del_values.split(',');
        	if (del_values.length>0) for (var i=0; i<del_values.length; i++) checked_values['id'+del_values[i]] = 1;

            var values =  cookie_value.split(',');
            var save_values = '';
         	if (values.length > 0) for (var i=0; i<values.length; i++) if (values[i]>0 && !checked_values['id'+values[i]]) {
					save_values += values[i]+',';
					checked_values['id'+values[i]] = 1;
         			}
     	if (save_values) save_values = save_values.substring(0,save_values.length-1);
       	addCookie(cookie_name, save_values, period, path);
		}
}

function resetCookie(cookie_name,group,period, path){	if (group==undefined) return false;
    if (period==undefined) period = 1;
    if (path==undefined) path = '/';

	var value = getCookie(cookie_name+'_group');
	//alert(value + ' == ' + group);
	if (value!=null && value!=group) {		addCookie(cookie_name,'',period,path);
	}
	addCookie(cookie_name+'_group',group,period,path);


}
////////////////////////////
// РАБОТА С COOKIE >>>>>> //
////////////////////////////



// УДАЛЕНИЕ ФАЙЛА
function delete_photo(name, dir){
	remove_func = new Function("remove_photo('"+name+"', '"+dir+"');");
	close_message('confirm','Вы действительно хотите удалить файл?');
}

function remove_photo(name, dir) {
	var req = new JsHttpRequest();
	req.open(null, '/js/_ajax/remove_photo.php', true);

	var data = { 'name': name, 'dir': dir};
        req.send(data);

		show_message('Удаление файла');

    req.onreadystatechange = function() {
		if (req.readyState == 4) {

		var status = req.responseJS.status;
		if (status == true) {
			//$('avatar_image_yes').style.display = 'none';
			$('avatar_image').innerHTML = 'Аватaр удален';
			close_message('info','Файл успешно удален');
			return true;
		} else {
			close_message('error','Невозможно удалить файл, <a href="/box/error_message/__user__edit__/" rel="gb_page_center[600, 320]" title="Форма отправки сообщений">Написать администратору</a>');
			return false;
		}


			close_message();
		}
    }
}





// ***************************************** //
// *****  <<<<<< Работа с формами   ******** //
// ***************************************** //
var errs = new Array();
var ie=document.all
var ns6=document.getElementById&&!document.all

function imgFormClick (el,val) {
	if ((ie||ns6) && $(el)) {
	rad_value = $(el).value;

	if (val > 0) new_value = val;
	else if (val == 'x') new_value = rad_value;
	else new_value = rad_value == 1? '2': '1';

	new_text_value = '';

	var path=$(el+'_img').src;
	var regexp =/_.\./g;
	path = path.replace(regexp,'_'+new_value+'.');
	$(el+'_img').src=path;
	$(el+'_img').alt = new_text_value;
	$(el).value = new_value;
	}
}

function FormCheckInt (el,id,showerr,elfocus,errmsg) {
	if ((ie||ns6) && el && $('f'+id)) {
	value = el.value;
	if (!(/^(\d{1,3})$/.test(value))) {
		el.className = 'inp_text_err';
		errs[id] = 1;
		if (showerr == 1) {
			$('f'+id).innerHTML = errmsg;
		}
		if (elfocus == 1) {
			el.focus();
		}
	}
	else if ((errs[id] == 1 && errmsg.toLowerCase() == $('f'+id).innerHTML.toLowerCase()) || !errs[id]) {

		$('f'+id).innerHTML = '';
		el.className = 'inp_text_hover';
		errs[id] = 0;
		if (elfocus == 1) {
			el.focus();
		}
	}
	}
}

function change_class(e,class_name){
 if (e!=null && e.value!='') e.className =(class_name != undefined) ? class_name : 'inp_text';
}

function FormCheckEmail(id, user_id){
    var e = $(id);
	if (e!=null) {
		if (e.value=='') close_message('error', 'Необходимо ввести email адрес', e.id);
		else if (/^[\w\-\.]{2,32}\@[\w\-\.]+\.[a-zA-Z0-9]{2,5}$/i.test(e.value)==false) close_message('error', 'Некорректно введен email адрес', e.id);
		else if (FormCheckLogin(e, 'Email', user_id, 'Необходимо ввести email адрес', 'Введенный email адрес уже существует')) return true;
    } else close_message('error', 'Неверно указан елемент');

return false;
}


function FormCheckLogin(e, name, user_id, errtext1, errtext2) {

	var value = e.value;
	if (value=='') { close_message('error', errtext1, e.id); return false; }
	else {
	if (name=='Name' && $('Email').type == 'text'){
			 if (/^[\w-\.]{2,64}$/i.test(value)==false) { close_message('error', 'Некорректно введено имя пользователя', e.id); return false;}
			 else if (/admin|root|support/i.test(value)==true) { close_message('error', 'В имени пользователя найдены запрещенные слова, попробуйте другой логин', e.id); return false;}
			 }

	  var req = new JsHttpRequest();
		req.open(null, '/js/_ajax/check_regname.php', true);
		var data = { 'Name': name, 'Value': value, 'UserID': user_id };
	    	req.send(data);

	    	req.onreadystatechange = function() {
				if (req.readyState == 4) if (req.responseJS.status>0) close_message('error', errtext2, e.id);
	    	}

	 	}

}



function FormCheckName (el,id,showerr,elfocus,errmsg) {
	if ((ie||ns6) && el && $('f'+id)) {
	value = el.value;
	if (/[\||\'|\<|\>|\"|\!|\$|\@|\&\~\*\+]/.test(value)) {
		el.className = 'inp_text_err';
		errs[id] = 1;
		if (showerr == 1) {
			$('f'+id).innerHTML = errmsg;
		}
		if (elfocus == 1) {
			el.focus();
		}
	}
	else if ((errs[id] == 1 && errmsg.toLowerCase() == $('f'+id).innerHTML.toLowerCase()) || !errs[id]) {

		$('f'+id).innerHTML = '';
		el.className = 'inp_text_hover';
		errs[id] = 0;
		if (elfocus == 1) {
			el.focus();
		}
	}
	}
}

function FormCheckEmpty (el,id,len,showerr,elfocus,errmsg) {
	if ((ie||ns6) && el && $('f'+id)) {
	value = el.value;
	if (el.value.replace(/ /gi,"").length < len) {
		el.className = 'inp_text_err';
		errs[id] = 1;
		if (showerr == 1) {
			$('f'+id).innerHTML = errmsg;
		}
		if (elfocus == 1) {
			el.focus();
		}
	}
	else if ((errs[id] == 1 && errmsg.toLowerCase() == $('f'+id).innerHTML.toLowerCase()) || !errs[id]) {
		$('f'+id).innerHTML = '';
		el.className = 'inp_text_hover';
		errs[id] = 0;
		if (elfocus == 1) {
			el.focus();
		}
	}
	}
}


function CheckForm ( type, el, id, showerr, elfocus, errmsg )
{
	if (type==undefined||type==null) type = 'empty';
    alert(type[0]);
	if ((ie||ns6)&&el)
	{
		var value=el.value.trim();
		var regexp=null;

		switch (type)
		{
			case 'int':
			 regexp = /^(\d{1,3})$/;
			 break;
		}
	}
}

function check_form_errors(form_id){var t = eval('checkFields_'+form_id);
var mas = (t) ? t : null;
if (!mas) return false;

for (var i in mas)
	if ($('fields'+i)){		var fname = ($('fname'+i)) ? ' "'+$('fname'+i).innerHTML+'"' : '';
		var value = $('fields'+i).value;
			if ((value == '' || value == 0) && mas[i] == 1) {				if ($('fields'+i).type == 'text') close_message('error', 'Необходимо заполнить поле'+fname, 'fields'+i);
				else close_message('error', 'Необходимо выбрать значение в поле'+fname, 'fields'+i);
				return false;
			} else if (/e-?mail|ема[и|й]л|электро(нная\ )?почта/i.test(fname) && /^[\w\-\.]+\@[\w\-\.]+\.[a-z]{2,5}$/i.test(value)==false && ((value.length>0 && mas[i] == 0) || mas[i] == 1)) {
				close_message('error', 'Некорректно введен email адрес', 'fields'+i);
				return false;
			} else if (/телефон|мобильный|сотовый|phone|mobile/i.test(fname) && /^[\d\-\(\)\ \.\,\+]{4,}$/i.test(value)==false && ((value.length>0 && mas[i] == 0) || mas[i] == 1)) {
				close_message('error', 'Некорректно введен '+fname, 'fields'+i);
				return false;
			}
	}

return true;}

function send_form_data(form_id){
if (check_form_errors(form_id) == false) return false;
else {
	var fdata = $('form_data'+form_id);
	var fields_value = new Array(fdata.length);
	for (var i=0; i<fdata.length; i++) fields_value[fdata.elements[i].name] = fdata.elements[i];

  		var req = new JsHttpRequest();
		req.open(null, '/js/_ajax/messages/send_form_data.php', true);
		var data = { 'form_id': form_id, 'data': fields_value, 'back_link' : eval('back_link'+form_id) };
        req.send(data);

		show_message('Отправление данных');

    	req.onreadystatechange = function() {
		//$('debug').innerHTML = req.responseText;

		  if (req.readyState == 4) {

		  var message = req.responseJS.result;
		  var errors = req.responseJS.errors;
          var focus = req.responseJS.focus;

            if (errors != '') close_message('error', errors, focus);
            else {
		        if (message) {
		        	close_message('info', message);
		        	$('form_data'+form_id).reset();
		        	reImg('iCodeForm'+form_id);
					//for (var i=0; i<fdata.length; i++) fdata.elements[i].value = '';
		        }
				else close_message();
            }

		   }
		}

}
}


function reImg(id){
	if ($(id)==null) return false;
	var ndate = new Date().getTime();
	$(id).src = "inc/Modules/antibot.php?" + ndate;
}


// ***************************************** //
// ******* Работа с формами >>>>>>> ******** //
// ***************************************** //

function print_page(){
	if (typeof(window.print) != undefined) {
	    window.print();
	}
}



/* ЗАГРУЗИТЬ КАРТИНКУ */
function Preload(imgObj,imgSrc) {
        if (document.images) {
                eval(imgObj+' = new Image()')
                eval(imgObj+'.src = "'+imgSrc+'"')
        }
}






////////////////////////////
// <<<<< DRAG AND DROP    //
////////////////////////////
var dflag=false;
var shift_x;
var shift_y;

function start_drag(itemToMove,e){
     if(!e) e = window.event;
     itemToMove.style.cursor='move';
     dflag=true;
     shift_x = e.clientX-parseInt(itemToMove.style.left);
     shift_y = e.clientY-parseInt(itemToMove.style.top);

     if(e.stopPropagation) e.stopPropagation();
     else e.cancelBubble = true;
     if(e.preventDefault) e.preventDefault();
     else e.returnValue = false;
}

function end_drag(){ dflag=false; }

function dragIt(itemToMove,e){
     if(!dflag) {
	itemToMove.style.cursor='default';
	addCookie('left',parseInt(itemToMove.style.top),30,'/');
	addCookie('top',parseInt(itemToMove.style.left),30,'/');
	return;
      }
     if(!e) e = window.event;
     itemToMove.style.left = (e.clientX-shift_x) + "px";
     itemToMove.style.top = (e.clientY-shift_y) + "px";

     if(e.stopPropagation) e.stopPropagation();
     else e.cancelBubble = true;
     if(e.preventDefault) e.preventDefault();
     else e.returnValue = false;
}


function r_over(e){
e.style.color = '#66ccff';
e.style.fontWeight = 'bold';
}
function r_out(e){
e.style.color = '#333';
e.style.fontWeight = 'normal';
}

////////////////////////////
// DRAG AND DROP   >>>>>> //
////////////////////////////

var timer;
        function scrolldelta(dy) {
            if (dy != 0) {
                doScroll(dy);
            } else {
                clearTimeout(timer);
            }
        }


        function doScroll(dy) {
            var target = document.getElementById('scrollable');
            target.scrollTop = target.scrollTop + dy
            timer = setTimeout("doScroll("+dy+");", 25);
            }


function change_city(id, value){

	if (value == 'other') {
		document.getElementById(id).style.display = '';
	} else document.getElementById(id).style.display = 'none';
}


/* LOGIN BOX */
function loc(e){ location.href = e.getElementsByTagName('a')[0].href;  }

function $(e) { return document.getElementById(e); }
function reloadPage() {
	document.body.style.display="inline";
	document.body.style.display="block";
}
// показать попап
function showPopup(current) {
	showShadow();
	if (current == 'auth') $(current).style.top = '30%';
	else {
		var top = (document.body.scrollTop>0) ? document.body.scrollTop : document.documentElement.scrollTop;
		//if (self.screen) $(current).style.top = (parseInt(top,10)+(screen.height/2)-200)+'px';
		//else
		$(current).style.top = (parseInt(top,10)+(document.body.clientHeight/2)-300)+'px';
	}
	$(current).style.display = "block";
	reloadPage();
	return false;
}
// спратать попап
function hidePopup(current) {
	hideShadow();
	$(current).style.display = "none";
	close_message();
	reloadPage();
	return false;
}

// показать тень
function showShadow() {
	var shadow = document.getElementById("shadow");
	shadow.style.display = "block";

	var bodyHeight = document.body.clientHeight;
	var wrapHeight = parseInt(document.getElementById("all").clientHeight);
	if (wrapHeight > bodyHeight) shadowHeight = wrapHeight;
	else shadowHeight = bodyHeight;
	shadow.style.height = shadowHeight + "px";
	return false;
}

// спрятать тень
function hideShadow() {
	var shadow = document.getElementById("shadow");
	shadow.style.display = "none";
	return false;
}


// показать попап
function showInPopup(current) {
	document.getElementById(current).style.display = "block";
	reloadPage();
	return false;
}
function hideInPopup(current) {
	document.getElementById(current).style.display = "none";
	reloadPage();
	return false;
}


function hideWin(shad){
 if (shad == undefined) hideShadow();
 if ($('auth')) $('auth').style.display = "none";
 if ($('adv_ser')) $('adv_ser').style.display = "none";
 close_message();
 reloadPage();
 return false;
}


function fixSomePng(){
if ($('main_menu')) {
   var imgs = $('main_menu').getElementsByTagName('img');
   if (imgs.length>0) for (var i=0; i<imgs.length; i++) fixPNG(imgs[i]);
}
if ($('ent_sep')) fixPNG($('ent_sep'));
if ($('news_list')) {
   var imgs = $('news_list').getElementsByTagName('img');
   if (imgs.length>0) for (var i=0; i<imgs.length; i++) fixPNG(imgs[i]);
}
if ($('no_slide')) {
   var imgs = $('no_slide').getElementsByTagName('img');
   if (imgs.length>0) for (var i=0; i<imgs.length; i++) fixPNG(imgs[i]);
}
if ($('shadow')) fixPNG($('shadow'));
if ($('moscow')) fixPNG($('moscow'));
if ($('novgorod')) fixPNG($('novgorod'));
}


function book(e,id){
var div = e.parentNode.parentNode.getElementsByTagName('div');
var j = 0;
for (var i=0; i<div.length; i++) if (/book/.test(div[i].className)) {
   j++;
   if ($('delivery'+j)) $('delivery'+j).style.display = 'none';
   div[i].className = 'book';
}
e.parentNode.className = 'book act';
if ($('r_'+id+'.1')) $('r_'+id+'.1').checked = true;
if (id!=undefined) choose_delivery_type(id+'.1');
if ($('delivery'+id)) $('delivery'+id).style.display = '';
e.blur();
if (isIE6) reloadPage();

//
}


function load_compare(compare_link){
   if (compare_link==undefined) compare_link = '';
   if (compare_link) {
	window.open('/compare/'+compare_link,'_blank');
	return false;
   }
   var show_compare = false;
   var fav = getCookie('favorite');
   if (fav) {
   	var els = fav.split(',');
   	if (els[1]>0) {
	   	var wid = (els.length-0+2)*150-30;
   	    wid = (wid<document.body.clientWidth) ? wid : (document.body.clientWidth>500?document.body.clientWidth-150:1000);
   	    var heig = (screen.height>750) ? 740 : 700;
   		window.open('/compare/'+compare_link,'_blank','width='+wid+',height='+heig+',menubar=no,status=no,location=no,toolbar=no,scrollbars=yes');
   		show_compare = true;
   		}
   }
   if (show_compare === false) close_message('info','Необходимо выбрать не менее двух часов для сравнения');
}

// ***************
// <<<< Избранное
// ***************

function clear_favorite(){
addCookie('favorite', '', '30', '/');
add_favorite_lot();
}

function add_favorite_lot(e,id,ver){

if (e){
  var img = e.getElementsByTagName('img')[0];
  var action = (/not/.test(img.src)===false) ? 'add' : 'delete';
  e.blur();
} else {
  var action = 'delete';
}

if (action == 'add') {
	saveCookieValues('favorite', id, 10, '/', 100);
	if (e) {
		img.src = img.src.replace(/active/i,"not-active");
		e.getElementsByTagName('span')[0].innerHTML = 'удалить '+(ver!='lite'?'':'')+'из избранного';
	}
	}
else {
	delCookieValues('favorite', id+',');
	if (e) {
		img.src = img.src.replace(/not\-/i,"");
		e.getElementsByTagName('span')[0].innerHTML = 'добавить '+(ver!='lite'?'':'')+'в избранное';
	}
}

	var fav1 = $('favorites') ? $('favorites') : ($p('favorites')?$p('favorites'):'') ;
	var fav2 = $('all_favorites') ? $('all_favorites') : ($p('all_favorites')?$p('all_favorites'):'') ;
	if (fav1){

		var req = new JsHttpRequest();
		req.open(null, '/js/_ajax/load_favorite.php', true);
		var data = { };
        req.send(data);

        show_message();
		//alert(action+' = '+ getCookie('favorite'))
    	req.onreadystatechange = function() {
		   if (req.responseText) alert(req.responseText);

    	   if (req.readyState == 4) {
			  var result = req.responseJS.result;
			  var errors = req.responseJS.errors;

            if (errors != '') close_message('error', errors);
            else {
              fav1.innerHTML = result;
			  if (fav2) fav2.style.display = result ? '' : 'none';
              close_message();
            }
         }
        }

     }

}


function load_lastopen(e,id){

	if ($('lastopen')){
		var req = new JsHttpRequest();
		req.open(null, '/js/_ajax/load_lastopen.php', true);
		var data = { };
        req.send(data);

        show_message();

    	req.onreadystatechange = function() {
    	   if (req.readyState == 4) {
		   //if (req.responseText) alert(req.responseText);
			  var result = req.responseJS.result;
			  var errors = req.responseJS.errors;

            if (errors != '') close_message('error', errors);
            else {
              $('lastopen').innerHTML = result;
              if ($('all_lastopen')) $('all_lastopen').style.display = result ? '' : 'none';
			  close_message();
            }
         }
        }

     }

}


function fav(e,act){
  if (act == undefined){
	e.className = 'fav fact';
	e.parentNode.className = 'act';
 } else {
	e.className = 'fav';
	e.parentNode.className = '';
 }

}

function favp(e,act){
	e.className = (act == undefined) ? 'act' : '';
}

function favclick(e){
	var els = e.getElementsByTagName('a');
	if (els.length>0) location.href = els[0].href;
}

function stop_acts(e){
  if (window.event) event.cancelBubble=true;
  else if (e.stopPropagation) e.stopPropagation();
}



/// Выпад. меню поиска бренда

function show_brends(value){
   if ($('brend_list')) {
		var req = new JsHttpRequest();
		req.open(null, '/js/_ajax/show_brends.php', true);
		var data = { 'word': value };
        req.send(data);

    	req.onreadystatechange = function() {
	//	   if (req.responseText) alert(req.responseText);
    	   if (req.readyState == 4) {
			  var result = req.responseJS.result;
			  var errors = req.responseJS.errors;

            if (errors != '') close_message('error', errors);
            else {
             $('brend_ul').innerHTML = (result) ? result :'';
             /*if (result) {
             for (var i=0; i<result.length; i++){
	             var li = document.createElement('li');
	             li.onmouseover = function(){ this.className='cur'; }
	             li.onmouseout = function(){ this.className=''; }
	             li.onclick = function(){ $('word_brend').value = a_title(this); loc(this); }
	             li.innerHTML = result[i];
	             $('brend_ul').appendChild(li);
			 }  */
             $('brend_list').style.display = (result) ? '' : 'none';
            }
         }
        }

   }

}

function brend_select(num){
  /*var lis = $('brend_ul').childNodes;
  if (num == 'first') {
    lis[0].className = 'cur';
  }

  $('brend_list').focus();
  */
}

function a_title(e){  value = e.firstChild.innerHTML.replace(/\<.*\>(.*)\<\/.*\>/ig,"$1"); if (value) return value; }
function hide_dropmenu(){ delayhide=setTimeout("clear_dropmenu();",3000); }
function show_dropmenu(){ if ($('brend_ul').innerHTML) $('brend_list').style.display = ''; if (typeof delayhide!="undefined") { clearTimeout(delayhide); } }
function clear_dropmenu(){ if ($('brend_list')) $('brend_list').style.display = 'none'; }

document.onclick=clear_dropmenu;




/// LOGIN


	function time(m){
	m--;
 		if ( m >= 0) {
 			document.getElementById('user_enter').style.display = 'none';
 			document.getElementById('wait_time').style.display = '';
			document.getElementById('login_name').disabled = true;
			document.getElementById('login_passwd').disabled = true;
			//if (document.getElementById('remember')) document.getElementById('remember').disabled = true;
 			document.getElementById('timer').innerHTML = m;

 		}
 		else {
 			document.getElementById('user_enter').style.display = '';
 			document.getElementById('wait_time').style.display = 'none';
 			document.getElementById('login_passwd').value = '';
			document.getElementById('login_name').disabled = false;
			document.getElementById('login_passwd').disabled = false;
			//if (document.getElementById('remember')) document.getElementById('remember').disabled = false;
			return false;
 		}

	setTimeout("time("+m+")",1000);
	}


	function user_login(){

	if (!$('login_name').value) close_message('error','Необходимо ввести имя пользователя и пароль', 'login_name');
	else {

    var req = new JsHttpRequest();
  	req.open(null, '/js/_ajax/login.php', true);
  	var name = $('login_name').value;
  	var pass = $('login_passwd').value;
  	if ($('remember')) var remember = $('remember').checked;

	var data = { 'name': name, 'pass' : pass, 'remember': remember };
        req.send(data);

        $('loading-text').style.textAlign = 'center';
		show_message('Проверка введенных данных');

	    req.onreadystatechange = function() {

		//$('debug').innerHTML = req.responseText;

		if (req.readyState == 4) {
               if (req.responseJS.error != 'no') {
               	$('loading-text').style.textAlign = 'left';
    		  	close_message('error', req.responseJS.error , 'login_passwd');
    		  		if (req.responseJS.disabled != 0 ) {
    		  			$('user_enter').style.display = 'none';
						$('login_name').disabled = true;
						$('login_passwd').disabled = true;
						time(req.responseJS.disabled);
    		  		}
    		  		else {
    		  			$('user_enter').style.display = '';
    		  			$('login_passwd').value = '';
						$('login_name').disabled = false;
						$('login_passwd').disabled = false;
    		  		}
    		  		return false;
               }

			$('loading-text').style.textAlign = 'center';
			close_message();
   			document.login_form.submit();
		}
    }


    }
	}


		var timer;
        function scrolldelta(id, dy) {
            if (dy != 0) {
                doScroll(id,dy);
            } else {
                clearTimeout(timer);
            }
        }


        function doScroll(id, dy) {
            var target = document.getElementById(id);
            target.scrollTop = target.scrollTop + dy;
			var d = (isIE) ? 15 : 25;
            timer = setTimeout("doScroll('"+id+"',"+dy+");", d);
           }


function setPhoneFormat(e,event){
   var k = event.keyCode;
	   if (k != 8 && k != 46){
	   var val = e.value;
	   val = val.replace(/[^0-9]/g, "");
	   var pattern = /\(?([0-9]{3})\)?\ ?([0-9]{0,7})?/;
	   if (pattern.test(val)) val = '('+RegExp.$1+') '+RegExp.$2;
	   e.value = val;
   }
}



function change_prices(value){

   if (value == 0) {
	$('price_from').value = '';
	$('price_to').value = '';
   } else {
	var prices = value.split('-');
	$('price_from').value = prices[0];
	$('price_to').value = prices[1];
   }

}

function reset_advsearch(){
	deleteCookie('adv_search_data');
	var t = '';
	var sel = $('advanced_search').getElementsByTagName('select');
	if (sel.length>0) for(var i=0; i<sel.length; i++) sel[i].options[0].selected = true;
	var inp = $('advanced_search').getElementsByTagName('input');
	if (inp.length>0) for(var i=0; i<inp.length; i++) if (inp[i].type == 'text') inp[i].value = '';
	else if (inp[i].value==1 || inp[i].value==2) {
	   inp[i].value = 1;
	   $(inp[i].id+'_img').src = $(inp[i].id+'_img').src.replace(/2/ig,1);
	}
	//location.href = '/search/';
}

function submit_advsearch(){
	var korpus = ''; var braslet = '';
	var stones = ''; var spec = ''; var funcs = '';
 	if ($('spec_tab')) {
		var t = $('spec_tab').getElementsByTagName('input');
	    if (t.length>0) for (var i=0; i<t.length; i++) spec += t[i].value+',';
	}
	if (spec) spec = spec.substring(0,spec.length-1);
 	if ($('stones_tab')) {
		var t = $('stones_tab').getElementsByTagName('input');
	    if (t.length>0) for (var i=0; i<t.length; i++) stones += t[i].value+',';
	}
	if (stones) stones = stones.substring(0,stones.length-1);
 	if ($('korpus_tab')) {
		var t = $('korpus_tab').getElementsByTagName('input');
	    if (t.length>0) for (var i=0; i<t.length; i++) korpus += t[i].value+',';
	}
	if (korpus) korpus = korpus.substring(0,korpus.length-1);
 	if ($('funcs_tab')) {
		var t = $('funcs_tab').getElementsByTagName('input');
	    if (t.length>0) for (var i=0; i<t.length; i++) funcs += t[i].value+',';
	}
	if (funcs) funcs = funcs.substring(0,funcs.length-1);
	if ($('braslet_tab')) {
		var t = $('braslet_tab').getElementsByTagName('input');
	    if (t.length>0) for (var i=0; i<t.length; i++) braslet += t[i].value+',';
	}
	if (braslet) braslet = braslet.substring(0,braslet.length-1);
	var get = $('brend_id').value+'|'+$('gender').value+'|'+$('mech').value+'|'+$('mech_type').value+'|'+$('glasses').value+'|'+$('watertightness').value+'|'+$('price_from').value+'|'+$('price_to').value+'|'+spec+'|'+korpus+'|'+braslet+'|'+stones+'|'+funcs+'|'+$('mech_model').value+'|';
	addCookie('adv_search_data',get,30,'/');
	location.href = '/search/?f='+get;
}


function change_page(num){
   addCookie('watch_on_page',num,30,'/');
   location.reload();
}

function change_sortby(num){
   addCookie('watch_sort_by',num,30,'/');
   location.reload();
}



function showVis(img_name){
  imgFormClick(img_name,'btn_check_blue');
  addCookie(img_name,$(img_name).value,30,'/');
  location.reload();
}

function show_adv_search(){
  if (isIE6 || !$('adv_ser')) location.href = '/search/'; else showPopup('adv_ser');
}

function ShowOne(name){
 	if ($('spec_tab')) {
		var t = $('spec_tab').getElementsByTagName('input');
	    if ($(name).value == 2 && t.length>0) for (var i=0; i<t.length; i++) if (t[i].id != name) {
	    	t[i].value = 1;
	    	$(t[i].id+'_img').src = $(t[i].id+'_img').src.replace(/2/ig,1);
	    	}
	}
}




var horizontal_offset="9px"
var vertical_offset="0"
var ie=document.all
var ns6=document.getElementById&&!document.all

function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

function iecompattest(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
var edgeoffset=(whichedge=="rightedge")? parseInt(horizontal_offset)*-1 : parseInt(vertical_offset)*-1
if (whichedge=="rightedge"){
var windowedge=ie && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-30 : window.pageXOffset+window.innerWidth-40
dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure+obj.offsetWidth+parseInt(horizontal_offset)
}
else{
var windowedge=ie && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure-obj.offsetHeight
}
return edgeoffset
}

var act_li = null;

function showhint(menucontents, obj, e, tipwidth){
if (tipwidth==undefined) tipwidth = 'auto';
if ((ie||ns6) && document.getElementById("hintbox")){
dropmenuobj=document.getElementById("hintbox")
dropmenuobj.style.display = '';
document.getElementById('hint_cont').innerHTML=menucontents
dropmenuobj.style.left=dropmenuobj.style.top=-500
if (tipwidth!=""){
dropmenuobj.widthobj=dropmenuobj.style
dropmenuobj.widthobj.width=tipwidth
}
dropmenuobj.x=getposOffset(obj, "left")
dropmenuobj.y=getposOffset(obj, "top")
dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+obj.offsetWidth-15+"px"
dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+"px"
dropmenuobj.style.visibility="visible"
obj.onmouseout=function(){ hidetip(obj); };
}
}

function hidetip(e){
dropmenuobj.style.visibility="hidden"
dropmenuobj.style.left="-500px"
dropmenuobj.style.display = '';
if (e.nodeName == 'LI') e.className = '';
}




/* Ratings */
var rat = {
	id: 0, yes: null, no: null,
	cName: function(e,val,cur){
 		if (cur==undefined && e.style.cursor!='pointer') e.style.cursor = 'pointer';
 		else if (cur!=undefined) e.style.cursor = cur;
 		e.className = val;
	},
	get_ip: function(e){
		var els = e.parentNode.getElementsByTagName('div');
		var cid = els[0].id;
		this.yes = els[1];
		this.no = els[2];
		this.id = parseInt(cid.substring(5,cid.length));
	},
	reset: function(){
		this.yes.onclick = null;
		this.yes.onmouseover = null;
		this.yes.onmouseout = null;
		this.no.onclick = null;
		this.no.onmouseover = null;
		this.no.onmouseout = null;
	},
	vote: function(e,val){
 		this.get_ip(e);
 		if (!this.id || !$('vote_'+this.id)) { close_message('error', 'Сервис не доступен, обратитесь к администратору'); return false; }
		this.reset();
		var req = new JsHttpRequest();
		req.open(null, '/js/_ajax/ratings/create_ocenka.php', true);
		var data = { 'comment_id': this.id, 'value': val };
		req.send(data);

		req.onreadystatechange = function() {
		//if (req.responseText) $('debug').innerHTML = req.responseText;
		if (req.readyState == 4) {

		var result = req.responseJS.result;
		var errors = req.responseJS.errors;
		var cName = req.responseJS.cName;

		   if (errors) close_message('error', errors);
		   else {
				if ($('vote_'+rat.id)) {
						if (result) $('vote_'+rat.id).innerHTML = result;
						if (cName) $('vote_'+rat.id).className = cName;
		   		}
		   }

		 }
		}
	},
	create: function(vote,id_num,module_id,ip_num,units,template){
		if (template == undefined) template = '';
		var theUL = $('unit_ul'+id_num);
		theUL.innerHTML = '<div class="rating_loading"></div>';

		var req = new JsHttpRequest();
		req.open(null, '/js/_ajax/ratings/create_rating.php', true);
		var data = { 'j': vote, 'q': id_num, 'm': module_id, 't' : ip_num, 'c' : units, 'templ': template };
		req.send(data);

		req.onreadystatechange = function() {
	//	if (req.responseText) alert(req.responseText);
		if (req.readyState == 4) {

		var result = req.responseJS.result;
		var errors = req.responseJS.errors;

		   if (errors) close_message('error', errors);
		   else {
				$('unit_long'+id_num).innerHTML = result;
		   }

		 }
		}

	}
}


function show_catalog(){
var catalog_href = '/catalog/';
catalog_href += ($('brend_sel').value=='') ? '' : $('brend_sel').value+'/';
catalog_href += ($('mech_sel').value) ? '?mech='+$('mech_sel').value : '?mech=';
catalog_href += ($('gender_sel').value) ? '&gender='+$('gender_sel').value : '&gender=';

if ($('brend_sel').value=='' && $('mech_sel').value=='' && $('gender_sel').value=='') location.href = '/catalog/all_watches/';
else if ($('brend_sel').value=='' && $('gender_sel').value=='' && ($('mech_sel').value=='swiss' || $('mech_sel').value=='japan')) location.href = '/catalog/'+$('mech_sel').value+'_watches/';
else if ($('brend_sel').value=='' && $('mech_sel').value=='' && ($('gender_sel').value=='man' || $('gender_sel').value=='woman')) location.href = '/catalog/'+($('gender_sel').value=='man'?'mens':'women')+'_watch/';
else location.href = catalog_href;
}


function filter_catalog(){
	var filter = '/search/?f=';
	var catalog_href = '/catalog/';
	var mech = ($('watch_mech').value=='swiss'?5:($('watch_mech').value=='japan'?1:0));
	var mech_type = ($('watch_mech').value==1 || $('watch_mech').value==2 || $('watch_mech').value==3)? $('watch_mech').value : 0;
	var mech_model = ($('watch_mech').value && !mech && !mech_type) ? $('watch_mech').value.substr(1,$('watch_mech').value.length) : 0;
	catalog_href += ($('watch_brend').value=='') ? '' : $('watch_brend').value+'/';
	catalog_href += ($('man_check').checked && !$('woman_check').checked) ? '?gender=man' : '';
	catalog_href += ($('woman_check').checked && !$('man_check').checked) ? '?gender=woman' : '';
	var go_filter = (($('watch_cost').value && $('watch_cost').value!='-') || $('watch_bra_kor').value || mech_type || mech_model) ? true : false;
    var sex = ($('man_check').checked && !$('woman_check').checked)?'mens':(($('woman_check').checked && !$('man_check').checked)?'women':'');
//                            alert($('watch_cost').value+', '+$('watch_bra_kor').value+': '+go_filter+' = '+mech+' = '+mech_type+' = '+mech_model)
	if ($('watch_brend').value=='' && !go_filter && sex) location.href = '/catalog/'+sex+'_watch/'+(mech?'?mech='+$('watch_mech').value:'');
	else if ($('watch_brend').value=='' && !go_filter && mech) location.href = '/catalog/'+$('watch_mech').value+'_watches/';
	else if ($('watch_brend').value && !go_filter) location.href = catalog_href+(mech?(catalog_href.indexOf('?')==-1?'?':'&')+'mech='+$('watch_mech').value:'');
	else {
		var sex = ($('man_check').checked && !$('woman_check').checked)?'1':(($('woman_check').checked && !$('man_check').checked)?'2':'');
		var prices = $('watch_cost').value.split('-');
		var braslet = ''; var values = [];
		if ($('watch_bra_kor')) {
			var t = $('watch_bra_kor').options;
		    if (t.length>0) for (var i=0; i<t.length; i++) if (t[i].value!='') {
		    	values[t[i].value] = (t[i].selected?2:1);
		    	}
		}
		if (values) for (var i=1; i<values.length; i++) if (i>0) braslet += values[i]+',';
		if (braslet) braslet = '||'+braslet.substring(0,braslet.length-1);
		filter += $('watch_brend').value+'|'+sex+'|'+mech+'|'+mech_type+'|0|0|'+prices[0]+'|'+prices[1]+'|'+braslet+(mech_model?'|||'+mech_model+'|':'');
		location.href = filter;
    }
	return false;


}



var effect = {
	timer: null,
	btimer: {},
	allHeights: {},
	allStandartDy: {},
	doScroll: function(id, dy) {
	    if (!$(id)) { if (timer!=undefined) clearTimeout(timer); return false; }
	    var target = $(id);
	    target.scrollTop = target.scrollTop + dy;
	    timer = setTimeout("doScroll('"+id+"',"+dy+");", 25);
	},
	slide: function(id,speed){
		if (!$(id)) return true;
		switch(speed){
			case 'fast': var coef = 3; break;
			case 'slow': var coef = 1/3; break;
			default: var coef = 1;
		}
		if (this.btimer[id]!=undefined) clearTimeout(this.btimer[id]);
		$(id).style.display = '';
		if (!this.allHeights[id]) this.allHeights[id] = parseInt($(id).offsetHeight);
		var m = (isIE) ? 15*coef : 6*coef;
		var dy = /minus/i.test($('i'+id).src) ? -m : m;
		this.allStandartDy[id] = dy;
		$(id).style.display = (m>0) ? '' : 'none';
		$('i'+id).src = (dy<0) ? $('i'+id).src.replace(/minus/i,"plus") : $('i'+id).src.replace(/plus/i,"minus");
	    if (dy>=0 && this.btimer[id]==undefined) $(id).style.height = '0px';
	    this.slide_block(id, dy);
	},
	slide_block: function(id, dy){
	    if (!$(id)) { if (this.btimer[id]!=undefined) clearTimeout(this.btimer[id]); return false; }
	    var target = $(id);
	    var height = parseInt(target.offsetHeight)+dy;
	    target.style.height = ((height>=0) ? height : 0)+'px';
	    var coef = parseFloat(this.allHeights[id]/height);
	    var coef2 = 1/coef;
		var dy = (coef>=1.2 && coef2>=0.15) ?  this.allStandartDy[id]*3 : this.allStandartDy[id];
	   // mes.show('info','Текущая высота: '+height+' = Предел: '+this.allHeights[id]+', коеф = '+coef+', коеф2 = '+coef2+', скорость = '+dy+' ('+this.allStandartDy[id]+')');
	    if ((height<=this.allHeights[id] && dy>0) || (height>=0 && dy<0)) this.btimer[id] = setTimeout("effect.slide_block('"+id+"',"+dy+");", 1);
	    else {
	    	//allHeights[id] = parseInt(target.offsetHeight)+dy;
	    	clearTimeout(this.btimer[id]);
		$(id).style.display = (dy>0) ? '' : 'none';
	    	if (isIE) reloadPage();
	    }
	}
}


function isTypeSymbs(e){
	if (e && $(e.id+'_symbs')) $(e.id+'_symbs').innerHTML = ''+e.value.length+'';
}
function isMaxCut(e){
    var max_length = e.getAttribute('maxlength');
 	if (e.value.length<=max_length) e.value = e.value.substring(0,max_length-1);
 	return max_length;
}

function isNotMax(e){
       e = e || window.event;
       var target = e.target || e.srcElement;
       var code=e.keyCode?e.keyCode:(e.which?e.which:e.charCode)
       var max_length = isMaxCut(target);

       switch (code){
                case 13: case 8: case 9: case 46:
                case 37: case 38: case 39: case 40:
                return true;
        }
	if (e.ctrlKey && code != 118) return true;
    return target.value.length <= max_length;
}

//// денежный формат
function format_cost(e){
    var val = set_money_format(e.value);
    e.value = val;
}

function set_money_format(num){
   if (num == undefined) return;
   var val = new String(num);
   var new_value = '';
   if (val.length>0) {
    val = val.replace(/[^0-9]/g, "");
   	var j = 0;
   	if (val.length>=3){
   		for (var i=val.length-1; i>=0; i--) {
   		j++;
   		new_value = val.charAt(i)+new_value;
   		if (j%3==0) new_value = ' '+new_value;
   		}
   	} else new_value = val;
    new_value = trim(new_value);

   } else new_value = val;

   return new_value;
}

// Функция trim удаляет пробелы
// в начале и в конце строки
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function notice_title_change(value){

if ($('notice_title')) {
    var cur_value = $('notice_title').value;
    switch(value){
	case 'sale': if (/куплю/i.test(cur_value)==false || cur_value.length == 0) $('notice_title').value = 'Куплю '+trim(cur_value.replace(/Продам/gi,"")); break;
	case 'buy': if (/продам/i.test(cur_value)==false || cur_value.length == 0) $('notice_title').value = 'Продам '+trim(cur_value.replace(/Куплю/gi,"")); break;
    }
}

}


var cl = {
  ch: function(e,new_class_name){
     e.className = new_class_name;
  }

}

function subscribe_begin(){

	var type1 = ($('subscribe_type1').checked) ? true : false;
	var type2 = ($('subscribe_type2').checked) ? true : false;
	var type3 = ($('subscribe_type3').checked) ? true : false;
	var type4 = ($('subscribe_type4').checked) ? true : false;
	var type5 = ($('subscribe_type5').checked) ? true : false;
	if (!type1 && !type2 && !type3 && !type4 && !type5)  { close_message('info','Необходимо выбрать хотя бы один раздел, на который Вы хотите подписаться'); return false; }
	else if ($('subscribe_email').value=='' || $('subscribe_email').value=='ваш email') { $('subscribe_email').value=''; close_message('info','Необходимо ввести email адрес','subscribe_email'); return false; }
    else if ($('subscribe_email').value.length>0 && /^[\w\-\.]{1,64}\@[\w\-\.]+\.[a-zA-Z0-9]{2,5}$/i.test($('subscribe_email').value)==false) { close_message('info','Email адрес введен некорректно','subscribe_email'); return false; }

	var req = new JsHttpRequest();
	req.open(null, '/js/_ajax/load_subscribe.php', true);
	var data = { 'news': type1, 'catalog': type2, 'special': type3, 'sale': type4,  'auction': type5, 'email': $('subscribe_email').value };
        req.send(data);

	    show_message();

    	req.onreadystatechange = function() {
	//	if (req.responseText) alert(req.responseText);
		if (req.readyState == 4) {

    		if (req.responseJS.result) {

			  var message = req.responseJS.result;
			  var errors = req.responseJS.errors;
	          var focus = req.responseJS.focus;

	            if (errors != '') close_message('error', errors, focus);
	            else { close_message('info', message, focus); }

    		}

    		close_message();

		}
    }

}




//flash
function AC_AddExtension(a,b){if(a.indexOf('?')!=-1)return a.replace(/\?/,b+'?');else return a+b}function AC_Generateobj(a,b,c){var d='<object ';for(var i in a)d+=i+'="'+a[i]+'" ';d+='>';for(var i in b)d+='<param name="'+i+'" value="'+b[i]+'" /> ';d+='<embed ';for(var i in c)d+=i+'="'+c[i]+'" ';d+=' ></embed></object>';document.write(d)}function AC_FL_RunContent(){var a=AC_GetArgs(arguments,".swf","movie","clsid:d27cdb6e-ae6d-11cf-96b8-444553540000","application/x-shockwave-flash");AC_Generateobj(a.objAttrs,a.params,a.embedAttrs)}function AC_SW_RunContent(){var a=AC_GetArgs(arguments,".dcr","src","clsid:166B1BCA-3F9C-11CF-8075-444553540000",null);AC_Generateobj(a.objAttrs,a.params,a.embedAttrs)}function AC_GetArgs(a,b,c,d,e){var f=new Object();f.embedAttrs=new Object();f.params=new Object();f.objAttrs=new Object();for(var i=0;i<a.length;i=i+2){var g=a[i].toLowerCase();switch(g){case"classid":break;case"pluginspage":f.embedAttrs[a[i]]=a[i+1];break;case"src":case"movie":a[i+1]=AC_AddExtension(a[i+1],b);f.embedAttrs["src"]=a[i+1];f.params[c]=a[i+1];break;case"onafterupdate":case"onbeforeupdate":case"onblur":case"oncellchange":case"onclick":case"ondblClick":case"ondrag":case"ondragend":case"ondragenter":case"ondragleave":case"ondragover":case"ondrop":case"onfinish":case"onfocus":case"onhelp":case"onmousedown":case"onmouseup":case"onmouseover":case"onmousemove":case"onmouseout":case"onkeypress":case"onkeydown":case"onkeyup":case"onload":case"onlosecapture":case"onpropertychange":case"onreadystatechange":case"onrowsdelete":case"onrowenter":case"onrowexit":case"onrowsinserted":case"onstart":case"onscroll":case"onbeforeeditfocus":case"onactivate":case"onbeforedeactivate":case"ondeactivate":case"type":case"codebase":f.objAttrs[a[i]]=a[i+1];break;case"width":case"height":case"align":case"vspace":case"hspace":case"class":case"title":case"accesskey":case"name":case"id":case"tabindex":f.embedAttrs[a[i]]=f.objAttrs[a[i]]=a[i+1];break;default:f.embedAttrs[a[i]]=f.params[a[i]]=a[i+1]}}f.objAttrs["classid"]=d;if(e)f.embedAttrs["type"]=e;return f}
