var GB_ROOT_DIR = "/js/GreyBox/";
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;

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';
		    else if (GB_CURRENT != null) parent.parent.GB_hide();
		    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 = 'Обработка данных';
	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-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){

    OK = false;
	$('loading-box').style.display = 'block';
	$('loading-box').style.textAlign = 'left';
	$('loading-box').style.left = '0px';
	if (navigator.appName == 'Opera') {
	$('loading-box').style.width = '200px';

	}
	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;
	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 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 left_color = ($('left_color') && $('left_eye').checked == true) ? $('left_color').value : '';
  var left_radius = ($('left_radius') && $('left_eye').checked == true) ? $('left_radius').value : '';
  var left_strong = ($('left_strong') && $('left_eye').checked == true) ? $('left_strong').value : '';

  var right_color = ($('right_color') && $('right_eye').checked == true) ? $('right_color').value : '';
  var right_radius = ($('right_radius') && $('right_eye').checked == true) ? $('right_radius').value : '';
  var right_strong = ($('right_strong') && $('right_eye').checked == true) ? $('right_strong').value : '';

  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, 'left_color' : left_color, 'left_radius' : left_radius, 'left_strong' : left_strong, 'right_color' : right_color, 'right_radius' : right_radius, 'right_strong' : right_strong };
        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 ($('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-2 == 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+' руб.';
					//$('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_form')!=null) $('order_form').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+' руб.';
					//$('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 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 choose_delivery_type(name){
   $('form_st_1.1').style.display = 'none';
   $('form_st_1.2').style.display = 'none';
   $('form_st_2.1').style.display = 'none';
   $('form_st_2.2').style.display = 'none';
   $('form_st_3.1').style.display = 'none';
   $('form_st_3.2').style.display = 'none';

   var total_price = $('total_price').innerHTML;
   total_price = total_price - 0;
   if (name == '2.2') total_price = Math.ceil((total_price + 500)*1.087);
   if (name == '3.1') total_price = total_price + 1500;
   if (name == '3.2') total_price = total_price + 4000;

   $('price_delivery').innerHTML = total_price+' руб.';
   $('help').style.display = 'none';
   $('order_title').style.display = '';
   $('form_st_'+name).style.display = '';
   $('delivery_type').value = name;
   $('price_value_'+name).value = total_price;
}






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;
            initLightbox();
			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 (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() {
		//$('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 eye_value(e){

if (e.parentNode) {
   var selects = e.parentNode.getElementsByTagName('select');
   if (selects.length>0) for (var i=0; i<selects.length; i++) selects[i].disabled = (e.checked == false) ? true : false;

}


}
