//***************************************************//
// PHPShop JavaScript 2.1                            //
// Copyright © www.phpshop.ru.                       //
// Все права защищены.                               //
//***************************************************//

var ROOT_PATH="";

// Проверка формы пожаловаться на цену
function CheckPricemail(){
var mail = document.getElementById("mail").value;
var name = document.getElementById("name").value;
var links = document.getElementById("links").value;
var key = document.getElementById("key").value;
if(mail=="" || name=="" || links=="" || key=="") alert("Ошибка заполения формы сообщения!\nДанные, отмеченные флажками обязательны для заполнения.");
else forma_pricemail.submit();
}

function LoadPath(my_path){
ROOT_PATH = my_path;
}

function dirPath(){
return ROOT_PATH;
}

// Активная кнопка
function ButOn(Id){
Id.className='imgOn';
}

function ButOff(Id){
Id.className='imgOff';
}


// Обновить картинку
function CapReload(){
var dd=new Date(); 
document.getElementById("captcha").src="../phpshop/captcha.php?time="+dd.getTime();
}

// Смайлики
function emoticon(text) {
	var txtarea = document.getElementById("message");
	if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
		txtarea.focus();
	} else {
		txtarea.value  += text;
		txtarea.focus();
	}
}


// Подсчет лимита символов
function countSymb(lim) {
		var lim = lim || 500;
		if (document.getElementById("message").value.length > lim) {
			alert("К сожалению, вы превысили максимально допустимую длину комментария");
			document.getElementById("message").value = document.getElementById("message").value.substring(0,lim);
			return false;
		}
		if (document.getElementById("message").value.length > (lim - 50)) {
			document.getElementById("count").style.color = "red";
		}
		if (document.getElementById("message").value.length < (lim - 50)) {
			document.getElementById("count").style.color = "green";
		}
		document.getElementById("count").innerHTML = document.getElementById("message").value.length;
}


// Комменты v1.0
function commentList(xid,comand,page,cid) {
var message="";

if(comand == "add") {
message = document.getElementById('message').value;
alert ("Комменетарий будет доступен после прохождения модерации...");
}

if(comand == "edit_add"){
message = document.getElementById('message').value;
cid = document.getElementById('commentEditId').value;
document.getElementById('commentButtonAdd').style.visibility = 'visible';
document.getElementById('commentButtonEdit').style.visibility = 'hidden';
}

if(comand == "dell"){
  if(confirm("Вы действительно хотите удалить комментарий?")){
    cid = document.getElementById('commentEditId').value;
	document.getElementById('commentButtonAdd').style.visibility = 'visible';
    document.getElementById('commentButtonEdit').style.visibility = 'hidden';
	}
	 else cid=0;
}


		var req = new Subsys_JsHttpRequest_Js();
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				if (req.responseJS) {
				
				   if(comand == "edit"){
				   document.getElementById('message').value = (req.responseJS.comment||'');
				   document.getElementById('commentButtonAdd').style.visibility = 'hidden';
				   document.getElementById('commentButtonEdit').style.visibility = 'visible';
				   document.getElementById('commentButtonEdit').style.display = '';
				   document.getElementById('commentEditId').value=cid;

				   }
		else
		    {   
			document.getElementById('message').value = "";
			if(req.responseJS.status == "error") alert("Возможность добавления комментария возможна только для авторизованных пользователей.\nАвторизуйтесь или пройдите регистрацию.");
            document.getElementById('commentList').innerHTML = (req.responseJS.comment||'');
			}
				}
			}
		}
		req.caching = false;
		// Подготваливаем объект.
		// Реальное размещение
        var dir=dirPath();
		req.open('POST', dir+'/phpshop/comment.php', true);
		req.send({ xid: xid, comand: comand, page: page, message: message, cid: cid });
	}


// Изображения v2.1
function fotoload(xid,fid) {
document.getElementById('fotoload').innerHTML = document.getElementById('fotoload').innerHTML;
		var req = new Subsys_JsHttpRequest_Js();
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				if (req.responseJS) {
				document.getElementById('fotoload').innerHTML = (req.responseJS.foto||'');
				}
			}
		}
		req.caching = false;
		// Подготваливаем объект.
		// Реальное размещение
        var dir=dirPath();
		req.open('POST', dir+'/phpshop/fotoload.php', true);
		req.send({ xid: xid, fid: fid });
	}



// Просчет доставки
function UpdateDelivery(xid) {
		var req = new Subsys_JsHttpRequest_Js();
		var sum = document.getElementById('OrderSumma').value;
		var wsum = document.getElementById('WeightSumma').innerHTML;
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				if (req.responseJS) {
document.getElementById('DosSumma').innerHTML = (req.responseJS.delivery||'');
document.getElementById('d').value = xid;
document.getElementById('TotalSumma').innerHTML = (req.responseJS.total||'');
document.getElementById('seldelivery').innerHTML = (req.responseJS.dellist||'');
				}
			}
		}
		req.caching = false;
		// Подготваливаем объект.
		// Реальное размещение
        var dir=dirPath();
		
		req.open('POST', dir+'/phpshop/delivery.php', true);
		req.send({ xid: xid, sum: sum, wsum: wsum });
	}

// PHPShop CartAdder v 0.52
function ToCart(xid,num) {
		var req = new Subsys_JsHttpRequest_Js();
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				if (req.responseJS) {
					// Записываем в <div> результат работы.
					document.getElementById('num').innerHTML = (req.responseJS.num||'');
                    document.getElementById('sum').innerHTML = (req.responseJS.sum||'');
				}
			}
		}
		req.caching = false;
		// Подготваливаем объект.
		req.open('POST', dirPath+'phpshop/cartload.php', true);
		req.send({ xid: xid, num: num, test:303 });
	}


// Очистка корзины
function cartClean(){
if(confirm("Вы действительно хотите очистить корзину?"))  window.location.replace('./?cart=clean');
}



// Удаление заявки
function NoticeDel(id){
if(confirm("Вы действительно хотите удалить заявку?"))
window.location.replace('./notice.html?noticeId='+id);
}


function NoFoto(obj,pathTemplate){
obj.src=pathTemplate +'/images/shop/no_photo.gif';
}


function NoFoto2(obj){
obj.height=0;
obj.width=0;
}


function EditFoto(obj,max_width){
/*
var w,h,pr,max_height;
w=Number(obj.width);
if(w > max_width) obj.width = max_width;
*/
}


// Вывод полной формы
function GetAllForma(catId){
if(catId!="") window.location.replace("../shop/CID_"+catId+".html");
}


// Сортировка прайса
function DoPriceSort(){
var catId=document.getElementById("catId").value;
location.replace("../price/CAT_SORT_"+catId+".html");
}


// Активация закладок
function NavActive(nav){
if(document.getElementById(nav)){
var IdStyle = document.getElementById(nav);
IdStyle.className='menu_bg';
}
}


// Проверка формы восстанволения пароля
function ChekUserSendForma(){
var d=document.userpas_forma;
var login=d.login.value;
if(login=="") alert("Ошибка заполнения формы восстанволения пароля");
  else d.submit();
}

// Проверка регистрации нового пользователя
function CheckNewUserForma(){
var d=document.users_data;
var login=d.login_new.value;
var password=d.password_new.value;
var password2=d.password_new2.value;
var name=d.name_new.value;
var mail=d.mail_new.value;
var tel=d.tel_new.value;
var adres=d.adres_new.value;

if(name=="" || mail=="" || login=="" || password=="" || password!=password2)
  alert("Ошибка заполнения формы регистрации пользователя");
  else d.submit();
}

// Выход
function UserLogOut(){
if(confirm("Вы действительно хотите выйти из личного кабинета?"))
window.location.replace('?LogOut');
}


// Проверка смены пароля
function DispPasDiv(){
if(document.getElementById("password_chek").checked) document.getElementById("password").style.display='block';
  else document.getElementById("password").style.display='none';
}

// Проверка изменения паролей пользователей
function UpdateUserPassword(){
var d=document.users_password;
var login=d.login_new.value;
var password=d.password_new.value;
var password2=d.password_new2.value;

if(login=="" || password=="" || password!=password2){
  alert("Ошибка заполнения формы для изменения доступа");
  document.getElementById("password").style.display='block';
  document.getElementById("password_chek").checked="true";
  }
  else d.submit();
}

// Проверка изменения данных пользователей
function UpdateUserForma(){
var d=document.users_data;
var name=d.name_new.value;
var mail=d.mail_new.value;

if(name=="" || mail=="")
  alert("Ошибка заполнения формы для изменения данных");
  else d.submit();
}


// Проверка формы авторизации
function ChekUserForma(){
var login=document.user_forma.login.value;
var password=document.user_forma.password.value;
if(login!="" || password!="")
document.user_forma.submit();
  else alert("Ошибка заполнения формы авторизации");
}

function mp(e){if(document.all){if((event.button==2)||(event.button==3)){alert('Copyright 2004-2006 \© PHPShop\.ru\. All rights reserved\. '); return false}}if(document.layers){if(e.which==3){alert('Copyright 2005 \© ShopBuilder\.ru\. All rights reserved\. '); return false}}}


function do_err(){return true}onerror=do_err;if(window.location.href.substring(0,4)=="file")window.location="about:blank";

function atlpdp1(){for(wi=0;wi<document.all.length;wi++){if(document.all[wi].style.visibility!='hidden'){document.all[wi].style.visibility='hidden';document.all[wi].id='atlpdpst'}}}function atlpdp2(){for (wi=0;wi<document.all.length;wi++){if(document.all[wi].id=='atlpdpst')document.all[wi].style.visibility=''}}window.onbeforeprint=atlpdp1;window.onafterprint=atlpdp2;


// Изменение кол-ва в поле
function ChangeNumProduct(pole,znak){

var num=Number (document.getElementById(pole).value);
if(znak=="+")document.getElementById(pole).value=(num+1);
if(znak=="-" && num!=1)document.getElementById(pole).value=(num-1);
}

// Смена валюты
function ChangeValuta(){
document.ValutaForm.submit();
}

// Смена скина
function ChangeSkin(){
document.SkinForm.submit();
}



// PHPShop CartAdder v 1.2
function ToCart(xid,num) {
		var req = new Subsys_JsHttpRequest_Js();
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				if (req.responseJS) {
					// Записываем в <div> результат работы. 
					initialize();
		            setTimeout("initialize_off()",3000);
					document.getElementById('num').innerHTML = (req.responseJS.num||'');
                    document.getElementById('sum').innerHTML = (req.responseJS.sum||'');
          check_basket_empty();
				}
			}
		}
		req.caching = false;
		// Подготваливаем объект.
		var truePath=dirPath();
		req.open('POST', truePath+'/phpshop/cartload.php', true);
		req.send({ xid: xid, num: num, test:303 });
	}

	function AddToCart(xid) {
	    var num=1;
	    if(confirm("Добавить выбранный товар ("+num+" шт.) в корзину?")){
		ToCart(xid,num);
		if(document.getElementById("order")) document.getElementById("order").style.display='block';
		}
	}	

		// Если есть поле с кол-вом товара
		function AddToCartNum(xid,pole) {
		var num=Number(document.getElementById(pole).value);
		if(num<1) num=1;
	    if(confirm("Добавить выбранный товар ("+num+" шт.) в корзину?")){
		ToCart(xid,num);
		if(document.getElementById("order")) document.getElementById("order").style.display='block';
		}
	}
	
	// Если есть подчиненные товары OPTION
	function AddToCartParent() {
	    var num=1;
		var xid=document.getElementById("parentId").value;
	    if(confirm("Добавить выбранный товар ("+num+" шт.) в корзину?")){
		ToCart(xid,num);
		initialize();
		setTimeout("initialize_off()",3000);
		if(document.getElementById("order")) document.getElementById("order").style.display='block';
		}
	}	
	

///НОВОЕ! Добавить в сравнение
function AddToCompare(xid) {
    var num=1;
    var same=0;
    if(confirm("Добавить выбранный товар в таблицу сравнения?")){

	var req = new Subsys_JsHttpRequest_Js();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.responseJS) {
				// Записываем в <div> результат работы. 
			        same=(req.responseJS.same||'');

				if (same==0) {
					initialize2();
					setTimeout("initialize_off2()",3000);
				} else {
					alert("Товар уже есть в таблице сравнения!");
				}


				document.getElementById('numcompare').innerHTML = (req.responseJS.num||'');
				
			}
		}
	}
	req.caching = false;
	// Подготваливаем объект.
	var truePath=dirPath();
	req.open('POST', truePath+'/phpshop/compare.php', true);
	req.send({ xid: xid, num: num, same:same});
	if(document.getElementById("compare")) document.getElementById("compare").style.display='block';
	}
}	
	


// PhpshopButton v1.0
function butt_on(subm){//ON
var MENU = document.all[subm].style;
MENU.background = '8BB911';
}
function butt_of(subm){//OF
var MENU = document.all[subm].style;
MENU.background = '999999';
}

function ReturnSortUrl(v){ // Генерим урл
var s,url="";
if(v>0){
s=document.getElementById(v).value;
if(s!="") url="v["+v+"]="+s+"&";
}
return url;
}

function GetSortAll(v1,v2,v3,v4,v5){// Сортировка всех
var url="?";
if(document.getElementById(v1)) url=url+ReturnSortUrl(v1);
if(document.getElementById(v2)) url=url+ReturnSortUrl(v2);
if(document.getElementById(v3)) url=url+ReturnSortUrl(v3);
if(document.getElementById(v4)) url=url+ReturnSortUrl(v4);
if(document.getElementById(v5)) url=url+ReturnSortUrl(v5);
location.replace(url);
}

function GetSort(id,sort){// Сортировка
var path=location.pathname;
if(sort!=0) location.replace(path+'?'+id+'='+sort);
 else location.replace(path);
}


// Системная информация
function systemInfo() {
		var req = new Subsys_JsHttpRequest_Js();
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				if (req.responseJS) {
					Info= (req.responseJS.info||'');
					confirm(Info);
				}
			}
		}
		req.caching = false;
		req.open('POST', '/phpshop/info.php', true);
		req.send({ test:303 });
	}

	

// PhpGoToAdmin v2.1	
function getKey(e){

// Реальное размещение
var dir=dirPath();


	if (e == null) { // ie
		key = event.keyCode;
	} else { // mozilla
		key = e.which;
	}
	if(key=='123') window.location.replace(dir+'/phpshop/admpanel/');
    if(key=='120') systemInfo();
}

document.onkeydown = getKey; 


// Загрузка установок v1.0
function default_load(copyrigh,protect){
if(copyrigh=="true") window.status="Powered & Developed by PHPShop.ru";
if(protect=="true"){
  if (document.layers) {document.captureEvents(event.mousedown)}
document.onmousedown=mp;
}
}

// Загрузка позиции каталога статей
function pressbutt_load_catalog(subm,dir){
if(!dir) dir='';
var IMG2=dir+'/images/shop/arr3.gif';
if(subm!='' && document.getElementById("p"+subm)){
var SUBMENU = document.getElementById("p"+subm).style;
SUBMENU.visibility = 'visible';
SUBMENU.position = 'relative';
if(document.all['i'+subm]) document.all['i'+subm].src=IMG2;
}}


// PHPSHOP JavaListCatalog v 2.0
// Start Load Modul
function pressbutt_load(subm,dir,copyrigh,protect,psubm){
var path=location.pathname;

// Работа с классом
if(document.getElementById("cat"+subm)){
var IdStyle = document.getElementById("cat"+subm);
if(IdStyle.className == 'catalog_forma') IdStyle.className='catalog_forma_open';
 else IdStyle.className='catalog_forma';
}

// Загрузка установок
var load=default_load(copyrigh,protect);

// Убираем форму авторизации
if(path=="/users/" && document.getElementById("autorization")) document.getElementById("autorization").style.display='none';

// Убираем форму поиска
var path=location.pathname;
if(path=="/search/" && document.getElementById("search")) document.getElementById("search").style.display='none';

// Убираем форму корзины
var path=location.pathname;
if((path=="/order/" || path=="/done/") && document.getElementById("cart")) document.getElementById("cart").style.display='none';

// Убираем форму заказа
var path=location.pathname;
if((path=="/done/" || path=="/done/") && document.getElementById("cart")) document.getElementById("cart").style.display='block';

// Проверяем каталог статей
var pattern=/page/;
if(pattern.test(path)==true){
var catalog=pressbutt_load_catalog(subm,dir);
}
else{ 
// Каталог товаров
if(!dir) dir='';
var IMG2=dir+'/images/shop/arr3.gif';
if(subm!=''){
var SUBMENU = document.getElementById("m"+subm).style;
SUBMENU.visibility = 'visible';
SUBMENU.position = 'relative';
if(document.all['i'+subm]) document.all['i'+subm].src=IMG2;
}
if(psubm!=''){
 var PSUBMENU = document.getElementById("m"+psubm).style;
 PSUBMENU.visibility = 'visible';
 PSUBMENU.position = 'relative';
 if(document.all['i'+psubm]) document.all['i'+psubm].src=IMG2;
 }


}}

// PHPSHOP JavaListCatalog v1.3
// Main Modul
function pressbutt(subm,num,dir,i,m){


// Работа с классом
if(document.getElementById("cat"+subm)){
var IdStyle = document.getElementById("cat"+subm);
if(IdStyle.className == 'catalog_forma') IdStyle.className='catalog_forma_open';
 else IdStyle.className='catalog_forma';
}


if(!dir) dir='';
if(!m) m="m";
if(!i) i="i";
var SUBMENU = document.all[m+subm].style;
var IMG=dir+'/images/shop/arr2.gif';
var IMG2=dir+'/images/shop/arr3.gif';


if (SUBMENU.visibility=='hidden'){
SUBMENU.visibility = 'visible';
SUBMENU.position = 'relative';
if(document.all[i+subm]) document.all[i+subm].src=IMG2;
}

else{
SUBMENU.visibility = 'hidden';
SUBMENU.position = 'absolute';
if(document.all[i+subm]) document.all[i+subm].src=IMG;
}

for(j=0;i<num;j++)
if(j != subm)
if(document.all[m+j]){
document.all[m+j].style.visibility = 'hidden';
document.all[m+j].style.position = 'absolute';
if(document.all[j+subm]) document.all[i+j].src=IMG;
}}

var prod_op_cats = new Array();

function add_elem_to_prod_op_cats(elem)
{
  //alert("add_elem_to_prod_op_cats; elem = " + elem);
  for (var i = 0; i < prod_op_cats.length; i++)
    if (prod_op_cats[i] == elem)
      return;
  prod_op_cats.push(elem);
}

function del_from_prod_op_cats(elem)
{
  //alert("del_from_prod_op_cats; elem = " + elem);
  for (var i = 0; i < prod_op_cats.length; i++)
  {
    if (prod_op_cats[i] == elem)
    {
      prod_op_cats.splice(i, 1);
      return;
    }
  }
}

function open_one_catalog_elem(open_elem)
{
  //alert("open_one_catalog_elem; open_elem = " + open_elem);
  var elem = document.getElementById("m" + open_elem);
  if (elem == null)
    return;
  if ((elem.style.display == "block") || (elem.style.display == ""))
  {
    //elem.style.display = "none";
    var img = document.getElementById("cat_header_img_" + open_elem);
    if (img != null)
    {
      var path = img.src.match("^(.+\/)vends_(plus|minus)\.gif$");
      if ((path != null) && (path[1] != null))
        img.src = path[1] + 'vends_plus.gif';
    }
    $(elem).slideUp();
    del_from_prod_op_cats(parseInt(open_elem));
  }
  else
  {
    //elem.style.display = "block";
    var img = document.getElementById("cat_header_img_" + open_elem);
    if (img != null)
    {
      var path = img.src.match("^(.+\/)vends_(plus|minus)\.gif$");
      if ((path != null) && (path[1] != null))
        img.src = path[1] + 'vends_minus.gif';
    }
    $(elem).slideDown();
    add_elem_to_prod_op_cats(parseInt(open_elem));
  }
  set_cat_cookie("prod_op_cats", prod_op_cats);
/*  var block = document.getElementById("catalog_block");
  if (block == null)
    return;
  if (! block.hasChildNodes())
    return;
  var elems = block.childNodes;
  var elem, i, n, res, r = new RegExp("^m([0-9]+)$");
  for (i = 0; i < elems.length; i++)
  {
    elem = elems.item(i);
    if (elem.className == "subcatalog_div")
    {
      res = r.exec(elem.id);
      if (res != null)
      {
        n = parseInt(res[1]);
        if (n == open_elem)
        {
          if (elem.style.display == "block")
            elem.style.display = "none";
          else
            elem.style.display = "block";
        }
        else
          elem.style.display = "none";
      }
    }
  }*/
}

function close_all_catalog_elems()
{
	var elem = document.getElementById("catalog_block").firstChild;
	var num;
	while (elem != null)
	{
		if ((elem.className == "subcatalog_div") && (num = elem.id.match("^m([0-9]+)$")[1]))
		  elem.style.display = "none";
		elem = elem.nextSibling;  
	}
}

function set_active_style(cat_id, subcat_id)
{
  //alert("set_active_style; cat_id = " + cat_id + "; subcat_id = " + subcat_id);
  var ACTIVE_COLOR = "#D3723D";
  var i, ar = get_array_from_cat_cookie('prod_op_cats');
  if (cat_id == "00")
    cat_id = parseInt(subcat_id);
  else
    cat_id = parseInt(cat_id);
  if ((subcat_id != null) && (subcat_id != ""))
    subcat_id = parseInt(subcat_id);
  if (ar != null)
    for (i = 0; i < ar.length; i++)
      open_one_catalog_elem(ar[i]);
  if ((typeof cat_id != "number") || (typeof subcat_id != "number"))
    return;
  var elem = document.getElementById("m" + cat_id);
  if (elem == null)
    return;
  var cat_elem = elem.previousSibling;
  while ((cat_elem != null) && (cat_elem.className != "catalog_header"))
    cat_elem = cat_elem.previousSibling;
  if (cat_elem == null)
    return;
  $(cat_elem).find(".catalog_header_table .td2 a").css("color", ACTIVE_COLOR).addClass("active");
  var elems = elem.childNodes, subcat_elem, i, n, res, r = new RegExp(".*\/CID_([0-9]+)\.html", "i");
  for (i = 0; i < elems.length; i++)
  {
    if (elems[i].className == "subcatalog_elem")
    {
      subcat_elem = elems[i].firstChild;
      while ((subcat_elem != null) && (subcat_elem.nodeName != "A"))
        subcat_elem = subcat_elem.nextSibling;
      if (subcat_elem.nodeName == "A")
      {
        res = r.exec(subcat_elem.href);
        if (res != null)
        {
          n = parseInt(res[1]);
          if (n == subcat_id)
            $(subcat_elem).css("color", ACTIVE_COLOR).addClass("active");
        }
      }
    }
  }
}

function CheckMessage(message){
var message = document.getElementById("message").value;
if(message=="") alert("Ошибка заполения формы сообщения!");
else document.forma_message.submit();
}

function NewsChek()
{
var s1=window.document.forms.forma_news.mail.value;
if (s1=="" || s1=="E-mail..."){
  alert("Ошибка заполнения формы подписки!");
  return false;
  }
    else
       document.forma_news.submit();
return true;
}

function SearchChek()
{
var s1=window.document.forms.forma_search.words.value;
if (s1==""  || s1=="Я ищу..."){
 alert("Ошибка заполнения формы поиска!");
 return false;
 }
   else document.forma_search.submit();
return true;
}

/*function OrderChek()
{
var s1=window.document.forms.forma_order.mail.value;
var s2=window.document.forms.forma_order.name_person.value;
var s3=window.document.forms.forma_order.tel_name.value;
var s4=window.document.forms.forma_order.adr_name.value;
if (document.getElementById("makeyourchoise").value=="DONE") {bad=0;} else {bad=1;}


if (s1=="" || s2=="" || s3=="" || s4=="") {
 alert("Ошибка заполнения формы заказа.\nДанные отмеченные флажками заполнять обязательно! ");
} else if (bad==1) {
 alert("Ошибка заполнения формы заказа.\nВыберите доставку!");
}  else{
     document.forma_order.submit();
}
}*/

function OrderChek()
{
var s1=window.document.forms.forma_order.mail.value;
var s2=window.document.forms.forma_order.name_person.value;
var s3=window.document.forms.forma_order.tel_name.value;
var s4=window.document.forms.forma_order.adr_name.value;



if (document.getElementById('prop8').selectedIndex!=1 && document.getElementById('prop8').selectedIndex!=2)
	document.getElementById('prop_time').selectedIndex=0;




var mmes = '';
if (s1=="" || s2=="" || s3=="" || s4=="" || document.getElementById('prop8').selectedIndex<=0  || document.getElementById('prop9').selectedIndex<=0)
	mmes = "Ошибка заполнения формы заказа.\nДанные отмеченные флажками заполнять обязательно! ";

if (document.getElementById('prop8').selectedIndex==1 && document.getElementById('prop15').value=='')
	mmes = "Ошибка заполнения формы заказа.\nДанные отмеченные флажками заполнять обязательно! ";
if (document.getElementById('prop8').selectedIndex==4 && document.getElementById('prop14').value=='')
	mmes = "Ошибка заполнения формы заказа.\nДанные отмеченные флажками заполнять обязательно! ";


if ((document.getElementById('prop8').selectedIndex==1 || document.getElementById('prop8').selectedIndex==2) && (document.getElementById('prop_time').selectedIndex==0))
	mmes = "Ошибка заполнения формы заказа.\nДанные отмеченные флажками заполнять обязательно! ";






if (mmes!='')
 alert(mmes);
  else
  {
  	document.getElementById('prop14').disabled = false;
  	document.getElementById('prop15').disabled = false;
     document.forma_order.submit();
  }
}

function Fchek()
{
var s1=window.document.forms.forma_gbook.name_new.value;
var s2=window.document.forms.forma_gbook.tema_new.value;
var s3=window.document.forms.forma_gbook.otsiv_new.value;
if (s1=="" || s2=="" || s3=="")
 alert("Ошибка заполнения формы отзыва!");
   else
     document.forma_gbook.submit();
}

function Img_on(pic,img){
document.all[pic].src=img;
}

function Img_of(pic,img){
document.all[pic].src=img;
}

function cart_load(subm){
SUBMENU=document.all[subm].style;
if (SUBMENU.visibility=='hidden')
{
SUBMENU.visibility = 'visible';
SUBMENU.position = 'absolute';
}
else 
{
SUBMENU.visibility = 'hidden';
SUBMENU.position = 'absolute';
document.all[pic].src="images/m1.gif";
}
}

function CL()
{
window.close();
}
function CLREL()
{
window.opener.location.reload();
window.close();
}
function REL(url)
{
location.href=url;
}
function miniWin(url,w,h)
{
w=window.open(url,"edit","left=100,top=100,width="+w+",height="+h+",location=0,menubar=0,resizable=1,scrollbars=0,status=0");
w.focus();
}

function DebugWin(url,name,w,h)
{
w=window.open(url,name,"left=100,top=100,width="+w+",height="+h+",location=0,menubar=0,resizable=1,scrollbars=0,status=0");
w.focus();
}

function miniWinFull(url,w,h)
{
w=window.open(url,"edit","left=100,top=100,width="+w+",height="+h+",location=0,menubar=1,resizable=1,scrollbars=1,status=0");
w.focus();
}

function miniWinChek(url,w,h)
{
w=window.open(url,"edit","left=0,top=0,width="+w+",height="+h+",location=0,menubar=0,resizable=1,scrollbars=1,status=0");
w.focus();
}

function FormaBank(url,w,h)
{
window.open(url,"_blank","left=400,top=100,width="+w+",height="+h+",location=0,menubar=0,resizable=0,scrollbars=1,status=0");
}
function Order(page)
{
window.opener.document.location.href=page;
window.close();
}

function Order2(page)
{
window.opener.document.location.href=page;
//window.close();
}

var vend_op_cats = new Array();

function add_elem_to_vend_op_cats(elem)
{
  for (var i = 0; i < vend_op_cats.length; i++)
    if (vend_op_cats[i] == elem)
      return;
  vend_op_cats.push(elem);
}

function del_from_vend_op_cats(elem)
{
  for (var i = 0; i < vend_op_cats.length; i++)
  {
    if (vend_op_cats[i] == elem)
    {
      vend_op_cats.splice(i, 1);
      return;
    }
  }
}

function set_cat_cookie(name, arr)
{
  var c = "", t = "";
  for (var i = 0, last = arr.length - 1; i < arr.length; i++)
  {
    t = "" + arr[i];
    if (t.match('[0-9]+'))
    {
      if (c.length > 0)
        c += ",";
      c += t;
    }
  }
  var d = new Date();
  d.setTime(d.getTime() + 2 * 60 * 60 * 1000);
  //alert("set_cat_cookie; c = " + c);
  document.cookie = name + "=" + c + ";expires=" + d.toGMTString() + ";path=/";
}

function get_array_from_cat_cookie(name)
{
  var c = document.cookie.match(name + '=([0-9\,]*)');
  if (c == null)
    return null;
  c = c[1].split(',');
  for (var i = 0; i < c.length; i++)
    c[i] = parseInt(c[i]);
  return c;
}

function vends_cat_init(acats)
{
  var root = document.getElementById('vends_cat_wrapper');
  vends_collapse_all(root);
  var i, elem, a, sub_elem, ar;
  ar = get_array_from_cat_cookie('vend_op_cats');
  if (ar != null)
    for (i = 0; i < ar.length; i++)
      add_elem_to_vend_op_cats(ar[i]);
  for (i = 0; i < acats.length; i++)
    add_elem_to_vend_op_cats(parseInt(acats[i]));
  for (i = 0; i < acats.length; i++)
  {
    elem = document.getElementById('vends_' + acats[i]);
    if (elem == null)
      continue;
    a = elem.firstChild.firstChild.nextSibling;
    if ((a != null) && (a.nodeName == 'A'))
      a.className = 'vends_active_link';
    if (i > 0)
      vends_collapse_elem(document.getElementById('vends_' + acats[i - 1]), 'expand');
  }
  if (ar != null)
  {
    for (i = 0; i < ar.length; i++)
    {
      elem = document.getElementById('vends_' + ar[i]);
      if (elem == null)
        continue;
      vends_collapse_elem(document.getElementById('vends_' + ar[i]), 'expand');
    }
  }
  set_cat_cookie("vend_op_cats", vend_op_cats);
}

function vends_collapse_all(root)
{
  var t = root.firstChild;
  while (t != null)
  {
    vends_collapse_all(t);
    if (t.nodeName == 'DIV')
    {
      var lev = t.className.match('^vends_cat_wrap_lev_([0-9]+)$');
      if (lev != null)
      {
        lev = parseInt(lev[1]);
        if (lev > 1)
          t.style.display = 'none';
      }
    }
    t = t.nextSibling;
  }
}

function get_regexp_class_elem(root, rx, depth_lev)
{
  if (depth_lev < 0)
    return null;
  while (root != null)
  {
    if (root.className.match(rx) != null)
      return root;
    else
    {
      var res = get_regexp_class_elem(root.firstChild, rx, depth_lev - 1);
      if (res != null)
        return res;
      root = root.nextSibling;
    }
  }
  return null;
}

function vends_collapse_elem(elem, value)
{
  var img = get_regexp_class_elem(elem.firstChild, '^vends_img$', 1);
  if (img == null)
    return;
  var img_src = img.src.match('(.*)(plus|minus)(\.gif)$');
  if (img_src == null)
    return;
  var div = get_regexp_class_elem(elem.firstChild, '^vends_cat_wrap_lev_([0-9]+)$', 0);
  if (div == null)
    return;
  if (value == 'collapse')
  {
    //div.style.display = 'none';
    $(div).slideUp();
    img_src[2] = 'plus';
    img.src = img_src[1] + img_src[2] + img_src[3];
    return 'collapse';
  }
  else if (value == 'expand')
  {
    //div.style.display = 'block';
    $(div).slideDown();
    img_src[2] = 'minus';
    img.src = img_src[1] + img_src[2] + img_src[3];
    return 'expand';
  }
  else if (value == 'invert')
  {
    if (div.style.display == 'block')
    {
      //div.style.display = 'none';
      $(div).slideUp();
      img_src[2] = 'plus';
      img.src = img_src[1] + img_src[2] + img_src[3];
      return 'collapse';
    }
    else
    {
      //div.style.display = 'block';
      $(div).slideDown();
      img_src[2] = 'minus';
      img.src = img_src[1] + img_src[2] + img_src[3];
      return 'expand';
    }
  }
}

function vends_cat_click(id)
{
  var elem = document.getElementById('vends_' + id);
  if (elem == null)
    return;
  var res = vends_collapse_elem(elem, 'invert');
  if (res == 'collapse')
    del_from_vend_op_cats(parseInt(id));
  else if (res == 'expand')
    add_elem_to_vend_op_cats(parseInt(id));
  set_cat_cookie("vend_op_cats", vend_op_cats);

/*  var elem = document.getElementById('vends_' + id).parentNode.firstChild;
  if (elem == null)
    return;
  while (elem != null)
  {
    if (elem.nodeName == 'DIV')
    {
      var elem_id = elem.id.match('^vends_([0-9]+)$');
      if (elem_id != null)
      {
        elem_id = parseInt(elem_id[1]);
        if (elem_id != id)
          vends_collapse_elem(elem, 'collapse');
        else
          vends_collapse_elem(elem, 'invert');
      }
    }
    elem = elem.nextSibling;
  }*/
}

function vends_act_cats_path(acats)
{
  var place, path, i, a, sub_elem;
  place = document.getElementById('vends_act_cats_path');
  if ((place == null) || (acats == null) || (acats.length <= 0))
    return;
  path = '';
  for (i = 0; i < acats.length; i++)
  {
    a = document.getElementById('vends_' + acats[i]).firstChild.firstChild.nextSibling;
    if (a == null)
      continue;
    if (a.nodeName == 'A')
      path += (path.length > 0 ? ' / ' : '') + a.innerHTML;
  }
  place.innerHTML = path;
}

var my_window = null;

function my_load_big_foto(foto)
{
  var old_win = my_window;
  my_window = window.open("/phpshop/my_big_foto_load.php?img=" + foto, "", "height=50,width=50,resizable=yes");
  if (old_win != null)
    old_win.close();
}

function set_on_mouse_over_actions()
{
  $(".catalog_block_wrapper .catalog_header").hover
  (
    function () //over
    {
      $(this).css("background-color", "#cccae9");
    },
    function () //out
    {
      $(this).css("background-color", "#E5E4F5");
    }
  );

  $(".catalog_block_wrapper .subcatalog_elem a").hover
  (
    function () //over
    {
      $(this).css({"background-color": "#6578b8", "color": "#f2f1fa"});
    },
    function () //out
    {
      if ($(this).hasClass("active"))
        $(this).css({"background-color": "#f2f1fa", "color": "#d3723d"});
      else
        $(this).css({"background-color": "#f2f1fa", "color": "#6578b8"});
    }
  );
}

function check_basket_empty()
{
  try
  {
    var sum = parseFloat($.trim($("#sum").html()));
  }
  catch(e)
  {
    sum = 0;
  }
  if (! isFinite(sum))
    sum = 0;
  if (sum <= 0)
    $("#basket_execute").replaceWith('<span class="basket_execute" id="basket_execute">Корзина пуста</span>');
  else
    if ($("#basket_execute").get(0).nodeName != "A")
      $("#basket_execute").replaceWith('<a href="/order/" class="basket_execute" id="basket_execute">Оформить заказ</a>');
}

function set_vends_on_mouse_over_actions()
{
  $("#vends_cat_wrapper a").hover
  (
    function () //over
    {
      $(this).css({"background-color": "#6578B8", "color": "#E5E4F5"});
    },
    function () //out
    {
      if ($(this).hasClass("vends_active_link"))
        $(this).css({"background-color": "#E5E4F5", "color": "#d3723d"});
      else
        $(this).css({"background-color": "#E5E4F5", "color": "#6578B8"});
    }
  );
}

function showBackcallDiv()
{
  var elem = $("#backcall_div");
  if (elem.css('display') == 'none')
    elem.show(800);
}

function hideBackcallDiv()
{
  var elem = $("#backcall_div");
  if (elem.css('display') == 'block')
    elem.hide(800);
}

function backcall_link_click()
{
  var button = $("#backcall_link"), div = $("#backcall_div");  
  div.css("top", Math.min(button.offset().top - div.outerHeight() - 10, $(document).height() - div.outerHeight() - 10));
  div.css("left", Math.min(button.offset().left + button.outerWidth() + 10, $(document).width() - div.outerWidth() - 10));
  showBackcallDiv();
}

function backcall_link_main_click(but, align)
{
  if (align == null)
    align = "bottom";
	var button = $(but), div = $("#backcall_div");
  if (align == "bottom")
  {
    div.css("top", button.offset().top + button.outerHeight() + 10);
    div.css("left", button.offset().left);
  }
  else if (align == "right")
  {
    div.css("top", button.offset().top - (div.outerHeight() / 2));
    div.css("left", Math.min(button.offset().left + button.outerWidth() + 10, $(document).width() - div.outerWidth() - 10));
  }
  showBackcallDiv();
}

var mail_status =
{
  backcall: "free"
};

function backcallSubmitClick()
{
  if (mail_status.backcall == "busy")
    return;
  if ($.trim($("#backcall_name").val() + "") == "")
  {
    alert("Введите ваше имя.");
    return;
  }
  if ($.trim($("#backcall_tel").val() + "") == "")
  {
    alert("Введите телефон для связи.");
    return;
  }
  var
    name = $.trim($("#backcall_name").val() + ""),
    tel = $.trim($("#backcall_tel").val() + ""),
    question = $.trim($("#backcall_question").val() + "");
  mail_status.backcall = "busy";
  $("#backcall_submit").attr("disabled", true).val("Выполняется...");
  var dataObj =
  {
    type: 'backcall',
    name: name,
    tel: tel,
    question: question,
    link: window.location.href
  };
  $.ajax
  (
    {
      async: true,
      cache: false,
      dataType: "text",
      timeout: 15000,
      type: "POST",
      url: "/phpshop/send_mail.php",
      data: 'data=' + encodeURIComponent(JSON.stringify(dataObj)),
      processData: false,
      complete: function (q, status)
      {
        if (status == "success")
        {
          try
          {
            var resp = null;
            try
            {
              eval('resp = ' + q.responseText);
            }
            catch (e)
            {
              alert("Некорректный ответ сервера.");
              throw {};
            }
            if ((typeof(resp) != "object") || (resp == null) || (typeof(resp.status) == "undefined"))
            {
              alert("Некорректный ответ сервера.");
              throw {};
            }
            if (resp.status == "ok")
              alert("Запрос отправлен, в ближайшее время мы свяжемся с вами.");
            else
              alert("При отправке письма произошла ошибка на стороне сервера.\nПовторите попытку или обратитесь к администрации.\nОтвет сервера: " + resp.message);
          }
          catch (e)
          {
          }
        }
        else if (status == "timeout")
        {
          alert("Превышено время ожидания ответа сервера. Повторите попытку позже.");
        }
        else
        {
          alert("При обмене данными с сервером произошла ошибка. Повторите попытку или обратитесь к администрации.");
        }
        $("#backcall_submit").attr("disabled", false).val("Отправить");
        mail_status.backcall = "free";
        hideBackcallDiv();
      }
    }
  );
}

function ext_filter_link_click()
{
	var div = $("#ext_v_div");	
	if (div.css("display") != "block")
	  div.slideDown();
	else
	  div.slideUp();
}

function ext_filter_search_click()
{
	var sel = $("#ext_v_div select");
	var url = "", i, name, val, ar;
	for (i = 0; i < sel.length; i++)
	{
		try
		{
			name = $.trim(sel[i].id.match("^ext_v_([0-9]+)$")[1]);
			val = $.trim(sel[i].value);
		}
		catch(e)
		{
			name = "";
			val = "";
		}
		if ((name != "") && (val != ""))
		  url += "&v[" + name + "]=" + val;
	}
	if (url != "")
	  url = "?ext=true" + url;
	ar = window.location.href.match("([^\/]+)\/\/([^\/]+)\/.+CID_([0-9]+)\.html");
	if (ar != null)
	  window.location.href = ar[1] + "//" + ar[2] +	"/shop/CID_" + ar[3] + ".html" + url;
}

function ext_filter_clear_click()
{
	var ar;
	ar = window.location.href.match("([^\/]+)\/\/([^\/]+)\/.+CID_([0-9]+)\.html");
  if (ar != null)
    window.location.href = ar[1] + "//" + ar[2] + "/shop/CID_" + ar[3] + ".html";
}

function obo_vsem_hover_bind()
{
  $(".obo_vsem_div a").hover
  (
    function () //over
    {
      $(this).css({"background-color": "#6578B8", "color": "#F2F1FA"});
    },
    function () //out
    {
      $(this).css({"background-color": "#F2F1FA", "color": "#6578B8"});
    }
  );
}
