function basket(ELEMENT, ID){
  var id = ID;
  var img = ELEMENT;
  var form = document.getElementById("catalog"+id);
  var price = form.price.value;
  var price2 = form.price2.value;
  
  var quantity = form.item.value;
  
	if (img.src == img.src.replace(/empty/, "full"))
	{
		img.src = img.src.replace(/full/, "empty");
		document.getElementById("catalog"+id).item.value = '';
		quantity = 0;
	}
	else
	{
		img.src = img.src.replace(/empty/, "full");
		
		if (Number(quantity)<1)
		{
			quantity = 1;
			document.getElementById("catalog"+id).item.value = 1;
		} 
	}
//alert(document.getElementById('price').innerHTML);
	var req = new Subsys_JsHttpRequest_Js();

  req.onreadystatechange = function() 
  {
  	if (req.readyState == 4)
  	{
        document.getElementById('price').innerHTML = req.responseJS.arr['price'];
        document.getElementById('quantity').innerHTML = req.responseJS.arr['quantity'];
     }	
  }

	req.caching = false;
	req.open('POST', '/requests/admin/shop/Catalog.php', true);
		
	//alert (id + '; ' + quantity + '; '+price+'; '+price2);
	var data = { id: id, quantity:quantity, price:price, price2:price2};
	req.send(data);
  

	return false;

}
function additem(VAL, ID, PRICE){
	var id = '' + ID;
	var val = '' + VAL;
	var price = '' + PRICE;
	var req = new Subsys_JsHttpRequest_Js();

	req.onreadystatechange = function() {
  		if (req.readyState == 4){
      			document.getElementById('price').innerHTML = req.responseJS.arr['price'];
      			document.getElementById('price2').innerHTML = req.responseJS.arr['price'];
      			document.getElementById('quantity').innerHTML = req.responseJS.arr['quantity'];
            document.getElementById('td'+id).innerHTML = req.responseJS.arr['sum'];      			
     }	
  }

	req.caching = false;
	req.open('POST', '/requests/admin/shop/getData.php', true);
		
	var data = { id: id, val: val, price:price};
	req.send(data);
  

	return false;
}


function removetr(TABLE, ID){
	var table = document.getElementById('' + TABLE);
	var id = '' + ID;
  var tr = document.getElementById('tr' + ID);
  //alert(table+" "+tr+" "+TABLE+" "+ID);
  //removeNamedItem(ss);
  //table.removeChild(tr);
	alert("asgv");
  var req = new Subsys_JsHttpRequest_Js();

	req.caching = false;
	req.open('POST', '/requests/admin/shop/remData.php', true);
		
	var data = { table: table, id: id};
	req.send(data);
  

	return false;
}

function insRow(ID, IDENT)
{
    var id = '' + ID;
    var req = new Subsys_JsHttpRequest_Js();
    
	req.onreadystatechange = function() 
	{
		if (req.readyState == 4)
		{
			with (document.getElementById(IDENT))
			{
				innerHTML = req.responseJS.arr['content'];
				style.display = req.responseJS.arr['content'] != '' ? 'block' : 'none';
			}
		}
	}

	req.caching = false;
	req.open('POST', '/requests/admin/shop/InsertRow.php', true);
		
	var data = { id: id, ident: IDENT};
	req.send(data);
}

function delivery_history(VAL,NAME,FORMNAME){
  document.getElementById(NAME).value = VAL;
  
  var frm = document.getElementById(FORMNAME);
  
  frm.action = '?action=order_req';
  frm.submit();
  return false;
}

function delivery(VAL,STEP,DIVNAME, STREET, BUILDING, FLAT, DELIVERY, APTEKA, LANG){
  val = '' + VAL;

  //alert('step = ' + STEP);
  var step = '' + STEP;
  var history = document.getElementById('history').value;
  
  if(step == '0')
    var type = val;
  else 
  	var type = history;
  
  var cnt = Number(document.getElementById('count').value);
  
  document.getElementById('history').value = type;    
  if(type != history){
      if(cnt>0 ){
        document.getElementById('count').value=0;
        for(i=0;i<cnt;i++)        document.getElementById('MyTable').deleteRow(0);
        cnt = 0;
      }
  }
  ;
	var req = new Subsys_JsHttpRequest_Js();
	req.onreadystatechange = function() {
  		if (req.readyState == 4){
  		
  		// AJAX
            switch(type){
            case '1': // по Киеву
                    switch(step){
                    case '0':   // улица
                          
                          var x=document.getElementById('MyTable').insertRow(cnt);
                          var Cell2 = x.insertCell(0);Cell2.align="left";Cell2.vAlign="top";
                          var Cell1 = x.insertCell(0);Cell1.align="right";Cell1.width="250";Cell1.vAlign="top";
                          
                          Cell1.innerHTML= STREET + ':';
                          Cell2.innerHTML='<input type="text" name="delivery[street]" id="delivery[street]" onkeyup="return help(event, this.value, 0, 0, 3, \'street\', \'' +STREET+ '\', \'' +BUILDING+ '\', \'' +FLAT+ '\',\'' +DELIVERY+ '\',\'' +APTEKA+ '\',\'' +LANG+ '\')"><br><br><div id="street" class="invisible"> </div>';
                          document.getElementById('count').value=1;
                      break;
                    case '1':   // дом
                          if(cnt > 1)
                          {                            
                            for(i=1;i<cnt;i++)
                            	document.getElementById('MyTable').deleteRow(1);
                            
                            cnt = 1;
                          }
                          
                          var mydiv = document.getElementById(DIVNAME);
                          mydiv.InnerHTML = '';
                          mydiv.className = 'invisible';
                          var mydiv = document.getElementById('delivery[street]');
    
                          mydiv.value = req.responseJS.arr['content'];
                          var x=document.getElementById('MyTable').insertRow(cnt);
                          var Cell2 = x.insertCell(0);Cell2.align="left";Cell2.vAlign="top";
                          var Cell1 = x.insertCell(0);Cell1.align="right";Cell1.width="250";Cell1.vAlign="top";
                          
                          Cell1.innerHTML = BUILDING + ':';
                          Cell2.innerHTML ='<input type="text" id="delivery[building]" name="delivery[building]" onkeyup="return help(event, this.value, 1, \'' + val + '\', 1, \'building\',\'' +STREET+ '\',\'' +BUILDING+ '\',\'' +FLAT+ '\',\'' +DELIVERY+ '\',\'' +APTEKA+ '\',\'' +LANG+ '\')"><br><br><div id="building" class="invisible"> </div>'; 
                          //Cell2.innerHTML='<select name="street" onchange="javascript:delivery(this.value,2)"><option value="1">1</option><option value="2">2</option></select>';
                          
                          
                          if ( document.getElementById('delivery[room]') == null ){
                            var x=document.getElementById('MyTable').insertRow(cnt+1);
                            var Cell2 = x.insertCell(0);Cell2.align="left";Cell2.vAlign="top";
                            var Cell1 = x.insertCell(0);Cell1.align="right";Cell1.width="250";Cell1.vAlign="top";
                            
                            Cell1.innerHTML= FLAT + ':';
                            Cell2.innerHTML='<input type="text" id="delivery[room]" name="delivery[room]" >';
                          
                          }
                          
                          document.getElementById('count').value=3;               
                      break;
                    case '2': //  дополнительная информация
                          
                          var mydiv = document.getElementById(DIVNAME);
                          
                          mydiv.InnerHTML = '';
                          mydiv.className = 'invisible';
                          var mydiv = document.getElementById('delivery[building]');
                         
                          mydiv.value = req.responseJS.arr['content'];
                          
                      break;
                    }
              break;
            case '2': // по Украине
                  var x=document.getElementById('MyTable').insertRow(cnt);
                  var Cell2 = x.insertCell(0);Cell2.align="left"; 
                  var Cell1 = x.insertCell(0);Cell1.align="right";Cell1.width="250";
                  Cell1.innerHTML= DELIVERY + ':';
                  Cell2.innerHTML='<input type="text" name="delivery[adress]" size="50">';
                  document.getElementById('count').value=1;      
              break;    
            case '3':   // самовывоз
                  var x=document.getElementById('MyTable').insertRow(cnt);
                  var Cell2 = x.insertCell(0);Cell2.align="left";
                  var Cell1 = x.insertCell(0);Cell1.align="right";Cell1.width="250";  
                  Cell1.innerHTML = APTEKA + ':';
                  Cell2.innerHTML = req.responseJS.arr['content'];
                  document.getElementById('count').value=1;
              break;    
            }
            
      // /AJAX
      }
  }
  
	req.caching = false;
	req.open('POST', '/requests/admin/shop/MasterDelivery.php', true);
		
	var data = { type: type, step: step, val: val, apteka:APTEKA, lang: LANG};
	req.send(data);
  

	return false;  
}


function help(E, VAL, TYPE, IDD, LIMIT, DIVNAME, STREET, BUILDING, FLAT, DELIVERY, APTEKA, LANG){
	var limit = '' + LIMIT;
	var type = '' + TYPE;
	var val = '' + VAL;
	
	var req = new Subsys_JsHttpRequest_Js();
	var mydiv = document.getElementById(DIVNAME);
	
	if(val.length >= limit){
		req.onreadystatechange = function() {
			if (req.readyState == 4){
				mydiv.innerHTML = req.responseJS.arr['content']; 
				mydiv.className = "scroll"              
			}
		}
		
	
	  	req.caching = false;
		req.open('POST', '/requests/admin/shop/KeyPrinter.php', true);
			
		var data = { val: val, type:type, idd: IDD, street:STREET, building:BUILDING, flat:FLAT, delivery:DELIVERY, apteka:APTEKA, lang:LANG};
		req.send(data);
	}
	
  
	return true;
}


// JavaScript Document

//  Установка глобальных переменных


cm=null;                    // сюда будем запоминать 
                                // видимый слой. Начальное 
                               // значение - null.
hide_delay=500;       // Время задержки (в м.с.) авто-закр.
                              // меню. 
tstat=0;                  // Признак активности таймера авто-закр.

// Определяем браузер пользователя

isNS4 = (document.layers) ? true : false;
isIE4 = (document.all && !document.getElementById) ? true : false;
isIE5 = (document.all && document.getElementById) ? true : false;
isNS6 = (!document.all && document.getElementById) ? true : false;


// Функция отображающая и скрывающая слои

// Вход:
// objElement - идентификатор(id) слоя;
// bolVisible - булева переменная:
// true  - отобразить слой;
// false - скрыть слой.

// Выход:
// 1


// P.S: В зависимости от типа браузера
// сценарий для манипуляции с видимостью слоёв
// несколько различается.

function switchDiv(objElement,bolVisible){
if(isNS4||isIE4){
     if(!bolVisible) {
       objElement.visibility ="hidden"
     } else {
       objElement.visibility ="visible"
     }     
 } else if (isIE5 || isNS6) {
      if(!bolVisible){
         objElement.style.display = "none";
         
      } else {
        objElement.style.display = "";
        
        }

      }

return 1;
}



// Функция возвращающая значение указанного ей 
// свойства объекта (не обязательно слоя).

// Вход:
// el    - идентификатор элемента;
// sProp - свойство (left,top...)

// Выход:
// Значение какого-нибудь свойства объекта.



function getPos(el,sProp) {
	var iPos = 0;
	while (el!=null) {
		iPos+=el["offset" + sProp]
		el = el.offsetParent
	}
	return iPos

}



// Функция выдаёт объект с указанным
// ей названием.

// Вход:
// myid - название объекта

// Выход: объект.

function getelementbyid(myid) {
   if (isNS4){
        objElement = document.layers[myid];
     }else if (isIE4) {
        objElement = document.all[myid];
     }else //if (isIE5 || isNS6) {
             objElement = document.getElementById(myid);
    // }
return(objElement);
}



// Функция отображающая|скрывающая
// ,а предварительно ещё и передвигающая
// должным образом слои.


// Вход:
// el - яйчейка таблицы на которой 
// находится указатель;
// m  - наименование слоя, который надо
// отобразить под этой яйчейкой.

function show(el,m) {

// Если имеется видимый слой,
// сделать его невидимым.

 if (cm!=null) {
 switchDiv(cm,false);
 }


// Если указано название слоя для отображения,
// то:
// 1) Получаем его объект;
// 2) X слоя = X яйчейки;
// 3) Y слоя = Y яйчейки + высота яйчейки;
// 4) Делаем слой видимым;
// 5) Сохраняем копию слоя в cm.  


 if (m!=null) {
 m=getelementbyid(m);
 m.style.left = getPos(el,"Left")+"px";
 m.style.top =  getPos(el,"Top")+el.offsetHeight+"px";
 switchDiv(m,true);
 cm=m;
 }

}



// Функция "закрывающая" меню.

// Функция ничего не принимает на вход
// и возвращает 1.

function hidemenu() {

// Устанавливаем задержку равную 
// hide_delay м.с. с помощью таймера; 

timer1=setTimeout("show(null,null)",hide_delay);

// Устанавливаем tstat=1 - признак, того, что таймер запущен.
tstat=1;

return 1;
}



// Функция, останавливающая таймер запущенный
// прошлой функцией. Таким образом,
// меню не пропадает.

// Функция ничего не принимает на вход
// и возвращает 1.

function cancelhide() {
 if (tstat==1) {
 clearTimeout(timer1);
 tstat=0;
 }
return 1;
}



/***********************************************
* Contractible Headers script- © Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use. Last updated Mar 23rd, 2004.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

var enablepersist="on" //Enable saving state of content structure using session cookies? (on/off)
var collapseprevious="no" //Collapse previously open content when opening present? (yes/no)

if (document.getElementById){
document.write('<style type="text/css">')
document.write('.switchcontent{display:none;}')
document.write('</style>')
}

function getElementbyClass(classname){
ccollect=new Array()
var inc=0
var alltags=document.all? document.all : document.getElementsByTagName("*")
for (i=0; i<alltags.length; i++){
if (alltags[i].className==classname)
ccollect[inc++]=alltags[i]
}
}

function contractcontent(omit){
var inc=0
while (ccollect[inc]){
if (ccollect[inc].id!=omit)
ccollect[inc].style.display="none"
inc++
}
}

function expandcontent(cid){
if (typeof ccollect!="undefined"){
if (collapseprevious=="yes")
contractcontent(cid)
document.getElementById(cid).style.display=(document.getElementById(cid).style.display!="block")? "block" : "none"
}
}

function revivecontent(){
contractcontent("omitnothing")
selectedItem=getselectedItem()
selectedComponents=selectedItem.split("|")
for (i=0; i<selectedComponents.length-1; i++)
document.getElementById(selectedComponents[i]).style.display="block"
}

function get_cookie(Name) { 
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) { 
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

function getselectedItem(){
if (get_cookie(window.location.pathname) != ""){
selectedItem=get_cookie(window.location.pathname)
return selectedItem
}
else
return ""
}

function saveswitchstate(){
var inc=0, selectedItem=""
while (ccollect[inc]){
if (ccollect[inc].style.display=="block")
selectedItem+=ccollect[inc].id+"|"
inc++
}

document.cookie=window.location.pathname+"="+selectedItem
}

function do_onload(){
uniqueidn=window.location.pathname+"firsttimeload"
getElementbyClass("switchcontent")
if (enablepersist=="on" && typeof ccollect!="undefined"){
document.cookie=(get_cookie(uniqueidn)=="")? uniqueidn+"=1" : uniqueidn+"=0" 
firsttimeload=(get_cookie(uniqueidn)==1)? 1 : 0 //check if this is 1st page load
if (!firsttimeload)
revivecontent()
}
}


if (window.addEventListener)
window.addEventListener("load", do_onload, false)
else if (window.attachEvent)
window.attachEvent("onload", do_onload)
else if (document.getElementById)
window.onload=do_onload

if (enablepersist=="on" && document.getElementById)
window.onunload=saveswitchstate

