var currentdiv="";
var openedHelp=0;
var allFeaturesStatus=false;
var allCategoriesStatus=false;
var promptInterval="";
var elementnow;
var allowedImages= new Array('jpg','gif');
var allowedImagesText=".jpg, .gif";
var currentlyOpenedDiv=0;
var currentActiveRow;

/************************* DRAGGING DIVS CODE *****************/

function Browser() {

  var ua, s, i;

  this.isIE    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

var browser = new Browser();

// Global object to hold drag information.

var dragObj = new Object();
dragObj.zIndex = 0;

function dragStart(event, id) {

  var el;
  var x, y;

  // If an element id was given, find it. Otherwise use the element being
  // clicked on.

  if (id)
    dragObj.elNode = document.getElementById(id);
  else {
    if (browser.isIE)
      dragObj.elNode = window.event.srcElement;
    if (browser.isNS)
      dragObj.elNode = event.target;

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Save starting positions of cursor and element.

  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = topStartPositionForDivs;

  // Update element's z-index.

  dragObj.elNode.style.zIndex = ++dragObj.zIndex;

  // Capture mousemove and mouseup events on the page.

  if (browser.isIE) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS) {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {

  var x, y;

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Move drag element by the same amount the cursor has moved.

  dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";

  if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS)
    event.preventDefault();
}

function dragStop(event) {

  // Stop capturing mousemove and mouseup events.

  if (browser.isIE) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  if (browser.isNS) {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
}


/**************************************************************/

function openDiv(id)
{
	
	if(currentdiv!="") document.getElementById(currentdiv).style.top="-1000";
	currentdiv=id;

	for (i=0;i<hiddableSelects.length ;i++ )
	{
		var element=hiddableSelects[i];
		if(document.getElementById(element)) document.getElementById(element).style.visibility="hidden";

		
	}
 
	document.getElementById(id).style.zIndex=2000;

	var scrollTop=document.body.scrollTop;
	document.getElementById(id).style.top=top_position_draggable_divs+scrollTop;

}

function closeDiv(id)
{
 
	document.getElementById(id).style.top="-1000";
	document.getElementById(id).style.zIndex=1;
	
	for (i=0;i<hiddableSelects.length ;i++ )
	{
		var element=hiddableSelects[i];
		if(document.getElementById(element)) document.getElementById(element).style.visibility="visible";
	}

}

function openCloseDraggableDiv(id)
{
 
	var html=document.getElementById("switch_"+id).innerHTML;
	//alert(html);
	
	if(html=="-")
	{
		document.getElementById("inner_"+id).className="hidden";
		document.getElementById("switch_"+id).innerHTML="+";

	}
	else if(html=="+")
	{
		document.getElementById("inner_"+id).className="active";
		document.getElementById("switch_"+id).innerHTML="-";
		
	}

	
	
}

var ns = (navigator.appName.indexOf("Netscape") != -1);
var d = document;
function JSFX_FloatDiv(id, sx, sy)
{
	var el=d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	var px = document.layers ? "" : "px";
	window[id + "_obj"] = el;
	if(d.layers)el.style=el;
	el.cx = el.sx = sx;el.cy = el.sy = sy;
	el.sP=function(x,y){this.style.left=x+px;this.style.top=y+px;};

	el.floatIt=function()
	{
		var pX, pY;
		pX = (this.sx >= 0) ? 0 : ns ? innerWidth : 
		document.documentElement && document.documentElement.clientWidth ? 
		document.documentElement.clientWidth : document.body.clientWidth;
		pY = ns ? pageYOffset : document.documentElement && document.documentElement.scrollTop ? 
		document.documentElement.scrollTop : document.body.scrollTop;
		if(this.sy<0) 
		pY += ns ? innerHeight : document.documentElement && document.documentElement.clientHeight ? 
		document.documentElement.clientHeight : document.body.clientHeight;
		this.cx += (pX + this.sx - this.cx)/8;this.cy += (pY + this.sy - this.cy)/8;
		this.sP(this.cx, this.cy);
		setTimeout(this.id + "_obj.floatIt()", 20);
	}
	return el;
}

var browser = new Browser();

function trim(sString) 
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
return sString;
}



function validatePrice(val)
{

	//checking number validation 
	//--------------------------------------------------------- 

	var cur = /^-?\d{1,3}(,\d{3})*(\.\d{1,2})?$/; 
	var anum= /(^-?\d+$)|(^-?\d+\.\d+$)/; 
	var ret = false; 
	
	if(val.indexOf(",")>-1)
	{
		
		val=val.replace(",",".");

	}

	if(val.indexOf(",")>-1) 
	ret = cur.test(val); 
	else 
	ret = anum.test(val); 

	if(!ret) return false;  
	else return true;

}

function is_number(nr)
{
	
	var expr=/\D/g; 
	var result=expr.test(nr);
	
	if(result) return false; 
	else return true;
	
}

function in_array(string, array2)
{
	 
	var r=false;
	for(j=0;j<array2.length;j++)
	{	
		if(array2[j]==string) r=true;
	}

	return r;
}

function getExtensionByName(filename)
{
	
	var text=filename.split(".");
	var len=text.length-1;
	var ext=text[len];

	return ext.toLowerCase();

}

function number_format(number, decimals, dec_point, thousand_sep, p)
{

	var n=(''+(Math.round(number*(p=Math.pow(10,decimals||0)))/p)).split('.');
	for(var i=(n[0]=n[0].split('')).length-3,j=n[0][0]=='-'?1:0; i>j; i-=3)
	{
		n[0].splice(i,0,thousand_sep||',');
	}
	
	var string=n[0].join('')+(n[1]?(dec_point||'.')+n[1]:'');

	if(string.indexOf(",")!=-1)
	{
	var p=string.split(",");
	var l=p.length-1;
	var ext=p[l];
	if(ext.length==1) string+="0";
	}
	else string+=",00";

	return string;

}

function nettoIntoBrutto(nettoId, bruttoId, taxRate)
{

	var nettoval=document.getElementById(nettoId).value;
	
	if(nettoval.indexOf(",")!=-1) nettoval=nettoval.replace(",",".");
	nettoval=nettoval*1;
	
	var newval=nettoval * ((taxRate / 100) + 1);
	var valnow=number_format(newval, 2, ',' , ' ', '^');
	valnow=valnow.replace(" ","");
	document.getElementById(bruttoId).value=valnow;

}

function bruttoIntoNetto(nettoId, bruttoId, taxRate)
{
	
	var bruttoval=document.getElementById(bruttoId).value;
	
	if(bruttoval.indexOf(",")!=-1) bruttoval=bruttoval.replace(",",".");
	bruttoval=bruttoval*1;

	var newval=bruttoval / ((taxRate / 100) + 1);
	var valnow=number_format(newval, 4, ',' , ' ', '^');
	valnow=valnow.replace(" ","");
	document.getElementById(nettoId).value=valnow;
}


function sortparts(sortedby)
{
	
 
	if(document.getElementById('key_sortby')) document.getElementById('key_sortby').value=sortedby;
	freezePartDetailsForSearchForm();
	document.searchpartform.submit();

}

function changePartsAmountPerPage(val)
{
	
	if(document.getElementById('key_perpage')) document.getElementById('key_perpage').value=val;
	
	setNewSearchForParts();
	freezePartDetailsForSearchForm();
	document.searchpartform.submit();
}

function changePageForParts(e,val, maxval)
{
	
	maxval=maxval*1;

	if(window.event) // IE 
	{ 
		keynum = e.keyCode 
	} 
	else if(e.which) // Netscape/Firefox/Opera 
	{ 
		keynum = e.which 
	} 

	if (keynum==13)
	{
		
		var expr=/\D/g;
		var result=expr.test(val); 
		
		if(result || val<1 || val>maxval || trim(val)=='')
		{
			alert("Wpisz wartość od 1 do "+maxval);	
			document.getElementById("currentpageval").focus();
		}
		else
		{
		
			document.getElementById("key_currentpage").value=val;
			showNotificationDiv();
			freezePartDetailsForSearchForm();
			document.searchpartform.submit();
		}

	}
}

function rewindParts(action, curval, maxval)
{
	
	curval=curval*1;
	maxval=maxval*1;
	
	if(action=='start') curval=1;
	else if(action=='previous') curval-=1;
	else if(action=='next') curval+=1;
	else if(action=='end') curval=maxval;

	document.getElementById("key_currentpage").value=curval;
	showNotificationDiv();
	freezePartDetailsForSearchForm();
	document.searchpartform.submit();
}

function showNotificationDiv()
{
	if(document.getElementById('notificationdiv'))
	{
		var top=document.getElementById('notificationdiv').offsetTop;
		
		if (browser.isIE) {
			var y =document.body.scrollTop;
		  }
		  if (browser.isNS) {
			var y = window.scrollY;
		  }

		document.getElementById('notificationdiv').style.top=top+y;
		document.getElementById('notificationdiv').style.visibility='visible';

	}
}

function hideNotificationDiv()
{
	if(document.getElementById('notificationdiv'))
	{
		document.getElementById('notificationdiv').style.top='-1000';
		document.getElementById('notificationdiv').style.visibility='visible';
	}
}

function setNewSearchForParts()
{
	if(document.getElementById('key_newsearch')) document.getElementById('key_newsearch').value="yes";
}

function updateCheckboxesList(action)
{
	
	if(!action) return;
	
	var d=document.resultsform;
	
	showNotificationDiv();

	if(action=='setall')
	{
		
		for(i=0;i<d.elements.length;i++)
		{

			var type=d.elements[i].type;
			var checked=d.elements[i].checked;
			if(type=='checkbox' && !checked) d.elements[i].checked=true;

		}
	}
	
	else if(action=='resetall')
	{
		
		for(i=0;i<d.elements.length;i++)
		{

			var type=d.elements[i].type;
			var checked=d.elements[i].checked;
			if(type=='checkbox' && checked) d.elements[i].checked=false;

		}
	}
	
	else if(action=='invertall')
	{
		
		for(i=0;i<d.elements.length;i++)
		{

			var type=d.elements[i].type;
			var checked=d.elements[i].checked;
			if(type=='checkbox' && checked) d.elements[i].checked=false;
			else if(type=='checkbox' && !checked) d.elements[i].checked=true;

		}
	}

	document.getElementById("checkboxesListSelect").selectedIndex=0;

	hideNotificationDiv();
}

function setRow(id)
{
	
	var d=document.resultsform;
	id="idslist_"+id;
	
	if(!document.getElementById(id)) return;

	var checked=d.elements[id].checked;

	if(checked) d.elements[id].checked=false;
	else if(!checked) d.elements[id].checked=true;

}

function performAction()
{
	
	var index=document.getElementById('performActionSelect').selectedIndex;
	
	if(!document.resultsform)
	{
		alert("Lista wynikowa jest pusta!");
		return;
	}
	if(index<1)
	{
		alert("Nie wybrałeś żadnej akcji");
		return;
	}
	else  
	{
		var d=document.resultsform;
		var ischecked=false;
		var checkedCounter=0;
		showNotificationDiv();

		for(i=0;i<d.elements.length;i++)
		{
			var type=d.elements[i].type;
			var checked=d.elements[i].checked;
			var name=d.elements[i].name;
			
			if(name.indexOf("idslist[]")!='-1' && type=='checkbox' && checked)
			{
				ischecked=true;
				checkedCounter++;
			}

		}
		
		hideNotificationDiv();

		if(!ischecked)
		{
			alert("Nie wybrałeś żadnych danych!");
			return;
		}

		var action=document.getElementById('performActionSelect').options[index].value;
		
	 
		if(action=='deleteclients')
		{
			if(confirm("Czy na pewno chcesz usunąć wybranych klientów?"))
			{
				d.a.value=action;
				d.submit();
			}
		}

		else if(action=='deleteorders')
		{
			if(confirm("Czy na pewno chcesz usunąć wybrane zamówienia?"))
			{
				d.a.value=action;
				d.submit();
			}
		}

		else if(action=='deleteproducts')
		{
			
			if(checkedCounter==1) var deltext="Czy na pewno chcesz usunąć ten produkt?";
			else if(checkedCounter>1) var deltext="Czy na pewno chcesz usunąć wybrane produkty?";

			if(confirm(deltext))
			{
				d.a.value=action;
				d.submit();
			}
		}

		else if(action=='delassociation')
		{
			if(confirm("Czy na pewno chcesz usunąć powiązania dla wybranych produktów?"))
			{
				d.a.value=action;
				d.submit();
			}
		}
		else
		{
		d.a.value=action;
		d.submit();
		}
	}

}

function pressTab(id, preffixid)
{
	
	if(currentdiv!="") 
	{
		if(document.getElementById(currentdiv))
		{
			document.getElementById(currentdiv).style.top="-1000";
			//currentdiv="";
		}
	}

	var maxid=50;
	
	for(i=1;i<=maxid;i++)
	{
		 var idno=preffixid+""+i;
		 if(document.getElementById(idno)) document.getElementById(idno).style.display='none';
		
		var idno="tab_left"+i;
		 if(document.getElementById(idno)) document.getElementById(idno).className='tab_left_off';
		 
			var idno="tab_middle"+i;
		if(document.getElementById(idno)) document.getElementById(idno).className='tab_middle_off';

		var idno="tab_right"+i;
		 if(document.getElementById(idno)) document.getElementById(idno).className='tab_right_off';
	}
	
	var idno=preffixid+""+id;
	if(document.getElementById(idno)) document.getElementById(idno).style.display='block';
	
	var idno="tab_left"+id;
		 if(document.getElementById(idno)) document.getElementById(idno).className='tab_left_on';
		 
			var idno="tab_middle"+id;
		if(document.getElementById(idno)) document.getElementById(idno).className='tab_middle_on';

		var idno="tab_right"+id;
		 if(document.getElementById(idno)) document.getElementById(idno).className='tab_right_on';

	if(document.searchpartform) document.searchpartform.activeTab.value=id;
	if(document.beheerform) document.beheerform.activeTab.value=id;
	
}

function fireEvent(obj,evt){
	
	var fireOnThis = obj;
	if( document.createEvent ) {
	  var evObj = document.createEvent('MouseEvents');
	  evObj.initEvent( evt, true, false );
	  fireOnThis.dispatchEvent(evObj);
	} else if( document.createEventObject ) {
	  fireOnThis.fireEvent('on'+evt);
	}
}

function pressTabDistr(id)
{
	
	var maxid=10;
	for(i=1;i<=maxid;i++)
	{
		 var idno="layer"+i;
		 if(document.getElementById(idno)) document.getElementById(idno).style.display='none';
	}
	
	if(id==1) var idButton="btn_distr1";
	else if(id==2) var idButton="btn_distr2";
	else if(id==3) var idButton="btn_distr3";
	else if(id==4) var idButton="btn_distr4";

	document.getElementById("distr1").className="general-FormPart-Btn";
	document.getElementById("distr2").className="contact-FormPart-Btn";
	document.getElementById("distr3").className="payment-FormPart-Btn";
	document.getElementById("distr4").className="sale-FormPart-Btn";
	
	if(document.getElementById("layer"+id)) document.getElementById("layer"+id).style.display='block';
	
	document.getElementById("distr"+id).className="active "+document.getElementById("distr"+id).className;

}

function popUp(urlnow, namenow, widthnow, heightnow, activation) 
{ 
	
	newWindow = window.open(urlnow, namenow, 'width='+widthnow+',height='+heightnow+',toolbar=no,focus=yes,menubar=yes,location=no,scrollbars=yes,resizable=yes,status'); 
	if(activation) newWindow.focus(); 

}


function enlargeImage(id, name)
{
	popUp("enlarge_image.php?id="+id+"&name="+escape(name),"zdjęcie",500,500,1);
}

function CaricaFoto(img)
{
 foto1= new Image();
 foto1.src=(img);
 Controlla(img);
}

function Controlla(img)
{
 if((foto1.width!=0)&&(foto1.height!=0)){
   viewFoto(img);
}

 else
{
   funzione="Controlla('"+img+"')";
   intervallo=setTimeout(funzione,20);
 }
}

function viewFoto(img)
{
 largh=foto1.width+20;
 altez=foto1.height+20;
 stringa="width="+largh+",height="+altez;
 finestra=window.open(img,"",stringa);
}

function resetFiltr()
{
	
	if(document.searchpartform)
	{
		document.searchpartform.key_resetfilter.value='1';
		document.searchpartform.submit();
	}
}

function confPartDel(id)
{
	if(confirm("Czy na pewno chcesz usunąć ten produkt")) document.location.href="management.php?s=products&a=deleteproducts&idslist="+id;
}

function confClientDel(id)
{
	if(confirm("Czy na pewno chcesz usunąć tego klienta?")) document.location.href="management.php?s=clients&a=deleteclients&idslist="+id;
}

function confDelIP(id)
{
	if(confirm("Czy chcesz zablokować adres IP tego klienta i usunąć go?")) document.location.href="management.php?s=clients&a=delIP&idslist="+id;
}

function confOrderDel(id)
{
	if(confirm("Czy na pewno chcesz usunąć to zamówienie?")) document.location.href="management.php?s=orders&a=deleteorders&idslist="+id;
}

function confManualOrderDel(id)
{
	if(confirm("Czy na pewno chcesz usunąć to zamówienie?")) document.location.href="management.php?s=orders_manual&a=deleteorders&idslist="+id;
}

function confAssociatedDel(id)
{
	if(confirm("Czy na pewno chcesz usunąć powiązania dla tego produktu?")) document.location.href="management.php?s=associated&a=delassociation&idslist="+id;
}

function unlinkPartFromOrder(pid)
{

	$.ajax({
		   
		   type: "POST",
		  
		   url: "/ajax/admin_product2order.php",
		   
		   data: "pid="+pid+"&action=delete",
		   
		   success: function(msg)
			{
			 document.getElementById("orderDetailsDiv").innerHTML=msg;
			closeDiv("chooseProductDiv");
		   }
		 });
}

function freezePartDetailsForSearchForm()
{
}

function changePaymentForAddingOrder(paymentid)
{
	
	$.ajax({
		   
		   type: "POST",
		  
		   url: "/ajax/admin_product2order.php",
		   
		   data: "paymentid="+paymentid+"&action=changepayment",
		   
		   success: function(msg)
			{
			 document.getElementById("orderDetailsDiv").innerHTML= msg;
			closeDiv("chooseProductDiv");
		   }
		 });
}

function changeAmountForOrder(partid, element)
{
	
	clearTimeout(intervalid);

	intervalid=setTimeout(
		function()
		{
		updateAmountForOrder(partid, element);
		}
		,1500);
}

// used on product cart in front-end!
function add2basketFromProductCart(pid)
{
	
	var q=trim(document.getElementById("product_quantity").value);

	if(!is_number(q) || trim(q)=='' || trim(q)==0)
	{
		alert("Wprowadź liczbę całkowitą większą od zera!");
		document.getElementById("product_quantity").focus();
	}
	else addProduct2basket(pid, q);

}

function add2basketFromCard(elid)
{
	var val=trim(document.getElementById("quantity"+elid).value);
	var element=document.getElementById("units"+elid);
	var selected=element.selectedIndex;
	var id=element.options[selected].value;
	var formatid="format_"+elid+"_"+selected;
	var formatQuantity=document.getElementById(formatid).value;
	//alert(val+", "+id+", "+formatQuantity);
	if(!val)
	{
		alert("Wprowadź ilość.");
		document.getElementById("quantity"+elid).focus();
	}

	else if(formatQuantity=='decimal' && !validatePrice(val) || val==0 || val<0)
	{
		alert("Wprowadź poprawnie ilość wybranego produktu.");
		document.getElementById("quantity"+elid).focus();
	}

	else if(formatQuantity=='int' && !is_number(val) || val==0 || val<0)
	{
		alert("Niepoprawna wartość. Wprowadź liczbę całkowitą.");
		document.getElementById("quantity"+elid).focus();
		return;
	}
	else
	{
		val=trim(val.replace(",","."));
		val*=1;
		addProduct2basket(id, val);
		//alert(elid);
		//viewAddToCartInfo($(".supplierItem"));
		viewAddToCartInfo($('.prodItem[title="'+elid+'"]'));
		viewAddToCartInfo($('.supplierItem-inner[title="'+elid+'"]').parent());
	}
}

function addProduct2basket(pid, amount)
{

	//alert(amount);
	$.ajax({
		   
	type: "POST",
	url: "/ajax/add_product2_basket.php",
	data: "pid="+pid+"&amount="+amount,
	success: function(msg)
	{
		
		msg=msg.split("||");
		
		if(document.getElementById("basketProductsAmount")) document.getElementById("basketProductsAmount").innerHTML=msg[0];

		if(document.getElementById("basketProductsSum")) document.getElementById("basketProductsSum").innerHTML=msg[1];

		if(document.getElementById("basketProductsLastAdded")) document.getElementById("basketProductsLastAdded").innerHTML=msg[2];
		

		if(msg[0]*1)
		{
			document.getElementById("basketBasketBoxDetails").style.display="block";
			document.getElementById("lastAddedText").style.display="block";
		}
		else
		{
			document.getElementById("basketBasketBoxDetails").style.display="none";
			document.getElementById("lastAddedText").style.display="none";
		}
		//alert("Produkt dodany do koszyka");

		//document.location.href=linkprefix+",,,,,koszyk";
	}
	});
}

function addProduct2przech(pid, amount)
{

	$.ajax({
		   
	type: "POST",
	url: "/ajax/manage_przechowalnia.php",
	data: "action=checkProduct&pid="+pid,

	success: function(msg)
	{
		
		//msg==-1
		//if(false) alert("Ten produkt jest już zapamiętany w przechowalni!");
		if(msg!=-1)
		{
			$.ajax({
			type: "POST",
			url: "/ajax/manage_przechowalnia.php",
			data: "action=add&pid="+pid+"&amount="+amount,
			success: function(msg)
			{
				
				if(document.getElementById("przechowalniaProductsAmount")) document.getElementById("przechowalniaProductsAmount").innerHTML=msg;
				
				//alert("Produkt został zapamiętany w przechowalni!");	
			}
			});
		}
	}
	});
}

function confDelBasket()
{

	if(confirm("Czy na pewno chcesz wyczyścić zawartość koszyka?"))
	{	
		var link=linkprefix+",,,,,deletebasket";
		document.location.replace(link);
	}

}

function confDelPrzech()
{

	if(confirm("Czy na pewno chcesz wyczyścić zawartość przechowalni?"))
	{	
		var link=linkprefix+",,,,,deleteprzech";
		document.location.replace(link);
	}

}

// used in CMS
function updateAmountForOrder(partid, element)
{

 	if(!is_number(element.value) || trim(element.value)=='' || trim(element.value)==0)
	{
		alert("Wprowadź liczbę całkowitą większą od zera!");
		element.focus();
	}
	else
	{
		
		$.ajax({
		   
		   type: "POST",
		  
		   url:	"/ajax/admin_product2order.php",
		   
		   data: "partid="+partid+"&action=changeamount&amount="+element.value,
		   
		   success: function(msg)
			{
			 document.getElementById("orderDetailsDiv").innerHTML= msg;
			closeDiv("chooseProductDiv");
		   }
		 });

	
	}


}

function validateDate(val)
{

	var expr=/^([0-9]{4})[\-]([0-9]{2})[\-]([0-9]{2})+$/;
	var result=expr.test(val);
	
	if(!result) 
	{
		return false;
	}
	return true;

}

function changeStatus(section, sql_table, sql_column, sql_id, sql_set_value, tdid)
{

	// change image in list

	if(sql_set_value==0) 
	{
		srcnow="images/cancel.gif";
		var sql_value=1;
	}	
	
	else if(sql_set_value==1) 
	{
		srcnow="images/accept.gif";
		var sql_value=0;
	}
	var newcontent="<a href=\"javascript:changeStatus('"+section+"', '"+sql_table+"', '"+sql_column+"','"+sql_id+"', '"+sql_value+"', '"+tdid+"')\"><img src='"+srcnow+"' width=16 height=16></a>";
	
	showNotificationDiv();

	$.ajax({
		   
	type: "POST",
  
	url: "/ajax/set_activation.php",
   
	data: "sql_table="+sql_table+"&sql_column="+sql_column+"&sql_id="+sql_id+"&sql_set_value="+sql_set_value,

	success: function(msg)
	{
		
		hideNotificationDiv();
		if(document.getElementById(tdid)) document.getElementById(tdid).innerHTML=newcontent;

	}
	});

}

function getRidPL(text)
{
	text=text.replace("ą","a");
	text=text.replace("ć","c");
	text=text.replace("ę","e");
	text=text.replace("ł","l");
	text=text.replace("ń","n");
	text=text.replace("ó","o");
	text=text.replace("ś","s");
	text=text.replace("ż","z");
	text=text.replace("ź","z");

	text=text.replace("Ą","A");
	text=text.replace("Ć","C");
	text=text.replace("Ę","E");
	text=text.replace("Ł","L");
	text=text.replace("Ń","N");
	text=text.replace("Ó","O");
	text=text.replace("Ś","S");
	text=text.replace("Ż","Z");
	text=text.replace("Ź","Z");
	
	return text;
}

function prepareURL(str)
{
	if(!str) return "";
	str=getRidPL(str);

	var signs=new Array('/','.',';','-','?','&','%','!','@','#','$','^','(',')',"'",'"');

	for(i=0;i<signs.length;i++)
	{
		var val=signs[i];
		str=str.replace(val,"");
	}

	str=str.replace(" ","_");
	str=str.replace(",","_");
	str=str.replace("____","_");
	str=str.replace("___","_");
	str=str.replace("__","_");
	str=str.toLowerCase();
	return str;
}

function showLoading()
{
	var d=document.featuresform;

	for(i=1;i<=100;i++)
	{
		var elementID="loader"+i;
		if(document.getElementById(elementID)) document.getElementById(elementID).style.display="block";
	}
}

function reloadFeaturesList(el, dostawca_id)
{
	
	showLoading();

	var checked=el.checked;
	var val=el.value;
	var name=el.name;
	
	if(checked) var action="add"; else var action="delete";
	
	if(document.getElementById("availabilityCheckbox").checked) var checker=1;
	else var checker=0;

	$.ajax({
	   type: "POST",
	   url:	"/ajax/get_features_list.php",
	   data: "action="+action+"&value="+val+"&name="+name+"&dostawca_id="+dostawca_id+"&features_availability="+checker,
	  
		success: function(msg)
		{
			msg=msg.split(">>>CURNO<<<");
			var curno=msg[1];
			msg=msg[0];
			msg=msg.replace(">>>CURNO<<<","");

			document.getElementById('features_content').innerHTML=msg;

			if(document.getElementById('productsListContainer')) document.getElementById('productsListContainer').innerHTML="";

			if(curno) refreshCurrentRow(curno);
		}
	});
}

function resetColumn(col, dostawca_id)
{

	showLoading();
	
	if(document.getElementById("availabilityCheckbox").checked) var checker=1;
	else var checker=0;

	$.ajax({
	   type: "POST",
	   url:	"/ajax/get_features_list.php",
	   data: "action=deleteColumn&colname="+col+"&features_availability="+checker+"&dostawca_id="+dostawca_id,
	  
		success: function(msg)
		{
			document.getElementById('features_content').innerHTML=msg;
			//document.location.href=document.featuresform.startlink.value;

			if(document.getElementById('productsListContainer')) document.getElementById('productsListContainer').innerHTML="";
		}
	});
}

function resetFilters()
{
	
	if(confirm("Czy na pewno chcesz usunąć wszystkie filtry?"))
	{

		showLoading();
		
		if(document.getElementById("availabilityCheckbox").checked) var checker=1;
		else var checker=0;

		$.ajax({
		   type: "POST",
		   url:	"/ajax/get_features_list.php",
		   data: "action=deleteFilters",
		  
			success: function(msg)
			{
				//document.getElementById('features_content').innerHTML=msg;
				var link=document.featuresform.startlink.value;
				document.location.href=link;
			}
		});
	}
}

function reloadFeaturesAvailable(dostawca_id)
{
	showLoading();
	var checker=0;

	if(document.getElementById("availabilityCheckbox")) 
	{
		if(document.getElementById("availabilityCheckbox").checked) var checker=1;
	}
	
	$.ajax({
	   type: "POST",
	   url:	"/ajax/get_features_list.php",
	   data: "action=deleteFilters&features_availability="+checker+"&dostawca_id="+dostawca_id,
	  
		success: function(msg)
		{
		
			document.getElementById('features_content').innerHTML=msg;
			//document.location.href=document.featuresform.startlink.value;

			if(document.getElementById('productsListContainer')) document.getElementById('productsListContainer').innerHTML="";

			// brak produktow
			if(msg.indexOf("pusto_brak_produktow")!=-1)
			{
			
				if(document.getElementById("noProductsFormDiv")) document.getElementById("noProductsFormDiv").style.display="block";
			}
		}
	});

}

function back2filterResults()
{
	document.getElementById("showLoaderImageEmptyResults").style.visibility="visible";
	reloadFeaturesAvailable();
}

function nextList()
{
	var d=document.featuresform;
	var item=d.active_row.value;
	var maxrows=d.features_rows.value*1;

	var tableElement="featuresList"+item;
	
	if(document.getElementById(tableElement))
	{
		
		document.getElementById(tableElement).style.display="none";
		
		item++;
		var nextElement="featuresList"+item;
		document.getElementById(nextElement).style.display="block";
		
		document.getElementById("previouslist").style.display="block";
		
		if(item>=maxrows) document.getElementById("nextlist").style.display="none";

		d.active_row.value=item;
	}
}

function previousList()
{
	
	var d=document.featuresform;
	var item=d.active_row.value;
	var maxrows=d.features_rows.value*1;

	var tableElement="featuresList"+item;
	
	if(document.getElementById(tableElement))
	{
		
		document.getElementById(tableElement).style.display="none";
		
		item--;
		var prevElement="featuresList"+item;
		document.getElementById(prevElement).style.display="block";
		
		document.getElementById("nextlist").style.display="block";
		
		if(item<=1) document.getElementById("previouslist").style.display="none";

		d.active_row.value=item;
	}
}

function categories()
{

	currentlyOpenedDiv="categoriesDiv";

	if(document.getElementById('f_feature_1')) document.getElementById('f_feature_1').style.visibility="hidden";

	if(document.getElementById('f_feature_2')) document.getElementById('f_feature_2').style.visibility="hidden";
	
	if(document.getElementById('f_feature_3')) document.getElementById('f_feature_3').style.visibility="hidden";

	if(document.getElementById('f_feature_4')) document.getElementById('f_feature_4').style.visibility="hidden";

	if(document.getElementById('showPerPageSelect')) document.getElementById('showPerPageSelect').style.visibility="hidden";

	var maxwidth=screen.availWidth;
	var divwidth=725;
	var x=(maxwidth/2-divwidth/2)-100;
	document.getElementById("categoriesDiv").style.left=x+"px";
	document.getElementById('categoriesDiv').style.display="block";
	//document.getElementById('categoriesDiv').focus();

	// reload all categories links list just for the 1st time
	if(!allCategoriesStatus)
	{
		allCategoriesStatus=true;
		$.ajax({
			type: "POST",
			url:	"/ajax/get_all_categories_links.php",
			data: "action=getAllCategoriesList&linkprefix="+linkprefix,
		  
			success: function(msg)
			{
				if(document.getElementById('categoriesDiv_content')) document.getElementById('categoriesDiv_content').innerHTML=msg;
			}
		});
	}

}

function closeCategories()
{
	
	currentlyOpenedDiv="";

	document.getElementById('categoriesDiv').style.display="none";

	if(document.getElementById('f_feature_1')) document.getElementById('f_feature_1').style.visibility="visible";

	if(document.getElementById('f_feature_2')) document.getElementById('f_feature_2').style.visibility="visible";
	
	if(document.getElementById('f_feature_3')) document.getElementById('f_feature_3').style.visibility="visible";

	if(document.getElementById('f_feature_4')) document.getElementById('f_feature_4').style.visibility="visible";

	if(document.getElementById('showPerPageSelect')) document.getElementById('showPerPageSelect').style.visibility="visible";


}

function showAllFeatures()
{
		
	currentlyOpenedDiv="allFeaturesDiv";

	if(document.getElementById('f_feature_1')) document.getElementById('f_feature_1').style.visibility="hidden";

	if(document.getElementById('f_feature_2')) document.getElementById('f_feature_2').style.visibility="hidden";
	
	if(document.getElementById('f_feature_3')) document.getElementById('f_feature_3').style.visibility="hidden";

	if(document.getElementById('f_feature_4')) document.getElementById('f_feature_4').style.visibility="hidden";

	if(document.getElementById('showPerPageSelect')) document.getElementById('showPerPageSelect').style.visibility="hidden";

	var maxwidth=screen.availWidth;
	var divwidth=725;
	var x=(maxwidth/2-divwidth/2)-100;
	document.getElementById("allFeaturesDiv").style.left=x+"px";
	document.getElementById('allFeaturesDiv').style.display="block";
	//document.getElementById('allFeaturesDiv').focus();

	// reload all features content just for the 1st time
	if(!allFeaturesStatus)
	{
		allFeaturesStatus=true;
		$.ajax({
			type: "POST",
			url:	"/ajax/get_all_features.php",
			data: "action=getAllFeatures",
		  
			success: function(msg)
			{
				if(document.getElementById('allFeaturesDiv_content')) document.getElementById('allFeaturesDiv_content').innerHTML=msg;

				if(document.getElementById('all_features_buttons')) document.getElementById('all_features_buttons').style.visibility="visible";
			}
		});
	}


}

function closeAllFeatures()
{
	
	currentlyOpenedDiv="";

	document.getElementById('allFeaturesDiv').style.display="none";

	if(document.getElementById('f_feature_1')) document.getElementById('f_feature_1').style.visibility="visible";

	if(document.getElementById('f_feature_2')) document.getElementById('f_feature_2').style.visibility="visible";
	
	if(document.getElementById('f_feature_3')) document.getElementById('f_feature_3').style.visibility="visible";

	if(document.getElementById('f_feature_4')) document.getElementById('f_feature_4').style.visibility="visible";

	if(document.getElementById('showPerPageSelect')) document.getElementById('showPerPageSelect').style.visibility="visible";


}

function openAllCategories()
{
	closeAllFeatures();
	categories();
}

function openAllFeatures()
{
	//if(currentlyOpenedDiv=='categoriesDiv') return;
	closeCategories();
	showAllFeatures();
}

function getDistributorProductsLink(el)
{
	var index=el.selectedIndex;
	var did=el.options[index].value;
	var name=el.options[index].text;
	
	if(index==0) var link=makeLink(linkprefix);
	else var link=makeLink(linkprefix+",,,,,,,,"+did+","+prepareURL(name));

	document.location.href=link;

}

function printSite(elementid)
{
	if(document.getElementById(elementid))
	{
		popUp(server+"/print_site.php?id="+elementid,"Metalpedia",840,500,1);
	}
}

function makeLink(link)
{
	return link;
}

function showLoadingAllFeatures()
{
	if(document.getElementById("reloader_allfeatures")) document.getElementById("reloader_allfeatures").style.visibility="visible";
}

function hideLoadingAllFeatures()
{
	if(document.getElementById("reloader_allfeatures")) document.getElementById("reloader_allfeatures").style.visibility="hidden";
}

function reloadAllFeaturesList(el)
{
	showLoadingAllFeatures();

	var checked=el.checked;
	var val=el.value;
	var name=el.name;
	//alert(val);

	if(checked) var action="add"; else var action="delete";
	
	if(document.getElementById("availabilityCheckbox").checked) var checker=1;
	else var checker=0;

	$.ajax({
	   type: "POST",
	   url:	"/ajax/get_all_features.php",
	   data: "action="+action+"&value="+val+"&name="+name+"&features_availability="+checker,
	  
		success: function(msg)
		{
			document.getElementById('allFeaturesDiv_content').innerHTML=msg;
			hideLoadingAllFeatures();
		}
	});
}

function resetColumnAllFeatures(col)
{

	showLoadingAllFeatures();
	
	if(document.getElementById("availabilityCheckbox").checked) var checker=1;
	else var checker=0;

	$.ajax({
	   type: "POST",
	   url:	"/ajax/get_all_features.php",
	   data: "action=deleteColumn&colname="+col+"&features_availability="+checker,
	  
		success: function(msg)
		{
			document.getElementById('allFeaturesDiv_content').innerHTML=msg;
			hideLoadingAllFeatures();
		}
	});
}

function resetFiltersAllFeatures()
{
	if(confirm("Czy na pewno chcesz usunąć wszystkie filtry?"))
	{

		showLoadingAllFeatures();
		
		if(document.getElementById("availabilityCheckbox").checked) var checker=1;
		else var checker=0;

		$.ajax({
		   type: "POST",
		   url:	"/ajax/get_all_features.php",
		   data: "action=deleteFilters",
		  
			success: function(msg)
			{
				document.getElementById('allFeaturesDiv_content').innerHTML=msg;
				hideLoadingAllFeatures();
			}
		});
	}
}

function reloadFeaturesAvailableAllFeatures()
{
	showLoadingAllFeatures();
	var checker=0;
	if(document.getElementById("availabilityCheckbox")) 
	{
		if(document.getElementById("availabilityCheckbox").checked) var checker=1;
	}
	
	$.ajax({
	   type: "POST",
	   url:	"/ajax/get_all_features.php",
	   data: "action=deleteFilters&features_availability="+checker,
	  
		success: function(msg)
		{
			document.getElementById('allFeaturesDiv_content').innerHTML=msg;
			hideLoadingAllFeatures();
		}
	});
}

function checkSearchField(el)
{
	
	if (document.getElementById(el.id).value=="nazwa produktu, firmy, kategorii...")
	{
		document.getElementById(el.id).value="";
	}
	else if (document.getElementById(el.id).value=="")
	{
		document.getElementById(el.id).value="nazwa produktu, firmy, kategorii...";
	}
}

function checkSearchForm()
{
	
	var d=document.searchform;
	var index1=d.f_feature_1.selectedIndex;
	var index2=d.f_feature_2.selectedIndex;
	var index3=d.f_feature_3.selectedIndex;
	var index4=d.f_feature_4.selectedIndex;

	var select1=d.f_feature_1.options[index1].value;
	var select2=d.f_feature_2.options[index2].value;
	var select3=d.f_feature_3.options[index3].value;
	var select4=d.f_feature_4.options[index4].value;

	var keyword=trim(d.f_keyword.value);

	if((!keyword || keyword=='szukaj produktu...') && select1=='' && select2=='' && select3=='' && select4=='')
	{
		
		alert("Wpisz słowo do wyszukania lub wybierz wartość!");
		d.f_keyword.focus();
		return false;

	}

	if(keyword=='szukaj produktu...') d.f_keyword.value="";
	//document.searchform.submit();
	return true;
}

function releaseSearchForm()
{
	
	var finalcounter=document.getElementById("final_counter").value*1;
	if(!finalcounter) getPromptLink();
	var finalcounter=document.getElementById("final_counter").value*1;

	if(!finalcounter)
	{
		
		var d=document.searchform;
		var index1=d.f_feature_1.selectedIndex;
		var index2=d.f_feature_2.selectedIndex;
		var index3=d.f_feature_3.selectedIndex;
		var index4=d.f_feature_4.selectedIndex;

		var select1=d.f_feature_1.options[index1].value;
		var select2=d.f_feature_2.options[index2].value;
		var select3=d.f_feature_3.options[index3].value;
		var select4=d.f_feature_4.options[index4].value;

		var keyword=trim(d.f_keyword.value);

		if((!keyword || keyword=='szukaj produktu...') && select1=='' && select2=='' && select3=='' && select4=='')
		{
			alert("Wpisz słowo do wyszukania lub wybierz wartość!");
			d.f_keyword.focus();
		}
		else
		{
			if(keyword=='szukaj produktu...') d.f_keyword.value="";
			//document.searchform.action=document.searchform.copy_action.value;
			document.searchform.submit();
		}
	}
	else
	{
		// advanced searching
		var f=document.getElementById("final_counter").value;
		if(f)
		{
			// take also additional features
			var feature2=document.getElementById("prompt_2").value;
			var feature3=document.getElementById("prompt_3").value;
			var linknow=document.getElementById("prompt_link").value;
			
			if(feature2) document.promptform.forceFeature2.value=feature2;
			if(feature3) document.promptform.forceFeature3.value=feature3;
			document.promptform.action=linknow;
			document.promptform.submit();
		}
	}
}

function reloadOptions(msg, lista, elId,  selectedValue)
{

	var selectionExists=0;

	for(i=0;i<msg.length;i++)
	{	
		var data=msg[i];
		if(data.indexOf("{nazwa}")!=-1)
		{
			var text=data.replace("{nazwa}","");
			lista.options[i]=new Option("- "+text+" -", "", true, false);
		}
		else 
		{
			var selection=false;

			var text=data.split("||");
			if(data==selectedValue)
			{
				var selection=true;
				selectionExists=i;
			}

			if(msg.length==2)
			{
				var selection=true;
				selectionExists=i;
			}

		    if(text[1])	lista.options[i]=new Option(text[1], data, true, selection);
		}
	}
	
	lista.selectedIndex=selectionExists;
}

// reload top searching features depending on category select (main categories)
function reloadTopSeaarchingFeatures(dostawca_id)
{
	var index=document.getElementById("topsearchcategory").selectedIndex;
	var category_id=document.getElementById("topsearchcategory").options[index].value;
	reloadFeatures('f_feature_1', dostawca_id, category_id);
	reloadFeatures('f_feature_2', dostawca_id, category_id);
	reloadFeatures('f_feature_3', dostawca_id, category_id);
	reloadFeatures('f_feature_4', dostawca_id, category_id);
}

// reload top searching features
function reloadFeatures(elementId, dostawca_id, category_id)
{

	var index=document.getElementById(elementId).selectedIndex;
	var value=document.getElementById(elementId).options[index].value;
	
	var sel_index_1=document.getElementById("f_feature_1").selectedIndex;
	var sel_val_1=document.getElementById("f_feature_1").options[sel_index_1].value;

	var sel_index_2=document.getElementById("f_feature_2").selectedIndex;
	var sel_val_2=document.getElementById("f_feature_2").options[sel_index_2].value;

	var sel_index_3=document.getElementById("f_feature_3").selectedIndex;
	var sel_val_3=document.getElementById("f_feature_3").options[sel_index_3].value;

	var sel_index_4=document.getElementById("f_feature_4").selectedIndex;
	var sel_val_4=document.getElementById("f_feature_4").options[sel_index_4].value;

	//alert( sel_val_1);
	//if(value!="" && value!=0 && value!="||")
	//{
		if(elementId!="f_feature_1")
		{
			
				columnList=columnListTopSearching[1];
				$.ajax({
				   type: "POST",
				   url:	"/ajax/manage_filter.php",
				   data: "action=reloadSelects&value="+value+"&columnList="+columnList+"&dostawca_id="+dostawca_id+"&category_id="+category_id+"&sel_val_2="+sel_val_2+"&sel_val_3="+sel_val_3+"&sel_val_4="+sel_val_4,

					success: function(msg)
					{
						
						msg=msg.split("*");

						var lista=document.getElementById("f_feature_1");
						var index=lista.selectedIndex;
						var selectedValue=lista.options[index].value;
						lista.options.length=0;
						reloadOptions(msg, lista, "f_feature_1",selectedValue );
					}
				});
			
		}

		if(elementId!="f_feature_2")
		{

			
				columnList=columnListTopSearching[2];
				$.ajax({
				   type: "POST",
				   url:	"/ajax/manage_filter.php",
				   data: "action=reloadSelects&value="+value+"&columnList="+columnList+"&dostawca_id="+dostawca_id+"&category_id="+category_id+"&sel_val_1="+sel_val_1+"&sel_val_3="+sel_val_3+"&sel_val_4="+sel_val_4,
					success: function(msg)
					{
						
						msg=msg.split("*");

						var lista=document.getElementById("f_feature_2");
						var index=lista.selectedIndex;
						var selectedValue=lista.options[index].value;
						lista.options.length=0;
						reloadOptions(msg, lista, "f_feature_2",selectedValue);
					}
				});
			
		}
	
		if(elementId!="f_feature_3")
		{

			
				columnList=columnListTopSearching[3];
				$.ajax({
				   type: "POST",
				   url:	"/ajax/manage_filter.php",
				   data: "action=reloadSelects&value="+value+"&columnList="+columnList+"&dostawca_id="+dostawca_id+"&category_id="+category_id+"&sel_val_1="+sel_val_1+"&sel_val_2="+sel_val_2+"&sel_val_4="+sel_val_4,
					success: function(msg)
					{
						
						msg=msg.split("*");

						var lista=document.getElementById("f_feature_3");
						var index=lista.selectedIndex;
						var selectedValue=lista.options[index].value;
						lista.options.length=0;
						reloadOptions(msg, lista, "f_feature_3",selectedValue);
					}
				});
			
		}
		
		if(elementId!="f_feature_4")
		{
			
				columnList=columnListTopSearching[4];
				$.ajax({
				   type: "POST",
				   url:	"/ajax/manage_filter.php",
				   data: "action=reloadSelects&value="+value+"&columnList="+columnList+"&dostawca_id="+dostawca_id+"&category_id="+category_id+"&sel_val_1="+sel_val_1+"&sel_val_2="+sel_val_2+"&sel_val_3="+sel_val_3,
					success: function(msg)
					{
						
						msg=msg.split("*");

						var lista=document.getElementById("f_feature_4");
						var index=lista.selectedIndex;
						var selectedValue=lista.options[index].value;	
						lista.options.length=0;
						reloadOptions(msg, lista, "f_feature_4", selectedValue);	
					}
				});
			
		}

	//}
}


function getPromptOptions(evt)
{
	
	window.clearInterval(promptInterval);

	evt = (evt) ? evt : ((window.event) ? event : null);
	if(evt)
	{

			if(evt.keyCode==37) // LEFT
			{
            }    

			else if(evt.keyCode==38) // UP
			{    
				var position=document.getElementById("prompt_counter").value*1;
				if(!position) var position=0; 
				var nextElement=position-1;				
				var previousElement=position;

				if(document.getElementById("prompt_element_"+nextElement))
				{
					if(document.getElementById("prompt_element_"+previousElement)) document.getElementById("prompt_element_"+previousElement).className='prompt_out';

					document.getElementById("prompt_element_"+nextElement).className='prompt_over';
					document.getElementById("prompt_counter").value=nextElement;

					if(nextElement>8)
					{
						document.getElementById("prompt_element_"+nextElement).focus();
						document.getElementById("searchfield").focus();
						
					}
					
					if(document.getElementById("searching_prompt").scrollTop>0)
					{
						var newscrollTop= document.getElementById("searching_prompt").scrollTop-18;
						if(newscrollTop<0) newscrollTop=0;
						document.getElementById("searching_prompt").scrollTop=newscrollTop;
					}
				}
			}

			else if(evt.keyCode==39) // right	
			{
            }   

			else if(evt.keyCode==40) // down
			{
                var position=document.getElementById("prompt_counter").value*1;
				if(!position) var position=0; 
				var nextElement=position+1;				
				var previousElement=position;

				if(document.getElementById("prompt_element_"+nextElement))
				{
					if(document.getElementById("prompt_element_"+previousElement)) document.getElementById("prompt_element_"+previousElement).className='prompt_out';

					document.getElementById("prompt_element_"+nextElement).className='prompt_over';
					document.getElementById("prompt_counter").value=nextElement;
					
					if(nextElement>8)
					{
						document.getElementById("prompt_element_"+nextElement).focus();
						document.getElementById("searchfield").focus();
					}
				}

			}  
			
			else if(evt.keyCode==13) // enter
			{
		
				var finalcounter=document.getElementById("final_counter").value*1;
				if(!finalcounter)
				{
					getPromptLink();
					var finalcounter=document.getElementById("final_counter").value*1;
					if(!finalcounter)
					{
						
						var txt=trim(document.getElementById("searchfield").value);
						
						if(!txt) alert("Wprowadź słowo do wyszukania!");
					
						else if(txt.length<2) alert("Wprowadź przynajmniej dwa znaki w słowie do wyszukania!");
					
						else // common searching
						{
							document.searchform.submit();
						}
					}
				}
				else
				{
					// advanced searching
					var f=document.getElementById("final_counter").value;
					if(f)
					{
						// take also additional features
						var feature2=document.getElementById("prompt_2").value;
						var feature3=document.getElementById("prompt_3").value;
						var linknow=document.getElementById("prompt_link").value;
						
						if(feature2) document.promptform.forceFeature2.value=feature2;
						if(feature3) document.promptform.forceFeature3.value=feature3;
						document.promptform.action=linknow;
						document.promptform.submit();
					}
				}
			}

			else // any other sign so reset setting
			{
				document.getElementById("final_counter").value=0;
				var txt=trim(document.getElementById("searchfield").value);
				if(txt.length>1 && evt.keyCode!=13)
				{
					promptInterval=window.setInterval("reloadPromptOptions()",500);
				}
			}
         
	}
}

function getPromptLink()
{
	
	var position=document.getElementById("prompt_counter").value*1;

	if(position)
	{
		if(document.getElementById("prompt_text_"+position))
		{
			var text=document.getElementById("prompt_text_"+position).value;
			document.getElementById("searchfield").value=text;
			document.getElementById("searchfield").focus();
			
			document.getElementById("prompt_link").value=document.getElementById("prompt_link_"+position).value;

			document.getElementById("prompt_2").value=document.getElementById("prompt_2_"+position).value;
			
			document.getElementById("prompt_3").value=document.getElementById("prompt_3_"+position).value;

			document.getElementById("searching_prompt").style.display="none";
			document.getElementById("searching_prompt").innerHTML="";
			document.getElementById("final_counter").value=position;
		}
	}

	window.clearInterval(promptInterval);
	promptInterval="";
	

	/*var rememberAction=document.searchform.action;
	document.searchform.action="";
	var position=document.getElementById("prompt_counter").value*1;
	if(position)
	{
		document.getElementById("prompt_element_"+position).onclick=true;
	}
	else document.location.href=rememberAction;
	*/
}

function checkLoginForm()
{
	var d=document.logingform;
	
	if(trim(d.email.value)=="" || trim(d.email.value)=="email")
	{
		alert("Wprowadź adres email!");
		d.email.focus();
		d.email.value="";
		return false;
	}

	if(trim(d.password.value)=="" || trim(d.password.value)=="hasło")
	{
		alert("Wprowadź hasło!");
		d.password.focus();
		d.password.value="";
		return false;
	}

	var email=trim(d.email.value);
	var expr=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
	var result=expr.test(email);
	
	if(!result)
	{
		alert("Wprowadź poprawny adres email!");
		d.email.focus();
		return false;
	}

	return true;

}

function checkEmail(el)
{
	
	if (document.getElementById(el.id).value=="email")
	{
		document.getElementById(el.id).value="";
	}
	else if (document.getElementById(el.id).value=="")
	{
		document.getElementById(el.id).value="email";
	}
}

function changeImage(imagename, counter, element)
{
	if(document.getElementById("image_"+counter))
	{
		var minisrc="img_categories/mini/"+imagename;
		document.getElementById("image_"+counter).src=minisrc;
		document.getElementById("image_"+counter).title=element.title;

		//document.getElementById("image_"+counter).onclick="reloadLink("+element.href+")";

	}

}
function reloadLink(link)
{
	alert(link);
}
function checkAllFeaturesForm()
{
	//alert("w budowie!");
	return true;
}

function checkNoProductsForm()
{

	var d=document.beheerform;
	
	if(trim(d.f_name.value)=='')
	{
		alert("Wprowadź imię i nazwisko osoby");
		d.f_name.focus();

		return false;
	}
	
	if(trim(d.f_phone.value)=='')
	{
		alert("Wprowadź numer telefonu");
		d.f_phone.focus();
		return false;
	}

	if(trim(d.f_email.value)=='')
	{
		alert("Wprowadź email");
		d.f_email.focus();
		return false;
	}
	
	var email=trim(d.f_email.value);
	var expr=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
	var result=expr.test(email);
	
	if(!result)
	{
		alert("Wprowadź poprawny adres email!");
		d.f_email.focus();
		return false;
	}

	if(trim(d.f_msg.value)=='')
	{
		alert("Wprowadź treść wiadomości!");
		d.f_msg.focus();
		return false;
	}

	if(d.verificationCode) 
	{
		if(trim(d.verificationCode.value)=='')
		{
			alert("Przepisz kod!");
			d.verificationCode.focus();
			return false;
		}
	}

	return true;
}

function refreshCurrentRow(currentActiveRow)
{
	//alert(currentActiveRow);
	if(currentActiveRow)
	{
		
		for(i=1;i<currentActiveRow;i++)
		{
			nextList();
		}
	}
}

function reloadCategoriesList(element)
{
	var did=element.options[element.selectedIndex].value;
	var link=linkprefix+"/kategorie";
	if(did) link+="/?f_distributor="+did;
	document.location.href=link;
}

function confLogOut()
{
	if(confirm("Czy na pewno chcesz się wylogować?")) {
			$.ajax({type: "POST",
					url: "/ajax/manage_basket.php",
					data: "action=deleteAll",
					success: function(){ document.location.href=linkprefix+"/wyloguj";}
					});
	}
}

function rewritePriceVariations(selectnr)
{
	var id="units"+selectnr;
	if(document.getElementById(id))
	{
		var index=document.getElementById(id).selectedIndex;

		document.getElementById("variation_form_"+selectnr).innerHTML=document.getElementById("vf_hidden_"+selectnr+"_"+index).value;
		document.getElementById("variation_shipment_"+selectnr).innerHTML=document.getElementById("vs_hidden_"+selectnr+"_"+index).value;
		document.getElementById("variation_price_"+selectnr).innerHTML=document.getElementById("vp_hidden_"+selectnr+"_"+index).value;
		
		recountPriceVariations(selectnr);
	}
}

function recountPriceVariations(selectnr)
{
	var id="quantity"+selectnr;
	if(document.getElementById(id))
	{
		var quantity=document.getElementById(id).value;
		quantity=quantity.replace(",",".");
		quantity*=1;

		if(quantity)
		{
			var id="units"+selectnr;
			var index=document.getElementById(id).selectedIndex;
			var price=document.getElementById("vp_pure_hidden_"+selectnr+"_"+index).value;
			var currency=document.getElementById("vc_hidden_"+selectnr+"_"+index).value;
	
			price=price.replace(",",".");
			price*=quantity;
			
			price=number_format(price, 2, ',' , ' ', '^');
			document.getElementById("variation_price_recount_"+selectnr).innerHTML=price+" "+currency;

		}
	}
}

function changePriceVariationProductList(selectnr)
{
	var id="units"+selectnr;
	var index=document.getElementById(id).selectedIndex;
	var priceVariation=document.getElementById("pricevariation_"+selectnr+"_"+index).value;
	document.getElementById("purchasingInfo"+selectnr).innerHTML=priceVariation;
	var inputObj = $("#quantity"+selectnr);
	inputObj.val(0);
	costCountProdList(inputObj);
}

function delDistributorFilter(did)
{
	document.location.href=linkprefix+"/filtr/wyczysc";
}

function getAutoComplete()
{
	var val=document.getElementById("searchfield").value;
	window.clearInterval(promptInterval);
	if(trim(val))
	{
		promptInterval=window.setInterval("getAutoCompleteGo()",500);
	}
}

function getAutoCompleteGo()
{
	var val=document.getElementById("searchfield").value;
	window.clearInterval(promptInterval);
	
	$.ajax({
	   type: "POST",
	   url:	"layout/ajax/autoCompleteTopSearching.php",
	   data: "keyword="+val,
	  
		success: function(msg)
		{
			//alert(msg);
		}
	});
}
