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;

/// JsHttpRequest
function JsHttpRequest(){var i=this;i.onreadystatechange=null;i.readyState=0;i.responseText=null;i.responseXML=null;i.status=200;i.statusText="OK";i.responseJS=null;i.caching=false;i.loader=null;i.session_name="PHPSESSID";i._0=null;i._1=[];i._3=null;i._5={inv_form_el:"Invalid FORM element detected: name=%, tag=%",must_be_single_el:"If used, <form> must be a single HTML element in the list.",js_invalid:"JavaScript code generated by backend is invalid!\n%",url_too_long:"Cannot use so long query with GET request (URL is larger than % bytes)",unk_loader:"Unknown loader: %",no_loaders:"No loaders registered at all, please check JsHttpRequest.LOADERS array",no_loader_matched:"Cannot find a loader which may process the request. Notices are:\n%",no_headers:"Method setRequestHeader() cannot work together with the % loader."};i.abort=function(){with(this){if(_0&&_0.abort){_0.abort()}_6();if(readyState==0){return}if(readyState==1&&!_0){readyState=0;return}_4(4,true)}};i.open=function(a,b,c,f,d){with(this){try{if(document.location.search.match(new RegExp("[&?]"+session_name+"=([^&?]*)"))||document.cookie.match(new RegExp("(?:;|^)\\s*"+session_name+"=([^;]*)"))){b+=(b.indexOf("?")>=0?"&":"?")+session_name+"="+this.escape(RegExp.$1)}}catch(e){}_3={method:(a||"").toUpperCase(),url:b,asyncFlag:c,username:f!=null?f:"",password:d!=null?d:""};_0=null;_4(1,true);return true}};i.send=function(a){if(!this.readyState){return}this._4(1,true);this._0=null;var b=[];var c=[];if(!this._7(a,null,b,c)){return}var f=null;if(this.caching&&!c.length){f=this._3.username+":"+this._3.password+"@"+this._3.url+"|"+b+"#"+this._3.method;var d=JsHttpRequest.CACHE[f];if(d){this._8(d[0],d[1]);return false}}var j=(this.loader||"").toLowerCase();if(j&&!JsHttpRequest.LOADERS[j]){return this._2("unk_loader",j)}var k=[];var g=JsHttpRequest.LOADERS;for(var l in g){var h=g[l].loader;if(!h){continue}if(j&&l!=j){continue}var m=new h(this);JsHttpRequest.extend(m,this._3);JsHttpRequest.extend(m,{queryText:b.join("&"),queryElem:c,id:(new Date().getTime())+""+JsHttpRequest.COUNT++,hash:f,span:null});var n=m.load();if(!n){this._0=m;JsHttpRequest.PENDING[m.id]=this;return true}if(!j){k[k.length]="- "+l.toUpperCase()+": "+this._9(n)}else{return this._2(n)}}return l?this._2("no_loader_matched",k.join("\n")):this._2("no_loaders")};i.getAllResponseHeaders=function(){with(this){return _0&&_0.getAllResponseHeaders?_0.getAllResponseHeaders():[]}};i.getResponseHeader=function(a){with(this){return _0&&_0.getResponseHeader?_0.getResponseHeader():[]}};i.setRequestHeader=function(a,b){with(this){_1[_1.length]=[a,b]}};i._8=function(a,b){with(this){if(caching&&_0){JsHttpRequest.CACHE[_0.hash]=[a,b]}if(a!==null||b!==null){status=4;responseText=responseXML=a;responseJS=b}else{status=500;responseText=responseXML=responseJS=null}_4(2);_4(3);_4(4);_6()}};i._9=function(a){var b=0,c=0,f=this._5[a[0]];while((c=f.indexOf("%",c))>=0){var d=a[++b]+"";f=f.substring(0,c)+d+f.substring(c+1,f.length);c+=1+d.length}return f};i._2=function(a){a=this._9(typeof(a)=="string"?arguments:a);a="JsHttpRequest: "+a;if(!window.Error){throw a;}else{if((new Error(1,"test")).description=="test"){throw new Error(1,a);}else{throw new Error(a);}}};i._7=function(a,b,c,f){if(b==null){b=""}if(a instanceof Object){var d=false;for(var j in a){var k=a[j];if(k instanceof Function){continue}var g=b?b+"["+this.escape(j)+"]":this.escape(j);var l=k&&k.parentNode&&k.parentNode.appendChild&&k.tagName;if(l){var h=k.tagName.toUpperCase();if(h=="FORM"){d=true}else{if(h=="INPUT"||h=="TEXTAREA"||h=="SELECT"){}else{return this._2("inv_form_el",(e.name||""),e.tagName)}}f[f.length]={name:g,e:k}}else{if(k instanceof Object){this._7(k,g,c,f)}else{if(k===null){continue}c[c.length]=g+"="+this.escape(""+k)}}if(d&&f.length>1){return this._2("must_be_single_el")}}}else{c[c.length]=a}return true};i._6=function(){var a=this._0;if(!a){return}JsHttpRequest.PENDING[a.id]=false;var b=a.span;if(!b){return}a.span=null;var c=function(){b.parentNode.removeChild(b)};JsHttpRequest.setTimeout(c,50)};i._4=function(a,b){with(this){if(b){status=statusText=responseJS=null;responseText=""}readyState=a;if(onreadystatechange){onreadystatechange()}}};i.escape=function(a){return escape(a).replace(new RegExp("\\+","g"),"%2B")}}JsHttpRequest.COUNT=0;JsHttpRequest.MAX_URL_LEN=2000;JsHttpRequest.CACHE={};JsHttpRequest.PENDING={};JsHttpRequest.LOADERS={};JsHttpRequest._b=function(){};JsHttpRequest.TIMEOUTS={s:window.setTimeout,c:window.clearTimeout};JsHttpRequest.setTimeout=function(a,b){window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.s;if(typeof(a)=="string"){c=window.JsHttpRequest_tmp(a,b)}else{var c=null;var f=function(){a();delete JsHttpRequest.TIMEOUTS[c]};c=window.JsHttpRequest_tmp(f,b);JsHttpRequest.TIMEOUTS[c]=f}window.JsHttpRequest_tmp=null;return c};JsHttpRequest.clearTimeout=function(a){window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.c;delete JsHttpRequest.TIMEOUTS[a];var b=window.JsHttpRequest_tmp(a);window.JsHttpRequest_tmp=null;return b};JsHttpRequest.query=function(a,b,c,f){var d=new this();d.caching=!f;d.onreadystatechange=function(){if(d.readyState==4){c(d.responseJS,d.responseText)}};var j=null;if(a.match(/^((\w+)\.)?(GET|POST)\s+(.*)/i)){d.loader=RegExp.$2?RegExp.$2:null;j=RegExp.$3;a=RegExp.$4}d.open(j,a,true);d.send(b)};JsHttpRequest.dataReady=function(a){var b=this.PENDING[a.id];delete this.PENDING[a.id];if(b){b._8(a.text,a.js)}else{if(b!==false){throw"dataReady(): unknown pending id: "+a.id;}}};JsHttpRequest.extend=function(a,b){for(var c in b){a[c]=b[c]}};JsHttpRequest.LOADERS.xml={loader:function(d){JsHttpRequest.extend(d._5,{xml_no:"Cannot use XMLHttpRequest or ActiveX loader: not supported",xml_no_diffdom:"Cannot use XMLHttpRequest to load data from different domain %",xml_no_headers:"Cannot use XMLHttpRequest loader or ActiveX loader, POST method: headers setting is not supported, needed to work with encodings correctly",xml_no_form_upl:"Cannot use XMLHttpRequest loader: direct form elements using and uploading are not implemented"});this.load=function(){if(this.queryElem.length){return["xml_no_form_upl"]}if(this.url.match(new RegExp("^([a-z]+)://([^\\/]+)(.*)","i"))){if(RegExp.$2.toLowerCase()==document.location.hostname.toLowerCase()){this.url=RegExp.$3}else{return["xml_no_diffdom",RegExp.$2]}}var a=null;if(window.XMLHttpRequest){try{a=new XMLHttpRequest()}catch(e){}}else{if(window.ActiveXObject){try{a=new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}if(!a){try{a=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){}}}}if(!a){return["xml_no"]}var b=window.ActiveXObject||a.setRequestHeader;if(!this.method){this.method=b?"POST":"GET"}if(this.method=="GET"){if(this.queryText){this.url+=(this.url.indexOf("?")>=0?"&":"?")+this.queryText}this.queryText="";if(this.url.length>JsHttpRequest.MAX_URL_LEN){return["url_too_long",JsHttpRequest.MAX_URL_LEN]}}else{if(this.method=="POST"&&!b){return["xml_no_headers"]}}this.url+=(this.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+(d.caching?"0":this.id)+"-xml";var c=this.id;a.onreadystatechange=function(){if(a.readyState!=4){return}a.onreadystatechange=JsHttpRequest._b;d.status=null;try{d.status=a.status;d.responseText=a.responseText}catch(e){}if(!d.status){return}try{eval("JsHttpRequest._a = function(id) { var d = "+d.responseText+"; d.id = id; JsHttpRequest.dataReady(d); }")}catch(e){return d._2("js_invalid",d.responseText)}JsHttpRequest._a(c);JsHttpRequest._a=null};a.open(this.method,this.url,true,this.username,this.password);if(b){for(var f=0;f<d._1.length;f++){a.setRequestHeader(d._1[f][0],d._1[f][1])}a.setRequestHeader("Content-Type","application/octet-stream")}a.send(this.queryText);this.span=null;this.xr=a;return null};this.getAllResponseHeaders=function(){return this.xr.getAllResponseHeaders()};this.getResponseHeader=function(a){return this.xr.getResponseHeader(a)};this.abort=function(){this.xr.abort();this.xr=null}}};JsHttpRequest.LOADERS.script={loader:function(j){JsHttpRequest.extend(j._5,{script_only_get:"Cannot use SCRIPT loader: it supports only GET method",script_no_form:"Cannot use SCRIPT loader: direct form elements using and uploading are not implemented"});this.load=function(){if(this.queryText){this.url+=(this.url.indexOf("?")>=0?"&":"?")+this.queryText}this.url+=(this.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+this.id+"-script";this.queryText="";if(!this.method){this.method="GET"}if(this.method!=="GET"){return["script_only_get"]}if(this.queryElem.length){return["script_no_form"]}if(this.url.length>JsHttpRequest.MAX_URL_LEN){return["url_too_long",JsHttpRequest.MAX_URL_LEN]}if(j._1.length){return["no_headers","SCRIPT"]}var a=this,b=document,c=null,f=b.body;if(!window.opera){this.span=c=b.createElement("SCRIPT");var d=function(){c.language="JavaScript";if(c.setAttribute){c.setAttribute("src",a.url)}else{c.src=a.url}f.insertBefore(c,f.lastChild)}}else{this.span=c=b.createElement("SPAN");c.style.display="none";f.insertBefore(c,f.lastChild);c.innerHTML="Workaround for IE.<script></script>";var d=function(){c=c.getElementsByTagName("SCRIPT")[0];c.language="JavaScript";if(c.setAttribute){c.setAttribute("src",a.url)}else{c.src=a.url}}}JsHttpRequest.setTimeout(d,10);return null}}};JsHttpRequest.LOADERS.form={loader:function(r){JsHttpRequest.extend(r._5,{form_el_not_belong:"Element \"%\" does not belong to any form!",form_el_belong_diff:"Element \"%\" belongs to a different form. All elements must belong to the same form!",form_el_inv_enctype:"Attribute \"enctype\" of the form must be \"%\" (for IE), \"%\" given."});this.load=function(){var g=this;if(!g.method){g.method="POST"}g.url+=(g.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+g.id+"-form";if(r._1.length){return["no_headers","FORM"]}if(g.method=="GET"){if(g.queryText){g.url+=(g.url.indexOf("?")>=0?"&":"?")+g.queryText}if(g.url.length>JsHttpRequest.MAX_URL_LEN){return["url_too_long",JsHttpRequest.MAX_URL_LEN]}var l=g.url.split("?",2);g.url=l[0];g.queryText=l[1]||""}var h=null;var m=false;if(g.queryElem.length){if(g.queryElem[0].e.tagName.toUpperCase()=="FORM"){h=g.queryElem[0].e;m=true;g.queryElem=[]}else{h=g.queryElem[0].e.form;for(var n=0;n<g.queryElem.length;n++){var i=g.queryElem[n].e;if(!i.form){return["form_el_not_belong",i.name]}if(i.form!=h){return["form_el_belong_diff",i.name]}}}if(g.method=="POST"){var s="multipart/form-data";var t=(h.attributes.encType&&h.attributes.encType.nodeValue)||(h.attributes.enctype&&h.attributes.enctype.value)||h.enctype;if(t!=s){return["form_el_inv_enctype",s,t]}}}var o=h&&(h.ownerDocument||h.document)||document;var q="jshr_i_"+g.id;var p=g.span=o.createElement("DIV");p.style.position="absolute";p.style.visibility="hidden";p.innerHTML=(h?"":"<form"+(g.method=="POST"?" enctype=\"multipart/form-data\" method=\"post\"":"")+"></form>")+"<iframe name=\""+q+"\" id=\""+q+"\" style=\"width:0px; height:0px; overflow:hidden; border:none\"></iframe>";if(!h){h=g.span.firstChild}o.body.insertBefore(p,o.body.lastChild);var u=function(a,b){var c=[];var f=a;if(a.mergeAttributes){var f=o.createElement("form");f.mergeAttributes(a,false)}for(var d=0;d<b.length;d++){var j=b[d][0],k=b[d][1];c[c.length]=[j,f.getAttribute(j)];f.setAttribute(j,k)}if(a.mergeAttributes){a.mergeAttributes(f,false)}return c};var v=function(){top.JsHttpRequestGlobal=JsHttpRequest;var a=[];if(!m){for(var b=0,c=h.elements.length;b<c;b++){a[b]=h.elements[b].name;h.elements[b].name=""}}var f=g.queryText.split("&");for(var b=f.length-1;b>=0;b--){var d=f[b].split("=",2);var j=o.createElement("INPUT");j.type="hidden";j.name=unescape(d[0]);j.value=d[1]!=null?unescape(d[1]):"";h.appendChild(j)}for(var b=0;b<g.queryElem.length;b++){g.queryElem[b].e.name=g.queryElem[b].name}var k=u(h,[["action",g.url],["method",g.method],["onsubmit",null],["target",q]]);h.submit();u(h,k);for(var b=0;b<f.length;b++){h.lastChild.parentNode.removeChild(h.lastChild)}if(!m){for(var b=0,c=h.elements.length;b<c;b++){h.elements[b].name=a[b]}}};JsHttpRequest.setTimeout(v,100);return null}}};

function show_catalog(){
   var link = ($('mark').value) ? '/'+$('mark').value+'/catalogue/' : '/catalogue/';
   link += ($('mech').value) ? '?mech='+$('mech').value : '';
   link += ($('sex').value) ? ($('mech').value?'&':'?')+'sex='+$('sex').value : '';
   if (!$('mark').value && !$('mech').value && !$('sex').value) close_message('info','Выберите хотя бы один параметр поиска');
   else location.href = link;
   //$('filter_data').submit();
}

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;
		   }
}

}


function show_message(text){
	if (text==undefined) text = 'Обработка данных';
	if (!$('loading-box')) return false;
	var top = (document.body.scrollTop>0) ? document.body.scrollTop : document.documentElement.scrollTop;
	$('loading-box').style.width = '270px';
	$('loading-box').style.textAlign = 'center';
	$('loading-box').style.display = 'block';
    	$('loading-actions').style.display = 'none';
    	$('loading-actions-confirm').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';

	var new_height = $('loading-box').offsetHeight;
	var top = (document.body.scrollTop>0) ? document.body.scrollTop : document.documentElement.scrollTop;
	//var scr_height=0; if (self.screen) scr_height = screen.height
	//else if (self.java) { var jkit = java.awt.Toolkit.getDefaultToolkit(); var scrsize = jkit.getScreenSize(); scr_height = scrsize.height;	}
	//var body_height = (scr_height>0 && document.body.clientHeight>scr_height) ? scr_height-150 : document.body.clientHeight;
	body_height = document.body.clientHeight;
	var new_top = (parseInt(top,10)+(body_height/2)-(new_height/2)-30);
	if (!isIE6) $('loading-box').style.top = new_top+'px';

	var new_width = $('loading-box').offsetWidth;
	$('loading-box').style.left = ((document.body.clientWidth/2)-(new_width/2))+'px';

	$('loading-img').style.display = '';
	$('loading-text').innerHTML = text+', пожалуйста подождите...';
}

function close_message(status, text, focus){
	if (!$('loading-box')) { alert(text); return true; }
    OK = false;
	$('loading-box').style.display = 'block';
	$('loading-box').style.textAlign = 'left';
	$('loading-box').style.left = '0px';

	if (navigator.appName == 'Opera' || isIE6) {
		$('loading-box').style.width = '270px';
		$('loading-box').style.height = '70px';
	}
	else {
		$('loading-box').style.width = 'auto';
		$('loading-box').style.height = 'auto';
		}


   	$('loading-actions').style.display = 'none';
   	$('loading-actions-confirm').style.display = 'none';

	if (status==undefined) {
		$('loading-box').style.display = 'none';
		return false;
		}
	else if (status=='info') {
		$('loading-img').style.display = 'none';
		if (text==undefined) text = 'Информация';
		$('loading-text').innerHTML = '<br /><img class="image" src="/_admincp/_design/img/icons/warning.png" />&nbsp;'+text+'';
	    $('loading-actions').style.display = '';
	} else if (status=='confirm') {
		OK = true;
		$('loading-img').style.display = 'none';
		if (text==undefined) text = 'Информация';
		$('loading-text').innerHTML = '<br />&nbsp;'+text+'';     //<img class="image" src="/_admincp/_design/img/icons/warning.png" />
	    $('loading-actions').style.display = 'none';
	    $('loading-actions-confirm').style.display = '';
	}
	else if (status=='error') {
		$('loading-img').style.display = 'none';
		if (text==undefined) text = 'Произошла ошибка';
		$('loading-text').innerHTML = '<br /><img class="image" src="/_admincp/_design/img/icons/error.png" />&nbsp;'+text+'';
	    $('loading-actions').style.display = '';
	}

	var new_height = $('loading-box').offsetHeight;
//	if (navigator.appName == 'Microsoft Internet Explorer' && /MSIE 6.0/i.test(navigator.userAgent)) var top = 0;
//	else var top = (document.body.scrollTop>0) ? document.body.scrollTop : document.documentElement.scrollTop;

	var new_height = $('loading-box').offsetHeight;
	var top = (document.body.scrollTop>0) ? document.body.scrollTop : document.documentElement.scrollTop;
	//var half_screen_height = (screen.height>0) ? (screen.height/2)-parseInt(screen.height/8) : (document.body.clientHeight/2);
	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();

}


// ****************************************** //
// ********* <<<<<<   ФИЛЬТР		   ****** //
// ****************************************** //
function execute_filter(){	var brend = $('brend');
	var catalog1 = $('catalog1');
	var catalog2 = $('catalog2');
	if (brend.value == 0) close_message('info', 'Необходимо выбрать производителя', 'brend');
	else if (catalog1.value == 0) close_message('info', 'Необходимо выбрать категорию товара', 'catalog1');
	else if (brend.value == 'all' && catalog1.value == 'all') close_message('info', 'Необходимо выбрать подкатегорию товара', 'catalog2');
	else document.filter.submit();
}

// ФИЛЬТР - выборка по трем полям
function load_filter(active){

	var brend = $('brend');
	var catalog1 = $('catalog1');
	var catalog2 = $('catalog2');
    var change_select;

	switch(active){
		case 1: catalog1.disabled=true;
				catalog2.disabled=true;
				catalog1.value = 0;
				catalog2.value = 0;
				change_select = catalog1;
				break;
		case 2: catalog2.disabled=true;
				catalog2.value = 0;
				change_select = catalog2;
				break;
		case 3: document.filter.submit(); return true;
	}

   if (active == 1 && brend.value == 0) return true;
   else if (active == 2 && catalog1.value == 0) return true;

	show_message();

	var value1 = brend.value;
	var value2 = catalog1.value;
	var value3 = catalog2.value;

  var req = new JsHttpRequest();
  req.open(null, '/js/_ajax/fetch.php', true);
  var data = { 'brend': value1, 'catalog1': value2, 'catalog2' : value3, 'active_field': active};
  req.send(data);

  req.onreadystatechange = function() {

//	$('debug').innerHTML = req.responseText;

  	if (req.readyState == 4) {

		if (req.responseJS.errors!=''){			if (active == 2) { document.filter.submit(); return true; }
			else { close_message('error', req.responseJS.errors); return true; }		} else {
	 		var massiv = new Array();
		    var keys = new Array();
	 		values = req.responseJS.values;
	 		keys = req.responseJS.keys;

 			///alert(value1+' ::: '+value2+' ::: '+value3); //+' === '+values);

			if (values.length>0) {
				change_select.length = 1;

				if (values.length>1 && (active==1 || (active==2 && (value1!='all' || value2!='all')))) {		 	    	 var option = document.createElement('option');
		     	 	 //option.id = 'all';
	             	 option.value = 'all';
		         	 option.innerHTML = (active==1) ? 'Все категории': 'Все подкатегории';
				 	 change_select.appendChild(option);					}

		        for (i = 0; i<values.length; i++) {
		 	    	 var option = document.createElement('option');
		     	 	 //option.id = 'value_'+i;
	             	 option.value = keys[i];
		         	 option.innerHTML = values[i];
				 	 change_select.appendChild(option);
		       	}
			}

			switch(active){
				case 1: catalog1.disabled=false; break;
				case 2: catalog2.disabled=false; break;
			}

			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', 'Ваша корзина пуста');
return result;}

// добавить позицию в корзину
function add_product(sid, catalog_id, id, price, action) {
  var spec_price = 1;
  if ($('new_pr'+id) && $('p2_'+id) && $('p1_'+id)) {
  	if (!$('p1_'+id).checked && !$('p2_'+id).checked) { close_message('info','Выберите пожалуйста цену'); return false;}
  	if ($('p2_'+id).checked) if (!isNaN(parseInt($('new_pr'+id).innerHTML))) {
  			price = parseInt($('new_pr'+id).innerHTML);
  			spec_price = 2;
  	}
  }

  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, 'spec_price' : spec_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 ($('lba') != null) $('lba').style.display = 'none';
				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('confirm','Товар добавлен в корзину<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';
        	}

			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;
					if ($('lba')) $('lba').style.display = 'none';
					$('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';
					if ($('lba')) $('lba').style.display = '';
					$('whole_basket').innerHTML = '<br>Ваша корзина пуста';
					if ($('order_table')!=null) $('order_table').style.display = 'none';
					if ($('divbasket') != null) $('divbasket').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;
					if ($('lba')) $('lba').style.display = 'none';
					$('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 = '';

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 адрес"'; if (focus=='') focus = 'email_'+name; }

if ($('fio_'+name)!=null) {	if ($('fio_'+name).value=='') { errors[1] = 'Не заполнено поле "Контактное лицо"'; if (focus=='') focus = 'fio_'+name; }
	//else if (/^[\w\(\)\ \.\,\+]{2,}$/i.test($('fio_'+name).value)==false) { errors[1] = 'Не корректно заполнено поле "Контактное лицо"'; if (focus=='') focus = 'fio_'+name; }
}
if ($('country_'+name)!=null) if ($('country_'+name).value=='') { errors[2] = 'Не заполнено поле "Cтрана"'; if (focus=='') focus = 'country_'+name; }
if ($('phone_'+name)!=null) {			if ($('phone_'+name).value=='') { errors[3] = 'Не заполнено поле "Телефон"'; if (focus=='') focus = 'phone_'+name; }
			else if (/^[\d\-\(\)\ \.\,\+]{4,}$/i.test($('phone_'+name).value)==false) { errors[3] = 'Не корректно введен "Телефон"'; if (focus=='') focus = 'phone_'+name; }
			}
if ($('post_code_'+name)!=null) if ($('post_code_'+name).value=='') { errors[5] = 'Не заполнено поле "Индекс города"'; if (focus=='') focus = 'post_code_'+name; }
if ($('oblast_'+name)!=null) if ($('oblast_'+name).value=='' && $('oblast_'+name).style.display == '') { errors[6] = 'Не заполнено поле "Область"'; if (focus=='') focus = 'oblast_'+name; }
if ($('city_'+name)!=null) if ($('city_'+name).value=='' && $('city_'+name).style.display == '') { errors[7] = 'Не заполнено поле "Населенный пункт"'; if (focus=='') focus = 'city_'+name; }
if ($('address_'+name)!=null) if ($('address_'+name).value=='') { errors[8] = 'Не заполнено поле "Адрес"'; if (focus=='') focus = 'address_'+name; }
if (name=='2.1' && $('confrim1')!=null && $('confrim2')!=null) if ($('confrim1').checked==false && $('confrim2').checked==false) { errors[9] = 'Не указано подтверждение Вашего заказа по телефону'; }
if (name=='2.2' && $('confrim3')!=null && $('confrim4')!=null) if ($('confrim3').checked==false && $('confrim4').checked==false) { errors[10] = 'Не указано подтверждение Вашего заказа по телефону'; }

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){

   var frms = $('all_forms').getElementsByTagName('div');
   if (frms.length>0) for(var i=0;i<frms.length;i++) if (frms[i].id && /^form\_st\_/i.test(frms[i].id)){
	frms[i].style.display = 'none';
   }
   if ($('form_st_'+name)) $('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);
   if (name == '3.2') total_price = total_price + 4000;

   $('price_delivery').innerHTML = total_price;
//   $('help').style.display = 'none';
//   $('order_title').style.display = '';
   if ($('price_value_'+name)) $('price_value_'+name).value = total_price;
   $('delivery_type').value = name;

}

// проверка на введенное количество
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() {
//			$('debug').innerHTML = 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){
        if (!new_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 == '') addCookie(cookie_name, new_values, period, path);
        else {
            var values = (cookie_value+','+new_values).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 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){
 if (e!=null && e.value!='') e.className = '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() {
		 //$('bg').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+'"')
        }
}





//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2008 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
function ControlVersion()
{
	var version;
	var axo;
	var e;
	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry
	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}
	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful.

			// default to the first public version
			version = "WIN 6,0,21,0";
			// throws if AllowScripAccess does not exist (introduced in 6.0r47)
			axo.AllowScriptAccess = "always";
			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}

	return version;
}
// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;

	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}
	return flashVer;
}
// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];
        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?');
  else
    return src + ext;
}
function AC_Generateobj(objAttrs, params, embedAttrs)
{
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }
  document.write(str);
}
function AC_FL_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
function AC_SW_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();
    switch (currArg){
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[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":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace":
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}




var timer;
        function scrolldelta(id,dy) {
            if (dy != 0) {
                doScroll(id,dy);
            } else {
                if (timer != undefined) clearTimeout(timer);
            }
        }


        function doScroll(id,dy) {
            var target = document.getElementById(id);
            target.scrollTop = target.scrollTop + dy
            timer = setTimeout("doScroll("+id+","+dy+");", 25);
            }


function change_city(id, value){

	if (value == 'other') {
		document.getElementById(id).style.display = '';
	} else document.getElementById(id).style.display = 'none';
}

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;
   }
}





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
}

function showhint(menucontents, obj, e, tipwidth){
	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=hidetip
}
}

function hidetip(e){
dropmenuobj.style.visibility="hidden"
dropmenuobj.style.left="-500px"
dropmenuobj.style.display = '';
}


function send_sms(phone,message){
	var req = new JsHttpRequest();
	req.open(null, '/inc/Modules/sms/_ajax/send_sms.php', true);
	var data = { 'phone': phone, 'message': message };
        req.send(data);
        //show_message();

	   	req.onreadystatechange = function() {
	    //if (req.responseText) alert(req.responseText);
    	   if (req.readyState == 4) {
			var result = req.responseJS.result;
			var errors = req.responseJS.errors;
			var type = req.responseJS.type;

            /*
            if (errors != '') { if (type == 'WARNING') close_message('info', errors); else close_message('error', errors); }
            else if (result && type == 'OK'){
					close_message('info', result, 'sms_code');
            } else close_message('info','По техническим причинам сервис SMS временно недоступен');
            */
         }
        }
}