
//id-ник ссылки
var idEl;

// текущий элемент для функции задержки
var curEl="";

var LastCurent = 1;

//время задержки
var SetTime = 500; 

//текущее положение мышки по оси х
var xpos;

//текущее положение мышки по оси y
var ypos;

var y;
var name;
var str;
var ns6=0,ie4=0,ns4=0,op5=0,ie=0;
var cur_hash="";

//var host = "http://www.elitan.ru";
  var host = "http://"+location.hostname;
// нужна для  проверки вывода таблицы с информацией
var opendiv;
if(navigator.appName=="Microsoft Internet Explorer")
{ie=1};
if(navigator.userAgent.indexOf("Opera")>-1)
{op5=1}
else 
if(typeof(document.layers)!="undefined"){ns4=1}
else 
if(document.getElementById && typeof(document.all)=="undefined"){ns6=1}
else 
if(typeof(document.all)!="undefined"&&typeof(document.all.tags)!="undefined"){ie4=1}
if(ns4){origWidth=innerWidth;origHeight=innerHeight;onresize=function(){if(innerWidth!=origWidth||innerHeight!=origHeight)if(confirm("Для корректного отображения страницу необходимо обновить"+(document.forms[0]?"\n\nВНИМАНИЕ!\nНесохраненные данные могут быть потеряны":"")))location.reload()}}


  function res(){
    document.getElementById('mfg').value = 'all';
  }


function dispInit()
{
 if(ns6||ns4||op5)
 {
 screenWidth=screen.availWidth;
 screenHeight=screen.availHeight;
 pageWidth=window.innerWidth;
 pageHeight=window.innerHeight;
 scrollWidth=window.pageXOffset;
 scrollHeight=window.pageYOffset;
 }
else if(ie4)
 {
 screenWidth=window.screen.availWidth;
 screenHeight=window.screen.availHeight;
 pageWidth=document.body.clientWidth;
 pageHeight=document.body.clientHeight;
 scrollWidth=document.body.scrollLeft;
 scrollHeight=document.body.scrollTop;
 }
}



function subRequest()
 {
  AjaxSr("");
  return false;
 }

function AjaxSr(url)
 {      //Если пойс осуществляется через каталог
        //скрываем таблицу с данными по товару
        HideElementInfo();
        if (typeof window.ActiveXObject != 'undefined' )
           {
          SR = new ActiveXObject("Microsoft.XMLHTTP");
          SR.onreadystatechange = ResultData;
           }
        else 
           {
          SR = new XMLHttpRequest();
          SR.onload = ResultData;        
           }

          f  = encodeURIComponent(document.getElementById('find').value);  
       ShowLoadInfo();
       if(url =="")
        {

        url   = host+"/price/index2.php?seenform=y&";
        ev    = document.getElementById('every');
        part  = document.getElementById('part');
        none  = document.getElementById('none');
        Stock = document.getElementById('onStock');
        mfg   = document.getElementById('mfg');
        
             
        if(ev.checked)
          {
            url += "flag="+ev.value;
          }
        else
        if(part.checked)
         {
            url += "flag="+part.value; 
         } 
        else
        if(none.checked)
          {
            url += "flag="+none.value; 
         }

        if(Stock.checked)
         {
                 url += "&onstock=y"; 
         }  
         url += "&mfg=" +mfg.options[mfg.selectedIndex].value + "&find=" + f;

       }
       else
       {


        var Regular =/[^ ]*find=/; 
        var mas = new Array();
        mas = url.split(Regular);
        var val = new Array();
         if (typeof window.ActiveXObject != 'undefined' )
            {
                val = mas[0].split(/&/);
            }
         else
           {
             val = mas[1].split(/&/);
           }
        url = url.replace(/find=[^&]*&/,"find=" + encodeURIComponent(val[0]) + "&");
       } 
        SR.open("GET",url, true );      
        SR.send(null);
 }

function ResultData()
 {
  if ( SR.readyState != 4 )
   return ;
   HideLoadInfo();

   info = document.getElementById('infoSearch');
   info.innerHTML = SR.responseText;
   //CreateHref();
  
 }

function CreateHref()
{
  try
   {   

     if (typeof window.ActiveXObject != 'undefined' )
      {
      test = new ActiveXObject("Microsoft.XMLHTTP");
      }
     else 
      {
      test = new XMLHttpRequest();      
      }


    var del,pole,hidID,href,image,valID,input;
    for(i=1;i<=25;i++)
    {
       del = document.getElementById('f'+i);
       input = document.getElementById('idref'+i);    
       valID = input.getAttribute('value');

       del.action ="";
       while(del.firstChild)
        {
        del.removeChild(del.firstChild);      
        }

        pole = document.createElement("input");
        pole.type = 'text';
        pole.name ='kolich';
        pole.size = '7';
        pole.setAttribute('maxlength',7);
         // pole.setAttribute("onKeyPress","  if(event.keyCode == 13){ add_zakaz('" + valID + "');  event.returnValue = false; } else event.returnValue = true; ");               
        // pole.setAttribute("onKeyPress","if(event.keyCode == 13){alert('preskey'); event.returnValue = false;}");
        pole.setAttribute('id',valID);          
        pole.name = 'id';
        // pole.id = valID;
        del.appendChild(pole);

        hidID = document.createElement("input");
        hidID.type ='hidden';
        hidID.name ='id';
        hidID.value =valID;
        del.appendChild(hidID);

        href = document.createElement("a");
        href.href ="javascript: add_zakaz('"+valID+"');";

        image = document.createElement("img");
        image.border = '0';
        image.src = 'http://elitan.ru/price/images/basket2.gif';
        image.alt = 'Добавить в заказ';
   
        href.appendChild(image);
        del.appendChild(href);
   }
  }
 catch(er)
  {

  }
}


function StopTime (find,nameElement,n,idElement)
{
//выводить таблицу с данными на экран
if(opendiv == 1)
{
 //повтор функции или нет
 if(n == 1)
  {

  // если за отведенное время текущий элемент не изменился то вызывае  ajax-кую функцию
   if (curEl == nameElement)
    { 
     
     
     //делаем текущий элемент пустым
     curEl="";


     // выполнить ajax
      stat(find,nameElement,idElement);

    }
  }
 else
  {
   //меняем текущий элемент в стэке
   curEl= nameElement;
   
   //строковой переменной к присваиваем  значение
   k= "StopTime('"+find+ "','" +nameElement+ "',1,'"+idElement+"')";                       
   //задержка
   setTimeout(k,SetTime);
  }
}
}

function  HideLastBackground (NumberElement)

 {
  sp = document.getElementById(NumberElement);
  sp.style.backgroundColor='#ffffff';
  sp.style.color='#0000ff';
 }

function ShowBackground (cur)
 { 
  try
  { 
  HideLastBackground('sp'+LastCurent);
  LastCurent = cur;  
  sp = document.getElementById('sp'+cur);
  sp.style.backgroundColor='#ff9933';
  sp.style.color='#000000';
  }
  catch(e)
  {
  }
 }

function ShowInfoDiv()
 {
   dispInit(); 
   document.getElementById('proc').style.visibility = "hidden";
   document.getElementById('infoDiv').style.visibility = "visible";
   document.getElementById('infoDiv').style.left = scrollWidth+(pageWidth-300)/2;
   document.getElementById('infoDiv').style.top  = scrollHeight+pageHeight/2;
   document.getElementById('infoDiv').style.height  = "50px";
   document.getElementById('infoDiv').style.width   = "240px";
   document.getElementById('infoDiv').style.background = "#ffff99"; 
  document.getElementById('infoDiv').innerHTML  = "<table style='border-width:1px;border-color:#000000;border-style:solid;padding:0px' width=100% height=100% cellspacing=0 cellpadding=0><tr><td>&nbsp;&nbsp;&nbsp;Товар добавляется в корзину...<br></td></tr></table>";
 }

function ShowLoadDiv()
 {
   dispInit();
   document.getElementById('proc').style.visibility = "hidden";
   document.getElementById('LoadDiv').style.visibility = "visible";
   document.getElementById('LoadDiv').style.left = scrollWidth+(pageWidth-300)/2;
   document.getElementById('LoadDiv').style.top  = scrollHeight+pageHeight/2;
   document.getElementById('LoadDiv').style.height  = "50px";
   document.getElementById('LoadDiv').style.width   = "240px";
   document.getElementById('LoadDiv').style.background = "#ffff99"; 
   document.getElementById('LoadDiv').innerHTML  = "<table style='border-width:1px;border-color:#000000;border-style:solid;padding:0px' width=100% height=100% cellspacing=0 cellpadding=0><tr><td>&nbsp;&nbsp;<img src=/price/images/loading6.gif >&nbsp; Загрузка, Подождите...<br></td></tr></table>";
 }

function ShowLoadInfo()
 {
   dispInit();
   document.getElementById('infoDiv').style.visibility = "visible";
   document.getElementById('infoDiv').style.left = scrollWidth+(pageWidth-300)/2;
   document.getElementById('infoDiv').style.top  = scrollHeight+pageHeight/2;
   document.getElementById('infoDiv').style.height  = "50px";
   document.getElementById('infoDiv').style.width   = "240px";
   document.getElementById('infoDiv').style.background = "#ffff99"; 
   document.getElementById('infoDiv').innerHTML  = "<table style='border-width:1px;border-color:#000000;border-style:solid;padding:0px' width=100% height=100% cellspacing=0 cellpadding=0><tr><td>&nbsp;&nbsp;<img src=/price/images/loading6.gif >&nbsp; Поиск, Подождите...<br></td></tr></table>";
 }


function HideLoadInfo()
{
 document.getElementById('infoDiv').style.visibility = "hidden";
}


function HideInfoDiv()
{
document.getElementById('infoDiv').style.visibility = "hidden";
document.getElementById('proc').style.visibility = "visible";
}
function HideLoadDiv()
{
 document.getElementById('LoadDiv').style.visibility = "hidden";
}
function HideElementInfo()
{
 document.getElementById('proc').innerHTML = "";
}


function add_zakaz(nik, pricenull)
{
   if(testbrowser == 1){
     if(pricenull == 0){
        if (typeof window.ActiveXObject != 'undefined' ){
          zakaz = new ActiveXObject("Microsoft.XMLHTTP");
          zakaz.onreadystatechange = table_zakaz;
        } else {
          zakaz = new XMLHttpRequest();
          zakaz.onload = table_zakaz;
        }
        ShowInfoDiv();
        col = document.getElementById(nik);
        var r = /^[0-9]*$/;
        if(r.test(col.value)){
          try
          {
            url = host+"/price/order_header.php?id=" + nik +"&kolich=" + col.value; 
            col.value="";
            zakaz.open("GET",url, true );
            zakaz.send(null);
          }
          catch(e)
          {
          }
        } else {
          HideInfoDiv();
          alert("введено не целочисленное значение");
          return false;
        }
     } else {
        alert("Вы можете купить данный товар только на сайте sbros.ru. \n Что бы купить данную позицию, перейдите по ссылке в столбце 'Количество:Цена'");
     }
   } else {
        alert("Извините, Ваш браузер может работать \n некорректно в нашем интернет-магазине. \n Рекомендуем использовать посленюю версию Firefox, Opera, Internet Explorer. ");
   }
 }
function table_zakaz()
 {
  if ( zakaz.readyState != 4 )
   return ;
   log = document.getElementById('logo');
   str = zakaz.responseText;

   HideInfoDiv();
   if(str.charAt(0) == "1")
   {
   alert(str.substring(2,str.length));
   }
   else
   {
   log.innerHTML="";
   log.innerHTML= str; 
   }
 }

function stat_catalog(id_group)
 {
      opendiv=0;
      window.location.hash = id_group;
      cur_hash = id_group;
      if (typeof window.ActiveXObject != 'undefined' )
           {
          catal = new ActiveXObject("Microsoft.XMLHTTP");
          catal.onreadystatechange = catalog ;
           }
        else 
           {
          catal = new XMLHttpRequest();
          catal.onload = catalog;
           }
          
          url = host+"/price/request_catal.php?gr=";
          url = url + id_group;
        ShowLoadDiv();
        catal.open("GET",url, true );   
        catal.send(null);
        
 }

 function hash()
 {
    if(cur_hash != window.location.hash.replace('#',''))
     {
         //cur_hash = window.location.hash;
         stat_catalog(window.location.hash.replace('#',''));
         //.substring(1,cur_hash.length));
     }
    setTimeout('hash()', 2);
 }

function catalog()
 {
  if ( catal.readyState != 4 )
   return ;

   document.getElementById("proc").innerHTML = "";
   td1 = document.getElementById('catalog_table');
   td1.innerHTML="";
   td1.innerHTML= catal.responseText;
   document.getElementById('proc').style.visibility = "hidden";
   HideLoadDiv();
 }

function stat (find,nameElement,idElement)
 {  
      opendiv=1;
//      document.getElementById('proc').innerHTML = "";
//      s = document.getElementById(idElement);
//      s.innerHTML = nameElement + ' <img border=0 src="../price/images/loading18.gif">';

        sp = document.getElementById(idElement);
        sp.style.backgroundColor='#ff9933';
       // $("item_info").attr("innerHTML","");
       $("#id_"+current_id).attr("innerHTML","");
//       if(current_id>0)
//       {
//         document.getElementById('id_'+current_id).innerHTML="";
//       }
       current_id=idElement;

       ShowBackground (idElement);
       ShowLoadDiv();   
       idEl = idElement;
       name = nameElement;
       str = find;
       y= ypos;
      if (typeof window.ActiveXObject != 'undefined' )
           {
          Doc = new ActiveXObject("Microsoft.XMLHTTP");
          Doc.onreadystatechange = element ;
           }
        else 
           {
          Doc = new XMLHttpRequest();
          Doc.onload = element;
           }
          url = host+"/price/catal_stock.php";
          url = url + "?find=" + find+"&id="+idElement;
        Doc.open("GET",url, true );
        Doc.send(null);
         
 }

function element()
 {
 if ( Doc.readyState != 4 )
  return ;
 
 //  document.getElementById(idEl).innerHTML = name;
   HideLoadDiv();
   HideLoadDiv();
   document.getElementById('proc').style.visibility = "visible";
   var arr = Doc.responseText.split("^^");
   div_proc = document.getElementById('id_'+arr[1]);
   div_proc.innerHTML = arr[0];
   //
   //div_proc = document.getElementById('item_info');
   //div_proc.innerHTML = arr[0];
   //$('item_info').innerHTML = arr[0];

   
 }
function test()
 {
  ypos=event.y+document.body.scrollTop;
  xpos=event.x+document.body.scrollLeft;
                         

   if(opendiv ==0)
   {
    document.getElementById('proc').innerHTML = "";
    document.getElementById('proc').style.visibility = "hidden";
   }              
   
 }

if(navigator.appName=="Microsoft Internet Explorer")
 document.onmousemove =test;
else
if(navigator.appName== "Netscape")


document.onmousemove = function(e) 
{
  ypos=e.screenY-150 +document.body.scrollTop;
  xpos=e.screenX +document.body.scrollLeft;
 if(opendiv ==0)
   {
    document.getElementById('proc').innerHTML = "";
    document.getElementById('proc').style.visibility = "hidden";
   }              
}

function CityInfo(){
  var sId = document.getElementById("selRegionId").value;
  if (typeof window.ActiveXObject != 'undefined' )
           {
          SR = new ActiveXObject("Microsoft.XMLHTTP");
          SR.onreadystatechange = ResultCity;
           }
        else
           {
          SR = new XMLHttpRequest();
          SR.onload = ResultCity;
           }
           SR.open("GET",host+"/price/city_list.php?id=" + sId, true );
           SR.send(null);
}

function ResultCity(){
  if ( SR.readyState != 4 )
    return ;

  var arr = SR.responseText.split("|");
  var  selObj =  document.getElementById("selCityId");
  selObj.options.length=0;
  j=0;
  for(i=0; i<arr.length-1; i=i+2){
    selObj.options[j] = new Option(arr[i+1],arr[i]);
    j++;
  }
}
function GetItemCatalog(StartPosition,Group)
{
  if (typeof window.ActiveXObject != 'undefined' )
   {
    ItemCatalog = new ActiveXObject("Microsoft.XMLHTTP");
    ItemCatalog.onreadystatechange = UpdateListCatalog;
   }
  else
   {
    ItemCatalog = new XMLHttpRequest();
    ItemCatalog.onload = UpdateListCatalog;
   }
   divSignal = document.getElementById("contentsignal");

   document.getElementById("nextdata").parentNode.removeChild(document.getElementById("nextdata"));
   document.getElementById("contentItem").innerHTML += divSignal.innerHTML +"<span id='imgload'>Подгрузка данных<img  src='price/images/loading18.gif'/></span>";
   document.getElementById("contentsignal").parentNode.removeChild(document.getElementById("contentsignal"));
//   document.getElementById("contentItem").innerHTML += "<img src='price/images/loading6.gif'>";

   StartPosition+=30;
   ItemCatalog.open("GET",host+"/price/get_item_catalog.php?start="+StartPosition+"&gr="+Group, true );
   ItemCatalog.send(null);


 
   
}
function UpdateListCatalog(){
  if ( ItemCatalog.readyState != 4 )
    return ;

   document.getElementById("imgload").parentNode.removeChild(document.getElementById("imgload"));
   document.getElementById("contentItem").innerHTML += ItemCatalog.responseText;


  //document.getElementById("contentItem").removeChild(divSignal);
}

