var AC_FL_RunContent = 0;
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 showtext (what) {
	if (document.getElementById("extratext").className !='extratext') {
		document.getElementById("extratext").className = 'extratext';
		what.innerHTML = "Закрыть";
	} else {
		document.getElementById("extratext").className = 'extratext un';
		what.innerHTML = "Подробнее";
	}
}


function doc(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 && doc('loading-box').style.display == 'block')  {  hideShadow();
		    doc('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) { hideShadow();
		    if (doc('loading-box').style.display == 'block') doc('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;
		   }
}
return false;
}

function getClientWidth()
{return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;}

function getClientHeight()
{return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;}


//
function show_message(text){
	if (text==undefined) text = 'Обработка данных';
	doc('loading-box').style.display = 'block';
	doc('msgheader').style.backgroundImage = 'none';
	doc('msgtext').innerHTML = '';
	doc('msgheader').innerHTML = text+', пожалуйста подождите...';
	//позиция окошка
	var top = getBodyScrollTop();
	var bottom = top+getClientHeight();
	var height = doc('loading-box').offsetHeight;
	doc('loading-box').style.top = ''+Math.round(top+(bottom-top)/2-height/2)+'px';
}

//
function close_message(status, text, focus, action, header){
	var top = (document.body.scrollTop>0) ? document.body.scrollTop : document.documentElement.scrollTop;
	
	if (status==undefined && doc('loading-box') && doc('loading-box').style.display == 'none') {
		return false;
	}
    OK = false;
	doc('loading-box').style.display = 'block';

	if (text==undefined && status!='error') text = 'Информация';
	if (action==undefined) action = '';

	if (status==undefined) {
		doc('loading-box').style.display = 'none';
		return false;
		}
	else if (status=='info') {
		if (header=='') header = 'Информация';
		doc('msgheader').style.backgroundImage = 'url(/img/info.gif)';
	} else if (status=='error') {
		if (header=='') header = 'Ошибка';
		if (text==undefined) text = 'Произошла ошибка';
		doc('msgheader').style.backgroundImage = 'url(/img/error.gif)';
		doc('msgtext').innerHTML = ''+text+'';
	} else {
		if (header=='') header = 'Сообщение';
		doc('msgheader').style.backgroundImage = 'none';
		doc('msgtext').innerHTML = ''+text+'';		
	}
	if (header==''||header==undefined) {header = text; text = '';}
	doc('msgtext').innerHTML = ''+text+'';
	doc('msgheader').innerHTML = ''+header+'';
	
	//var top = getBodyScrollTop();
	var mstop = top+100;
	
	doc('loading-box').style.top = ''+mstop+'px';

	doc('loading-box').focus();
 	if (isIE6) reloadPage();

}


// Функция trim удаляет пробелы
// в начале и в конце строки
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

// ****************************************** //
// ********* <<<<<<   ФИЛЬТР		   ****** //
// ****************************************** //
function execute_filter(){
	var brend = doc('brend');
	var catalog1 = doc('catalog1');
	var catalog2 = doc('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 = doc('brend');
	var catalog1 = doc('catalog1');
	var catalog2 = doc('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() {

//	doc('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 (doc('empty_shopping_cart')!=null) result = (doc('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 req = new JsHttpRequest();
	req.open(null, '/js/_ajax/basket/add.php', true);
	var data = { 'sid': sid, 'catalog_id': catalog_id, 'id': id, 'price' : price };
        req.send(data);

	if (action!='купить') show_message('Добавление товара в корзину');

    	req.onreadystatechange = function() {
		if (req.readyState == 4) {
//		alert(req.responseText);

			var quantity = req.responseJS.quantity;
			var total_price = req.responseJS.total_price;

			if (quantity>0) {
				if (doc('empty_shopping_cart') != null) doc('empty_shopping_cart').style.display = 'none';
				if (doc('shopping_cart') != null) doc('shopping_cart').style.display = '';
				if (doc('quantity') != null) doc('quantity').innerHTML = quantity;
				if (doc('total_price') != null) doc('total_price').innerHTML = total_price;
				if (doc('ending') != null) doc('ending').innerHTML = req.responseJS.end;
				if (doc('basket_'+id) != null) doc('basket_'+id).src = '/_templates/default/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 = doc('tr_'+id).parentNode.id;
		removeElement(parent,'tr_'+id);
        if (doc(parent)) {
        	var parent_table = doc(parent).parentNode.id;
        	var trs = doc(parent).getElementsByTagName('tr').length;
        	if (trs-2 == 0 && parent_table) doc(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 && doc('recount_ids')!=null) doc('recount_ids').value = ids;
					//if (doc('delivery_type')!=null) var delivery = doc('delivery_type').value;
					if (doc('t_price')!=null) doc('t_price').innerHTML = total_price+' руб.';
					//doc('price_delivery').innerHTML = total_price+' руб.';
					doc('empty_shopping_cart').style.display = 'none';
					doc('shopping_cart').style.display = '';
					if (doc('quantity')!=null) doc('quantity').innerHTML = quantity;
					if (doc('total_price')!=null) doc('total_price').innerHTML = total_price;
					if (doc('ending')!=null) doc('ending').innerHTML = req.responseJS.end;
					//if (doc('delivery_type')!=null) choose_delivery_type(delivery);
			}
			else {
					doc('empty_shopping_cart').style.display = '';
					doc('shopping_cart').style.display = 'none';
					doc('whole_basket').innerHTML = '<br>Ваша корзина пуста';
					if (doc('order_form')!=null) doc('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 (doc('recount_ids')!=null) products = doc('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 (doc('quantity_'+products[i])!=null) {
	values[j] = doc('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(){
		//doc('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 (doc('delivery_type')!=null) var delivery = doc('delivery_type').value;

				if (quantity>0) {
					if (doc('t_price')!=null) doc('t_price').innerHTML = total_price+' руб.';
					//doc('price_delivery').innerHTML = total_price+' руб.';
					doc('empty_shopping_cart').style.display = 'none';
					doc('shopping_cart').style.display = '';
					if (doc('quantity')!=null) doc('quantity').innerHTML = quantity;
					if (doc('total_price')!=null) doc('total_price').innerHTML = total_price;
					if (doc('ending')!=null) doc('ending').innerHTML = req.responseJS.end;
					//if (delivery>0) choose_delivery_type(delivery);
					if (products.length>0)
						for (i = 0; i<products.length; i++) if (doc('price_'+products[i])!=null && total_prices[k]) {
						if (total_prices[k]>0) doc('price_'+products[i]).innerHTML = product_prices[k];
						if (doc('summa_'+products[i])!=null) doc('summa_'+products[i]).innerHTML = total_prices[k];
						k++;
						}

				}

				close_message();

		}
	 }
   }
}

// проверка на введенное количество
function CheckQuantities(){

	var ids = new Array();
    if (doc('recount_ids')!=null) ids = doc('recount_ids').value.split(',');

 if (ids.length > 0) {
 	for (var i = 0; i < ids.length; i++) if (doc('quantity_'+ids[i])!=null) {

 	    inp = doc('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 (doc(parent_name) && doc(child_name)) {
  var d = doc(parent_name);
  var olddiv = doc(child_name);
  d.removeChild(olddiv);
  }
}

function choose_delivery_type(name){
   doc('form_st_1.1').style.display = 'none';
   doc('form_st_1.2').style.display = 'none';
   doc('form_st_2.1').style.display = 'none';
   doc('form_st_2.2').style.display = 'none';
   doc('form_st_3.1').style.display = 'none';
   doc('form_st_3.2').style.display = 'none';

   var total_price = doc('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;

   doc('price_delivery').innerHTML = total_price+' руб.';
   doc('help').style.display = 'none';
   doc('order_title').style.display = '';
   doc('form_st_'+name).style.display = '';
   doc('delivery_type').value = name;
   doc('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 && doc('cat_h1')!=null) {
				doc('cat_h1').innerHTML = h1;
				//if (doc('zakaz')!=null) doc('zakaz').style.display = 'none';
				}
				else if (doc('zakaz')!=null) doc('zakaz').style.display = '';

		doc('menu_catalog').innerHTML = (menu) ? menu : '';
		if (html && doc('content')!=null) doc('content').innerHTML = (html) ? html : '';
		if (nav_line && doc('navigation_line')!=null) doc('navigation_line').innerHTML = nav_line;
		if (doc('sorting')!=null) doc('sorting').style.display = (new_id==11) ? 'none' : '';

		if (doc('menu_class')!=null && sort_link) {
							doc('menu_class').className = (doc('menu_class').className == 'zag') ? 'zag2' : 'zag';
							doc('menu_class').innerHTML = sort_link;
			}

		close_message();

		////// ЗАГОЛОВОК СТРАНИЦЫ
		document.title = meta_title;

		}


	}

}


function load_catalog(cat_id, page){
  	var req = new JsHttpRequest();
  	//var id = ((doc('catalog_id')!=null)) ? doc('catalog_id').innerHTML : 0;
  	var brend = ((doc('brend_id')!=null)) ? doc('brend_id').innerHTML : 0;
	var num_on_page = doc('num_on_page').value;
	var sort_by = doc('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) doc('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 reloadPage() {
	document.body.style.display="inline";
	document.body.style.display="block";
}



////////////////////////////////////
// <<<<<ДИНАМ. ИЗМЕН. СОДЕРЖИМОГО //
////////////////////////////////////

function change_content(id, path, parent_name){
	var content = doc(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() {
//			doc('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 && doc('navigation')!=null) doc('navigation').innerHTML = navigationLine;
			//**** МЕНЮ САЙТА ****//
			//var menu = req.responseJS.menu;
			//if (menu && doc('menu')!=null) doc('menu').innerHTML = menu;
			close_message();
			reloadPage();
			}


		}
	} 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 (doc('goback')!=null) {
if (doc('goback').style.cursor == '') {
    	doc('goback').src = 'js/images/btn_left_on.png';
    	doc('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 = doc('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) {

		//doc('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 (doc('cat_'+id) != null) doc('cat_'+id).className = 'hov';
		if (!before_id && doc('cat_'+cat_id) != null && id!=cat_id) doc('cat_'+cat_id).className = '';
		if (doc('cat_'+before_id) != null && id!=before_id) doc('cat_'+before_id).className = '';
		} else {
			//alert('модули');
		}
		////// ЗАГОЛОВОК СТРАНИЦЫ
		document.title = MetaTitle;
		////// НАВИГАЦИОННАЯ ЛИНИЯ
		if (navigationLine && doc('navigation')!=null) doc('navigation').innerHTML = navigationLine;
		///// МЕНЮ САЙТА
		if (menu && doc('menu')!=null) doc('menu').innerHTML = menu;

		before_id = id;
		close_message();
		}


	}


}


function menu(id){
if (doc('img_'+id)!=null && doc('menu_'+id)!=null){
	var img = doc('img_'+id);
	var menu = doc('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 = doc('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 (doc(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) {
			//doc('avatar_image_yes').style.display = 'none';
			doc('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) && doc(el)) {
	rad_value = doc(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=doc(el+'_img').src;
	var regexp =/_.\./g;
	path = path.replace(regexp,'_'+new_value+'.');
	doc(el+'_img').src=path;
	doc(el+'_img').alt = new_text_value;
	doc(el).value = new_value;
	}
}

function FormCheckInt (el,id,showerr,elfocus,errmsg) {
	if ((ie||ns6) && el && doc('f'+id)) {
	value = el.value;
	if (!(/^(\d{1,3})$/.test(value))) {
		el.className = 'inp_text_err';
		errs[id] = 1;
		if (showerr == 1) {
			doc('f'+id).innerHTML = errmsg;
		}
		if (elfocus == 1) {
			el.focus();
		}
	}
	else if ((errs[id] == 1 && errmsg.toLowerCase() == doc('f'+id).innerHTML.toLowerCase()) || !errs[id]) {

		doc('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 = doc(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' && doc('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 && doc('f'+id)) {
	value = el.value;
	if (/[\||\'|\<|\>|\"|\!|\$|\@|\&\~\*\+]/.test(value)) {
		el.className = 'inp_text_err';
		errs[id] = 1;
		if (showerr == 1) {
			doc('f'+id).innerHTML = errmsg;
		}
		if (elfocus == 1) {
			el.focus();
		}
	}
	else if ((errs[id] == 1 && errmsg.toLowerCase() == doc('f'+id).innerHTML.toLowerCase()) || !errs[id]) {

		doc('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 && doc('f'+id)) {
	value = el.value;
	if (el.value.replace(/ /gi,"").length < len) {
		el.className = 'inp_text_err';
		errs[id] = 1;
		if (showerr == 1) {
			doc('f'+id).innerHTML = errmsg;
		}
		if (elfocus == 1) {
			el.focus();
		}
	}
	else if ((errs[id] == 1 && errmsg.toLowerCase() == doc('f'+id).innerHTML.toLowerCase()) || !errs[id]) {
		doc('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 (doc('fields'+i)){
		var fname = (doc('fname'+i)) ? ' "'+doc('fname'+i).innerHTML+'"' : '';
		var value = doc('fields'+i).value;
			if ((value == '' || value == 0) && mas[i] == 1) {
				if (doc('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,type){

if (check_form_errors(form_id) == false) return false;
else {
	var fdata = doc('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 osago = {};
		if (form_id == 6 && doc('form_osago')) {

			var fdata_osago = doc('form_osago');
			for (var i=0; i<fdata_osago.length; i++) osago[fdata_osago.elements[i].name] = fdata_osago.elements[i].value;
			if (doc('res_osago')) osago['polis_cost'] = doc('res_osago').innerHTML; 
		}
		var data = { 'form_id': form_id, 'data': fields_value, 'type': type, 'osago': osago, 'back_link' : eval('back_link'+form_id) };
        req.send(data);

		show_message('Отправление данных');

    	req.onreadystatechange = function() {

		//doc('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) {
				var phone = (doc('fields47')) ? doc('fields47').value : 0; 
		        	close_message('info', message);
		        	doc('form_data'+form_id).reset();
		        	if (doc('iCodeForm'+form_id)) reImg('iCodeForm'+form_id);
				if (form_id == 6 && req.responseJS.order_id>0) send_osago_sms(phone,req.responseJS.order_id);
		        }
				else close_message();
            }

		   }
		}

}

}

function send_osago_sms(phone,order_id){
	if (!phone || phone.length!=13) return false;
	var phone = '+7'+phone.replace(/[^0-9]/ig,"");

	var req = new JsHttpRequest();
	req.open(null, '/js/_ajax/calc/send_sms_osago.php', true);
	var data = { 'phone': phone, 'order_id': order_id };
        //show_message();
        req.send(data);

    	req.onreadystatechange = function() {
	 //   if (req.responseText) alert(req.responseText);
    	   if (req.readyState == 4) {

			var result = req.responseJS.result;
			var errors = req.responseJS.errors;
			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 временно недоступен.');

         }
        }
}


function reImg(id){
	if (doc(id)==null) return false;
	var ndate = new Date().getTime();
	doc(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+'"')
        }
}





/*
setElementOpacity - установка прозрачности
getOpacityProperty - проверка, есть ли возможность менять прозрачность
fadeOpacity - плавное изменение прозрачности
*/
function setElementOpacity(oElem, nOpacity)
{
	var p = getOpacityProperty();
	(setElementOpacity = p=="filter"?new Function('oElem', 'nOpacity', 'nOpacity *= 100;	var oAlpha = oElem.filters["DXImageTransform.Microsoft.alpha"] || oElem.filters.alpha;	if (oAlpha) oAlpha.opacity = nOpacity; else oElem.style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity="+nOpacity+")";'):p?new Function('oElem', 'nOpacity', 'oElem.style.'+p+' = nOpacity;'):new Function)(oElem, nOpacity);
}

function getOpacityProperty(){
	var p;
	if (typeof document.body.style.opacity == 'string') p = 'opacity';
	else if (typeof document.body.style.MozOpacity == 'string') p =  'MozOpacity';
	else if (typeof document.body.style.KhtmlOpacity == 'string') p =  'KhtmlOpacity';
	else if (document.body.filters && navigator.appVersion.match(/MSIE ([\d.]+);/)[1]>=5.5) p =  'filter';

	return (getOpacityProperty = new Function("return '"+p+"';"))();
}
/* Функции для плавного изменения прозрачности:
1) fadeOpacity.addRule('opacityRule1', 1, 0.5, 30); //вначале создаем правило, задаем имя правила, начальную прозрачность и конечную, необязательный параметр задержки, влийяющий на скорость смены прозрачности
2) fadeOpacity('elemID', 'opacityRule1'); // выполнить плавную смену прозрачности элемента с id равным elemID, по правилу opacityRule1
3) fadeOpacity.back('elemID'); //вернуться в исходное сотояние прозрачности
*/
function fadeOpacity(sElemId, sRuleName, bBackward){
	var elem = doc(sElemId);
	if (!elem || !getOpacityProperty() || !fadeOpacity.aRules[sRuleName]) return;

	var rule = fadeOpacity.aRules[sRuleName];
	var nOpacity = rule.nStartOpacity;

	if (fadeOpacity.aProc[sElemId]) {clearInterval(fadeOpacity.aProc[sElemId].tId); nOpacity = fadeOpacity.aProc[sElemId].nOpacity;}
	if ((nOpacity==rule.nStartOpacity && bBackward) || (nOpacity==rule.nFinishOpacity && !bBackward)) return;

	fadeOpacity.aProc[sElemId] = {'nOpacity':nOpacity, 'tId':setInterval('fadeOpacity.run("'+sElemId+'")', fadeOpacity.aRules[sRuleName].nDalay), 'sRuleName':sRuleName, 'bBackward':Boolean(bBackward)};
}

fadeOpacity.addRule = function(sRuleName, nStartOpacity, nFinishOpacity, nDalay){fadeOpacity.aRules[sRuleName]={'nStartOpacity':nStartOpacity, 'nFinishOpacity':nFinishOpacity, 'nDalay':(nDalay || 30),'nDSign':(nFinishOpacity-nStartOpacity > 0?1:-1)};};
fadeOpacity.back = function(sElemId){fadeOpacity(sElemId,fadeOpacity.aProc[sElemId].sRuleName,true);};
fadeOpacity.run = function(sElemId){
	var proc = fadeOpacity.aProc[sElemId];
	var rule = fadeOpacity.aRules[proc.sRuleName];

	proc.nOpacity = Math.round(( proc.nOpacity + .1*rule.nDSign*(proc.bBackward?-1:1) )*10)/10;
	setElementOpacity(document.getElementById(sElemId), proc.nOpacity);

	if (proc.nOpacity==rule.nStartOpacity || proc.nOpacity==rule.nFinishOpacity) clearInterval(fadeOpacity.aProc[sElemId].tId);
}
fadeOpacity.aProc = {};
fadeOpacity.aRules = {};
fadeOpacity.addRule('block', .0, 1, 100);
fadeOpacity.addRule('fade', 1, 0, 100);
fadeOpacity.addRule('reset', 1, 0, 0);
fadeOpacity.addRule('shadow', 0, 1, 10);




////////////////////////////
// <<<<< DRAG AND DROP    //
////////////////////////////
var dflag=false;
var shift_x;
var shift_y;

function start_drag(itemToMove,e){
     if(!e) e = window.event;
     itemToMove.style.cursor='move';
     dflag=true;
     shift_x = e.clientX-parseInt(itemToMove.style.left);
     shift_y = e.clientY-parseInt(itemToMove.style.top);

     if(e.stopPropagation) e.stopPropagation();
     else e.cancelBubble = true;
     if(e.preventDefault) e.preventDefault();
     else e.returnValue = false;
}

function end_drag(){ dflag=false; }

function dragIt(itemToMove,e){
     if(!dflag) {
	itemToMove.style.cursor='default';
	addCookie('left',parseInt(itemToMove.style.top),30,'/');
	addCookie('top',parseInt(itemToMove.style.left),30,'/');
	return;
      }
     if(!e) e = window.event;
     var l = e.clientX-shift_x;
     var t = e.clientY-shift_y;
     
     $(itemToMove).css('left',l);
     $(itemToMove).css('top',t);
    // itemToMove.style.left = (e.clientX-shift_x) + "px";
    // itemToMove.style.top = (e.clientY-shift_y) + "px";

     if(e.stopPropagation) e.stopPropagation();
     else e.cancelBubble = true;
     if(e.preventDefault) e.preventDefault();
     else e.returnValue = false;
}


function r_over(e){
e.style.color = '#66ccff';
e.style.fontWeight = 'bold';
}
function r_out(e){
e.style.color = '#333';
e.style.fontWeight = 'normal';
}

////////////////////////////
// DRAG AND DROP   >>>>>> //
////////////////////////////


// показать тень
function showShadow(nitro_show) {
	var shadow = document.getElementById("shadow");
	shadow.style.display = "block";
     if (isIE==false) fadeOpacity('shadow', 'shadow');
     else shadow.className = '';
	//if(ie) {document.body.className += "hideselects";}

	var bodyHeight = document.body.clientHeight;
	var wrapHeight = (isIE) ? document.getElementById("wrap").offsetHeight : document.getElementById("wrap").clientHeight;

	if (wrapHeight > bodyHeight) shadowHeight = wrapHeight;
	else shadowHeight = bodyHeight;
	shadow.style.height = shadowHeight + "px";

	if (doc('obj1') && nitro_show!=2) show_hide_swf('none')
	if (doc('nitro') && nitro_show!=2) show_nitro();

	return false;
}

// спрятать тень
function hideShadow() {
	var shadow = document.getElementById("shadow");
	if (shadow) {
	shadow.style.display = "none";}
	if (doc('nitro')) {
	    if (typeof nitro!="undefined") clearTimeout(nitro);
		doc('nitro').style.display = 'none';
		if (isIE) doc('nitro').innerHTML = '';
		//doc('swf_obj').src = '';
	}
	//if(ie) {document.body.className = document.body.className.replace(" hideselects", "");}
    if (isIE==false && fadeOpacity.aProc['shadow']) fadeOpacity.back('shadow');
	if (doc('obj1')) show_hide_swf('')
	return false;
}



function setPhoneFormat(e,event){
   var k = event.keyCode;
	   if (k != 8 && k != 46){
	   var val = e.value;
	   val = val.replace(/[^0-9]/g, "");
	   var pattern = /\(?([0-9]{3})\)?\ ?([0-9]{0,7})?/;
	   if (pattern.test(val)) val = '('+RegExp.$1+') '+RegExp.$2;
	   e.value = val;
   }
}

function show_hide_swf(display){
 if (doc('obj1')) doc('obj1').style.display = display;
 if (doc('obj2')) doc('obj2').style.display = display;
 if (doc('obj3')) doc('obj3').style.display = display;
 if (doc('obj4')) doc('obj4').style.display = display;
}


function show_nitro(){
	doc('nitro').style.display = '';
	var top = (document.body.scrollTop>0) ? document.body.scrollTop : document.documentElement.scrollTop;
	if (self.screen) doc('nitro').style.top = (parseInt(top,10)+(screen.height/2)-400)+'px';
	else doc('nitro').style.top = (parseInt(top,10)+(document.body.clientHeight/2)-400)+'px';
	//doc('nitro').style.left = ((document.body.clientWidth/2)-250)+'px';
	if (doc('nitro').innerHTML == '') location.reload();
}



function load_calendar(id,showtime){
showtime = (showtime == 'no') ? false : true;
var format = (showtime===true) ? "%Y-%m-%d %H:%M" : "%Y-%m-%d";
if (doc(id))
	Calendar.setup({
		inputField:  id,
		button:      id,
		ifFormat:    format,
		firstDay:    1,
		timeFormat:  "24",
		showsTime:   showtime,
		weekNumbers: false
	});
}
