var currentdiv="";
var openedHelp=0;

/************************* 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 reloadYears(brandid)
{
	
	if(!brandid)
	{

		var el=document.getElementById("key_type");
		el.options.length=0;
		el.options[0]=new Option("- wybierz rocznik -", "0", true, false);

		if(document.getElementById("key_model"))
		{
			var el=document.getElementById("key_model");
			el.options.length=0;
			el.options[0]=new Option("- wybierz rocznik -", "0", true, false);
		}

		return;
	}

}

function reloadBrands(veh)
{
	

	if(document.getElementById("key_marka"))
	{	
		var el=document.getElementById("key_marka");
		el.options.length=0;
		el.options[0]=new Option("- wybierz rodzaj -", "0", true, false);
	}

	if(document.getElementById("key_model"))
	{	
		var el=document.getElementById("key_model");
		el.options.length=0;
		el.options[0]=new Option("- wybierz rocznik -", "0", true, false);
	}

	if(document.getElementById("key_prodyearfrom"))
	{
		var el=document.getElementById("key_prodyearfrom");
		el.options.length=0;
		el.options[0]=new Option("- wybierz markę -", "0", true, false);
	}

	if(document.getElementById("key_marka"))
	{
		
		showDataLoader();

		$.ajax({
		   
		   type: "POST",
		  
		   url:	"/ajax/get_brands_by_vehicle.php",
		   
		   data: "vehicle="+veh,
		   
		   success: function(msg)
			{
				
				hideDataLoader();

				if(msg)
				{
					var results=msg;
					results=results.split("@|@");
					
					var el=document.getElementById("key_marka");
					el.options.length=0;
					el.options[0]=new Option("- wybierz markę -", "0", true, false);
					
					for(i=0;i<results.length;i++)
					{
						var k=i+1;
						var data=results[i];
						data=data.split("|");
						var idnow=data[0];
						var namenow=data[1];
						el.options[k]=new Option(namenow, idnow, true, false);
					}
				}
				else
				{
					var el=document.getElementById("key_marka");
					el.options.length=0;
					el.options[0]=new Option("- nie znaleziono powiązania -", "0", true, false);
				}
		   }
		 });


	}
}

function reloadYearsAndModels(brandid)
{
	
	if(!document.getElementById("key_prodyearfrom")) return;

	if(document.getElementById("key_model"))
	{
		var el=document.getElementById("key_model");
		el.options.length=0;
		el.options[0]=new Option("- wybierz rocznik -", "0", true, false);
	}

	if(!brandid)
	{
		var el=document.getElementById("key_prodyearfrom");
		el.options.length=0;
		el.options[0]=new Option("- wybierz markę -", "0", true, false);

		return;
	}
	
	if(document.getElementById("key_prodyearfrom"))
	{

		showDataLoader();

		$.ajax({
		   
		   type: "POST",
		  
		   url:	"/ajax/get_years_by_brandid.php",
		   
		   data: "brandid="+brandid,
		   
		   success: function(msg)
			{
			
				hideDataLoader();
				var results=msg;
				results=results.split("|");
				
				var el=document.getElementById("key_prodyearfrom");
				el.options.length=0;
				el.options[0]=new Option("- wybierz rocznik -", "0", true, false);
				
				for(i=0;i<results.length;i++)
				{
					var k=i+1;
					el.options[k]=new Option(results[i], results[i], true, false);
				}
		   }
		 });
	}
	
}

function reloadYears4front(brandid)
{
	
	if(!brandid)
	{
		var el=document.getElementById("key_year");
		el.options.length=0;
		el.options[0]=new Option("- wybierz markę -", "0", true, false);

		return;
	}
	
	if(document.getElementById("key_year"))
	{
		$.ajax({
		   
		   type: "POST",
		  
		   url:	"/ajax/get_years_by_brandid.php",
		   
		   data: "brandid="+brandid,
		   
		   success: function(msg)
			{
				
	 
				var results=msg;
				results=results.split("|");
				
				var el=document.getElementById("key_year");
				el.options.length=0;
				el.options[0]=new Option("- wybierz rocznik -", "0", true, false);
				
				for(i=0;i<results.length;i++)
				{
					var k=i+1;
					el.options[k]=new Option(results[i], results[i], true, false);
				}
		   }
		 });
	}
}

function reloadModels()
{
	
	var brandindex=document.getElementById("key_marka").selectedIndex;
	var brandid=document.getElementById("key_marka").options[brandindex].value;

	var modelsindex=document.getElementById("key_prodyearfrom").selectedIndex;
	var modelsyear=document.getElementById("key_prodyearfrom").options[modelsindex].value;	
	
	if(modelsindex<1)
	{
	
		var el=document.getElementById("key_model");
		el.options.length=0;
		el.options[0]=new Option("- wybierz rocznik -", "0", true, false);
		return;
	}

	if(document.getElementById("key_model"))
	{
	
	showDataLoader();

	$.ajax({
		   
		   type: "POST",
		  
		   url:	"/ajax/get_model_by_brandid.php",
		   
		   data: "brandid="+brandid+"&modelsyear="+modelsyear,
		   
		   success: function(msg)
			{
				hideDataLoader();
				var results=msg;
				results=results.split("|");
				
				var el=document.getElementById("key_model");
				el.options.length=0;
				el.options[0]=new Option("- wybierz model -", "0", true, false);
				
				for(i=0;i<results.length;i++)
				{
					var k=i+1;
					el.options[k]=new Option(results[i], results[i], true, false);
				}
		   }
		 });
	}

}

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=='deletemodels')
		{
			if(confirm("Czy na pewno chcesz usunąć wybrane modele oraz ich powiązania z częściami?"))
			{
				d.a.value=action;
				d.submit();
			}
		}
		
		else 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ąć tę część?";
			else if(checkedCounter>1) var deltext="Czy na pewno chcesz usunąć "+checkedCounter+" części?";

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

		else if(action=='delassociation')
		{
			if(confirm("Czy na pewno chcesz usunąć powiązania dla wybranych części?"))
			{
				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=10;
	
	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 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ąć tę część?")) 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 confModelDel(id)
{
	if(confirm("Czy na pewno chcesz usunąć ten model?")) document.location.href="management.php?s=models&a=deletemodels&idslist="+id;
}

function confAssociatedDel(id)
{
	if(confirm("Czy na pewno chcesz usunąć powiązania dla tej części?")) 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 changeDeliveryForAddingOrder(deliveryid)
{
	
 
	$.ajax({
		   
		   type: "POST",
		  
		   url: "/ajax/admin_product2order.php",
		   
		   data: "deliveryid="+deliveryid+"&action=changedelivery",
		   
		   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 addProduct2basket(pid, 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];
		
		//alert("Produkt dodany do koszyka");

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

function confDelBasket()
{

	if(confirm("Czy na pewno chcesz wyczyścić zawartość koszyka?"))
	{	
		var link=linkprefix+",,,,,deletebasket";
		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 chooseManuallyClientForOrder(element)
{

	clearTimeout(intervalid);

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

}

function updateManuallyClientForOrder(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_client2order.php",
		   
		   data: "cid="+element.value,
		   
		   success: function(msg)
			{
				
				if(msg=='-1')
				{
					alert("Nie znaleziono klienta o podanym numerze ID");
					document.beheerform.f_companyname.value="";
					document.beheerform.f_name.value="";
					document.beheerform.f_nip.value="";
					document.beheerform.f_street.value="";
					document.beheerform.f_city.value="";
					document.beheerform.f_zipcode.value="";
					document.beheerform.f_post.value="";
					document.beheerform.f_email.value="";
					document.beheerform.f_phone.value="";
					document.beheerform.f_partner.selectedIndex=0;
					
					document.beheerform.f_pricegroup.selectedIndex=0;
					document.beheerform.f_pricegroup.disabled=true;

					element.focus();
				}
				else
				{
					msg=msg.split("{|}");

					document.beheerform.f_companyname.value="";
					document.beheerform.f_name.value="";
					document.beheerform.f_nip.value="";
					document.beheerform.f_street.value="";
					document.beheerform.f_city.value="";
					document.beheerform.f_zipcode.value="";
					document.beheerform.f_post.value="";
					document.beheerform.f_email.value="";
					document.beheerform.f_phone.value="";
					document.beheerform.f_partner.selectedIndex=0;
					
					document.beheerform.f_pricegroup.selectedIndex=0;
					document.beheerform.f_pricegroup.disabled=true;
					
					//document.beheerform.f_clientid.value="<?=$cid?>";
					document.beheerform.f_companyname.value=msg[0];
					document.beheerform.f_name.value=msg[1];
					document.beheerform.f_nip.value=msg[2];
					document.beheerform.f_street.value=msg[3];
					document.beheerform.f_city.value=msg[4];
					document.beheerform.f_zipcode.value=msg[5];
					document.beheerform.f_post.value=msg[6];
					document.beheerform.f_partner.value=msg[7];
					
					if(msg[8])
					{
						document.beheerform.f_pricegroup.value=msg[8];
						document.beheerform.f_pricegroup.disabled=false;
					}

					document.beheerform.f_email.value=msg[9];
					document.beheerform.f_phone.value=msg[10];

				}
		   }
		 });


	}
}

function check_emailform()
{
	
	var d=document.emailform;
	
	hideNotificationDiv();

	if(!trim(d.f_mail_to.value))
	{
		alert("Podaj adres email odbiorcy");
		d.f_mail_to.focus();
		return false;
	}

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

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

	}

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

	}
	
	if(!trim(d.f_mail_subject.value))
	{
		
		alert("Wpisz temat wiadomości");
		d.f_mail_subject.focus();
		return false;

	}

	if(!trim(d.f_mail_message.value))
	{
		
		alert("Wpisz treść wiadomości");
		d.f_mail_message.focus();
		return false;

	}

	return true;
}

function generateFV(oid)
{
	popUp("generate_fv.php?oid="+oid,"FAKTURA",'812','500',1);
}

function printoutFV(oid)
{
	
	popUp(server+"/cms/printout_fv.php?oid="+oid,"FAKTURA",'812','500',1);
}

function displayFV(oid)
{
	alert("funkcja w budowie");
}

function printOutFV()
{
	document.getElementById('divoptionsFV').style.display='none';
	window.print();
	//document.getElementById('divoptionsFV').style.display='block';
}

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

}

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 confDeleteFV(oid)
{
	if(confirm("Czy na pewno chcesz usunąć fakturę FV dla tego zamówienia?")) document.location.href="management.php?s=orders&a=deleteFV&oid="+oid;
}

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.toLowerCase();
	return str;
}

function checkBasketForm()
{
	
	var d=document.basketform;
	
	var iserror=false;
	var ispayment=false;
	var isdelivery=false;

	for(i=0;i<d.elements.length;i++)
	{
		var name=d.elements[i].name;
		var val=trim(d.elements[i].value);
		var type=d.elements[i].type;
		
		if(type=='text' && name.indexOf("product_amount")!=-1)
		{
			
			if(!is_number(val) || trim(val)=='' || trim(val)==0)
			{
				alert("Wprowadź liczbę całkowitą większą od zera!");
				d.elements[i].focus();
				iserror=true;
			}

		}

		if(type=='radio' && name=='payment' && d.elements[i].checked) var ispayment=true;
		if(type=='radio' && name=='delivery' && d.elements[i].checked) var isdelivery=true;
	
	
	}
	
	if(!ispayment)
	{
		
		alert("Wybierz sposób płatności");
		iserror=true;

	}
	
	if(!isdelivery)
	{
		
		alert("Wybierz sposób wysyłki");
		iserror=true;

	}

	if(!iserror) document.basketform.submit();

}

function updatePaymentForBasket(element, sum)
{
	
	var payment=element.value;
	sum=sum*1;
	
	var delivery="";
	for(i=0;i<document.basketform.elements.length;i++)
	{
		
		var d=document.basketform;
		if (d.elements[i].type=='radio' && d.elements[i].name=='delivery' && d.elements[i].checked)
		{
			delivery=d.elements[i].value;
			break;
		}
	}

	reloadBasket(payment, delivery, sum);

}

function updateDeliveryForBasket(element, sum)
{
	
	var delivery=element.value;
	sum=sum*1;

	var payment="";
	for(i=0;i<document.basketform.elements.length;i++)
	{
		
		var d=document.basketform;
		if (d.elements[i].type=='radio' && d.elements[i].name=='payment' && d.elements[i].checked)
		{
			payment=d.elements[i].value;
			break;
		}
	}

	reloadBasket(payment, delivery, sum);

}

// reload price below in basket as well as 
function reloadBasket(payment, delivery, sum)
{

	//alert("pay: "+payment+", del: "+delivery);
 	$.ajax({
	type: "POST",
	url: "/ajax/manage_basket.php",
	data: "action=&payment="+escape(payment)+"&delivery="+escape(delivery)+"&sum="+escape(sum),
   
	success: function(msg)
	{

		msg=trim(msg);
		 
		if(msg)
		{
			
			if(document.getElementById("basketProductsSum")) document.getElementById("basketProductsSum").innerHTML=msg;

			if(document.getElementById("bottomBasketSum")) document.getElementById("bottomBasketSum").innerHTML=msg;

		}
	}

	});
}

function changeAmountForBasket(elementid, pid)
{
	
	var val=trim(document.getElementById(elementid).value);
	
	if(!is_number(val) || trim(val)=='' || trim(val)==0)
	{
		alert("Wprowadź liczbę całkowitą większą od zera!");
		document.getElementById(elementid).focus();
	}

	else
	{

		$.ajax({
		type: "POST",
		url: "/ajax/manage_basket.php",
		data: "action=changeamount&pid="+pid+"&amount="+val,
	   
		success: function(msg)
		{
			document.location.replace(linkprefix+",,,,,koszyk");
		}

		});
	
	}

}

function deleteProductForBasket(pid)
{
	
	if(confirm("Czy chcesz usunąć ten produkt z koszyka?"))
	{
		
		$.ajax({
		type: "POST",
		url: "/ajax/manage_basket.php",
		data: "action=delete&pid="+pid,
	   
		success: function(msg)
		{
			document.location.replace(linkprefix+",,,,,koszyk");
		}
		});


	}
}

function makeLink(link)
{
	return link;
}

function showDataLoader()
{
	
	if (browser.isIE) {
		//var y =document.body.scrollTop; // nowszy IE?
		var y =document.documentElement.scrollTop; // stary IE
	  }
	  
	 else { // if (browser.isNS)
		var y = window.scrollY;
	  }

	if(document.getElementById('dataLoader')) document.getElementById('dataLoader').style.top=220+y+"px";

	if(document.getElementById('dataLoader')) document.getElementById('dataLoader').style.display='block';

}

function hideDataLoader()
{
	if(document.getElementById('dataLoader')) document.getElementById('dataLoader').style.display='none';
}