var xmlHttp = createXmlHttpRequest();
var textarea_max_motto = 105;
var current_id = "";
var cache = new Array();

Math.decimal = function(n, k)
{ 
	var factor = Math.pow(10, k+1); 
	n = Math.round(Math.round(n*factor)/10); 
	return n/(factor/10); 
} 

function createXmlHttpRequest()
{
	var  xmlHttp;
	try
	{
		xmlHttp = new XMLHttpRequest();
	}
	catch(e)
	{
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP");
		for(var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
		{
			try
			{
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			}
			catch(e){}
		}
	}
	if(!xmlHttp)
		alert("Error AJAX");
	else
		return xmlHttp;
}

function createAjaxString(params)
{
	cache.push(params);
}

function sendAjaxRequest(responseFunction)
{
	if(xmlHttp.readyState==4 || xmlHttp.readyState==0)
	{
		var params = "";
		if(cache.length>0)
		{
			params = cache.shift();
			try
			{
				xmlHttp.open("POST","mvc_controller/ajaxcontainer.php",true);
				xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				xmlHttp.setRequestHeader("Content-length", params.length);
				xmlHttp.onreadystatechange = eval(responseFunction);
				xmlHttp.send(params);
			}
			catch(e)
			{
				alert('1 '+e.description);
			}
		}
	}
}


function actualCart()
{
	if(xmlHttp.readyState==4)
	{
		
		if(xmlHttp.status == 200)
		{
			
			var xmlResponse = xmlHttp.responseXML;
		   	xmlRoot = xmlResponse.documentElement;
		   	currencyArray = xmlRoot.getElementsByTagName("currency");
		   	sumArray = xmlRoot.getElementsByTagName("sumcart");
			sumnetArray = xmlRoot.getElementsByTagName("sumcartnet");
			oprArray = xmlRoot.getElementsByTagName("countcart");
			lastaddArray = xmlRoot.getElementsByTagName("lastadded");
			productIdArray = xmlRoot.getElementsByTagName("articleid");
			infoAddArray = xmlRoot.getElementsByTagName("infoadd");
			
			currency=currencyArray.item(0).firstChild.data;
			sum=sumArray.item(0).firstChild.data;
			sumnet=sumnetArray.item(0).firstChild.data;
			count=oprArray.item(0).firstChild.data;
			lastadd=lastaddArray.item(0).firstChild.data;
			productId=productIdArray.item(0).firstChild.data;
			infoAdd=infoAddArray.item(0).firstChild.data;
			document.getElementById("cartquantity").innerHTML="ilo¶ć szt: "+count;
			document.getElementById("cartdetails_net").innerHTML="netto: "+sumnet+" "+currency;
			document.getElementById("cartdetails").innerHTML="kwota: "+sum+" "+currency;
			document.getElementById("cartlastadd").innerHTML="<span style=\"font-size:10px;font-weight:none;\"><p><b>Ostatnio dodano:</b><br>"+lastadd+"</p></span>";

			//if(document.getElementById("prdetail_preloader")) document.getElementById("prdetail_preloader").innerHTML="";
			//if(document.getElementById("prsmalltab_dodano"+productId)) document.getElementById("prsmalltab_dodano"+productId).innerHTML=infoAdd;
			showPreloader(productId,0);
			sendAjaxRequest("actualCart");
		}
		else
			alert("Operacja mogłą się nie udać. Powtórz operację.");
	}
}

function actualCart2()
{
	if(xmlHttp.readyState==4)
	{
		if(xmlHttp.status == 200)
		{
			var xmlResponse = xmlHttp.responseXML;
			xmlRoot = xmlResponse.documentElement;
			summaryArray = xmlRoot.getElementsByTagName("productItem");
			currencyArray = xmlRoot.getElementsByTagName("currency");
			countcartArray = xmlRoot.getElementsByTagName("countcart");
			sumtaxArray = xmlRoot.getElementsByTagName("sumtax");
			sumArray = xmlRoot.getElementsByTagName("sumcart");
			sumnetArray = xmlRoot.getElementsByTagName("sumcartnet");
			raw_sumArray = xmlRoot.getElementsByTagName("rawsumcart");
			raw_sumnetArray = xmlRoot.getElementsByTagName("rawsumcartnet");
			shippingArray = xmlRoot.getElementsByTagName("shipping");
			shippinggrossArray = xmlRoot.getElementsByTagName("shippinggross");
			minimalpriceArray = xmlRoot.getElementsByTagName("minimalprice");
			percentoforderArray = xmlRoot.getElementsByTagName("percentoforder");
			zero_infoArray = xmlRoot.getElementsByTagName("zero_info");
			shippinggroupinfoArray = xmlRoot.getElementsByTagName("shippinggroupinfo");
			
			shippinggroupinfo = shippinggroupinfoArray.item(0).firstChild.data;
			zero_info = zero_infoArray.item(0).firstChild.data;
			minimalprice=minimalpriceArray.item(0).firstChild.data;
			percentoforder=percentoforderArray.item(0).firstChild.data;
			currency=currencyArray.item(0).firstChild.data;
			count=countcartArray.item(0).firstChild.data;
			sumtax=sumtaxArray.item(0).firstChild.data;
			sum=sumArray.item(0).firstChild.data;
			sumnet=sumnetArray.item(0).firstChild.data;
			raw_sum=raw_sumArray.item(0).firstChild.data;
			raw_sumnet=raw_sumnetArray.item(0).firstChild.data;
			shipping=shippingArray.item(0).firstChild.data;
			shippinggross=shippinggrossArray.item(0).firstChild.data;
		
			t=document.getElementById('tabcart');
			cols = eval(t.rows[0].cells.length-4);
			row_count=t.rows.length;
			
			while(t.rows.length)        
			      t.deleteRow(t.rows.length-1);
			
//			for(i=0;i<row_count;i++)
	//			t.deleteRow();

			var mode_function = new Array();
			for(i=0;i<summaryArray.length;i++)
			{
				summary=summaryArray.item(i).firstChild.data;
				mode_function[0]=summary;
				mode_function[1]=summaryArray.item(i).getAttribute("quant");
				mode_function[2]=summaryArray.item(i).getAttribute("jm");
				mode_function[3]=summaryArray.item(i).getAttribute("price_net");
				mode_function[4]=summaryArray.item(i).getAttribute("amount_net");
				mode_function[5]=summaryArray.item(i).getAttribute("vat");
				mode_function[6]=summaryArray.item(i).getAttribute("tax");
				mode_function[7]=summaryArray.item(i).getAttribute("amount_gross");
				mode_function[8]=summaryArray.item(i).getAttribute("id");
				mode_function[9]=summaryArray.item(i).getAttribute("pses");
				mode_function[10]=summaryArray.item(i).getAttribute("hardcode");
				mode_function[11]=summaryArray.item(i).getAttribute("img");
				mode_function[12]=summaryArray.item(i).getAttribute("imglength");
				
				var IE = document.all ? true : false;
				if(!IE)
					nr = t.appendChild(document.createElement("TR"));
				else
					nr=t.insertRow();
				
				row_count=eval(row_count+1);
				t.recordNumber=row_count;
				
				for(j=1;j<=cols;j++)
				{
				  //x=nr.insertCell();
				  x=nr.appendChild(document.createElement("TD"));
				  if(j-1==0)
				  {
					  x.width="250px";
					  x.innerHTML = '<a href="sc.php?part=product&aid='+mode_function[10]+'">'+mode_function[0]+'</a>';//<input id="cnt'+mode_function[8]+'" type="text" value="'+mode_function[j-1]+'">';
				  }
				  else if(j-1==1)
				  {
					  x.width="55px";
					  x.innerHTML = '<img src="'+mode_function[11]+'" '+mode_function[12]+' />';
				  }				  
				  else if(j-1==2)
				  {
					  x.width="34px";
					  x.innerHTML = '<input id="cnt'+mode_function[8]+'" type="text" value="'+mode_function[j-2]+'" />';
				  }
				  else if(j-1==3)
				  {
					  x.width="26px";
					  x.innerHTML = mode_function[2];
				  }
				  else if(j-1==4)
				  {
					  x.width="55px";
					  x.innerHTML = mode_function[3];
				  }
				  else if(j-1==5)
				  {
					  x.width="65px";
					  x.innerHTML = mode_function[4];
				  }
				  else if(j-1==6)
				  {
					  x.width="27px";
					  x.innerHTML = mode_function[5];
				  }
				  else if(j-1==7)
				  {
					  x.width="60px";
					  x.innerHTML = mode_function[6];
				  }
				  else if(j-1==8)
				  {
					  x.width="70px";
					  x.innerHTML = mode_function[7];
				  }
				  else
					  x.innerHTML = mode_function[j-2];
					//  x.insertAdjacentText("beforeEnd",mode_function[j-1]);
				}
				//x=nr.insertCell();
				x=nr.appendChild(document.createElement("TD"));
				x.innerHTML = '<a href="javascript:changeCart(2,2,'+mode_function[8]+',0,1,\''+mode_function[9]+'\')\"><img src="img/plus.gif" border=0></a>';
				//x=nr.insertCell();
				x=nr.appendChild(document.createElement("TD"));
				x.innerHTML = '<a href="javascript:changeCart(2,1,'+mode_function[8]+',0,1,\''+mode_function[9]+'\')\"><img src="img/minus.gif" border=0></a>';
				//x=nr.insertCell();
				x=nr.appendChild(document.createElement("TD"));
				x.innerHTML = '<a href="javascript:changeCart(2,3,'+mode_function[8]+',0,1,\''+mode_function[9]+'\')\"><img src="img/kosz.gif" border=0 alt="Usuń pozycję"></a>';
				//x=nr.insertCell();
				x=nr.appendChild(document.createElement("TD"));
				div="document.getElementById('cnt"+mode_function[8]+"').value";
				x.innerHTML = '<a href="javascript:changeCart(2,4,'+mode_function[8]+',0,'+div+',\''+mode_function[9]+'\')"><img src="img/b_save.gif" alt="PotwierdĽ zmianę"></a>';
			}
			
			document.getElementById("cartquantity").innerHTML="ilo¶ć szt: "+count;
			document.getElementById("cartdetails").innerHTML="kwota: "+sum+" "+currency;
			document.getElementById("gross_summary").innerHTML= sum;
			document.getElementById("net_summary").innerHTML= sumnet;
			document.getElementById("tax_summary").innerHTML= sumtax;
			try
			{
				document.getElementById("shipping_cost_zero").innerHTML = "";
				document.getElementById("shipping_cost").style.visibility = "visible";
				if(zero_info == "true")
				{
					document.getElementById("shipping_cost_zero").innerHTML = shippinggroupinfo;
					document.getElementById("shipping_cost").style.visibility = "hidden";
					document.getElementById("shippingcostzero").value = "true";
				}
				//alert(document.getElementById("shippingcost").value);
				document.getElementById("shipping_gross_main").value = shippinggross;
				payment_cost = 0;
				document.getElementById("sum_gross").value = raw_sum;
				document.getElementById("sum_net").value = raw_sumnet;
				percentoforder = Math.decimal(parseFloat(raw_sum)*parseInt(percentoforder)/100,0);
				if(percentoforder>minimalprice)
					payment_cost = percentoforder;
				else
					payment_cost = minimalprice;
				if(document.getElementById("shippingcost").value==1)
					shippinggross=parseFloat(payment_cost)+parseFloat(shippinggross);
				else
					shippinggross=parseFloat(payment_cost);
				document.getElementById("shipping_gross").value = shippinggross;
				
				document.getElementById("shipping_net").value = shipping;
			}
			catch(e){}
			document.getElementById("shipping_cost").innerHTML="Koszt dostawy z VAT: "+shippinggross+" "+currency;
		}
		else
			alert("Operacja mogłą się nie udać. Powtórz operację.");
	}
}

function getRandomProductListAfter()
{
	if(xmlHttp.readyState==4)
	{
		if(xmlHttp.status == 200)
		{
			var xmlResponse = xmlHttp.responseXML;
			xmlRoot = xmlResponse.documentElement;
			summaryArray = xmlRoot.getElementsByTagName("productItem");

			var random_list = "";
			for(i=0;i<summaryArray.length;i++)
			{
				summary=summaryArray.item(i).firstChild.data;
				pname=summary;
				pprice=summaryArray.item(i).getAttribute("price_gross");
				pid=summaryArray.item(i).getAttribute("id");
				ppicturepath=summaryArray.item(i).getAttribute("picture_path");
				ppicturesize=summaryArray.item(i).getAttribute("picture_size");
				ppicture=summaryArray.item(i).getAttribute("picture");
				full_picture = ppicturepath+ppicture; 
				random_list += '<div class="item_productpromobox"><div class="item_productpromocontent"><div class="item_productpromoimage"><a href="sc.php?part=product&aid='+pid+'"><img src="'+full_picture+'" '+ppicturesize+' /></a></div><div class="item_productpromoname"><a href="sc.php?part=product&aid='+pid+'">'+pname+'</a></div><div class="item_productpromoprice_gross">'+pprice+' zł</div></div></div>';
			}
			document.getElementById("promo_list").innerHTML = random_list;
			setTimeout("getRandomProductList(3,5)",5000);
		}
		else
			alert("Operacja mogłą się nie udać. Powtórz operację.");
	}
}

function sendProductToUserAfter()
{
	if(xmlHttp.readyState==4)
	{
		
		if(xmlHttp.status == 200)
		{
			var xmlResponse = xmlHttp.responseXML;
		   	xmlRoot = xmlResponse.documentElement;
		   	msgArray = xmlRoot.getElementsByTagName("message");
			msg=msgArray.item(0).firstChild.data;
			alert(msg);
			sendAjaxRequest("sendProductToUserAfter");
		}
		else
			alert("Operacja mogłą się nie udać. Powtórz operację.");
	}
}

function sendQueryToSellerAfter()
{
	if(xmlHttp.readyState==4)
	{
		
		if(xmlHttp.status == 200)
		{
			var xmlResponse = xmlHttp.responseXML;
		   	xmlRoot = xmlResponse.documentElement;
		   	msgArray = xmlRoot.getElementsByTagName("message");
			msg=msgArray.item(0).firstChild.data;
			alert(msg);
			sendAjaxRequest("sendQueryToSellerAfter");
		}
		else
			alert("Operacja mogłą się nie udać. Powtórz operację.");
	}
}

function askProductsAfter()
{
	if(xmlHttp.readyState==4)
	{
		if(xmlHttp.status == 200)
		{
			var xmlResponse = xmlHttp.responseXML;
			xmlRoot = xmlResponse.documentElement;
			comArray = xmlRoot.getElementsByTagName("items");
			try
			{
				com=comArray.item(0).firstChild.data;
				document.getElementById("resultarea").innerHTML = com;
				sendAjaxRequest("askProductsAfter");
			}
			catch(e)
			{
				sendAjaxRequest("askProductsAfter");
			}	
		}
	}
}

function getPaymentListAfter()
{
	if(xmlHttp.readyState==4)
	{
		if(xmlHttp.status == 200)
		{
			var xmlResponse = xmlHttp.responseXML;
			xmlRoot = xmlResponse.documentElement;
			comArray = xmlRoot.getElementsByTagName("payment");
			shippingcostArray = xmlRoot.getElementsByTagName("shippingcost");
			try
			{
				shippingcost=shippingcostArray.item(0).firstChild.data;
				com=comArray.item(0).firstChild.data;
				if(shippingcost==0)
				{
					document.getElementById("shipping_cost").innerHTML = "Koszt dostawy z VAT: 0 zł";
					//document.getElementById("shipping_gross_main").value = 0;
					document.getElementById("shipping_gross").value = 0;
					document.getElementById("shipping_net").value = 0;
				}
				else
				{
					document.getElementById("shipping_cost").innerHTML = "Koszt dostawy z VAT: "+document.getElementById("shipping_gross_main").value+" zł";
					document.getElementById("shipping_gross").value = document.getElementById("shipping_gross_main").value;
				}
				document.getElementById("shippingcost").value = shippingcost;
				document.getElementById("payment_list").innerHTML = com;
				sendAjaxRequest("askProductsAfter");
			}
			catch(e)
			{
				sendAjaxRequest("askProductsAfter");
			}	
		}
	}
}


function getPaymentAfter()
{
	shippinggross_main = document.getElementById('shipping_gross_main').value;

	if(xmlHttp.readyState==4)
	{
		if(xmlHttp.status == 200)
		{
			payment_cost = 0;
			var xmlResponse = xmlHttp.responseXML;
			xmlRoot = xmlResponse.documentElement;
			minimalpriceArray = xmlRoot.getElementsByTagName("minimalprice");
			percentoforderArray = xmlRoot.getElementsByTagName("percentoforder");
			shippingcostArray = xmlRoot.getElementsByTagName("shippingcost");
			titleArray = xmlRoot.getElementsByTagName("title");
			minimalprice=minimalpriceArray.item(0).firstChild.data;
			percentoforder=percentoforderArray.item(0).firstChild.data;
			shippingcost=shippingcostArray.item(0).firstChild.data;
			ptitle=titleArray.item(0).firstChild.data;
			percentoforder = Math.decimal(parseFloat(document.getElementById('sum_gross').value)*parseInt(percentoforder)/100,0);
			if(percentoforder>minimalprice)
				payment_cost = percentoforder;
			else
				payment_cost = minimalprice;
			if(shippingcost==1)
				shippinggross=parseFloat(payment_cost)+parseFloat(shippinggross_main);
			else if(shippingcost==0)
				shippinggross=parseFloat(payment_cost);
			document.getElementById("shippingcost").value = shippingcost;
			document.getElementById("shipping_gross").value = shippinggross;
			document.getElementById("shipping_cost").innerHTML=ptitle+" "+shippinggross+" zł";
			//document.getElementById("shipping_net").value = shipping;
			sendAjaxRequest("getPaymentAfter");
		}
	}
}

function getGroupByManufacturersAfter()
{
	if(xmlHttp.readyState==4)
	{
		if(xmlHttp.status == 200)
		{
			var xmlResponse = xmlHttp.responseXML;
			xmlRoot = xmlResponse.documentElement;
			grouplistArray = xmlRoot.getElementsByTagName("grouplist");
			try
			{
				grouplist=grouplistArray.item(0).firstChild.data;
				document.getElementById("group_tree").innerHTML = grouplist;
				sendAjaxRequest("getGroupByManufacturersAfter");
			}
			catch(e)
			{
				sendAjaxRequest("getGroupByManufacturersAfter");
			}	
		}
	}	
}


function addToCart(mode,artId,cena,ile,pses)
{
	createAjaxString("mode="+mode+"&pr_id="+artId+"&cena="+cena+"&ile="+ile+"&pses="+pses);
	sendAjaxRequest("actualCart");	
}

function changeCart(mode,operation,artId,cena,ile,pses)
{
	payment = 0;
	try{
	if(document.orderform.payment!=undefined)
	{
		var pay = document.orderform.payment;
		for(i=0;i<pay.length;i++)
			if(pay[i].checked==true)
				payment = pay[i].value;
	}
	}catch(e){}
	createAjaxString("mode="+mode+"&pr_id="+artId+"&cena="+cena+"&ile="+ile+"&pses="+pses+"&operation="+operation+"&payment_id="+payment);
	sendAjaxRequest("actualCart2");
}

function getRandomProductList(mode,cnt)
{
	createAjaxString("mode="+mode+"&cnt="+cnt);
	sendAjaxRequest("getRandomProductListAfter");
}

function sendProductToUser(mode,product_id,email)
{
	if(email!="")
	{
		createAjaxString("mode="+mode+"&pid="+product_id+"&email="+email);
		sendAjaxRequest("sendProductToUserAfter");
	}
}

function askProducts(searchpart)
{
	document.getElementById("resultarea").style.display="block";
	createAjaxString("mode=5&searchpart="+searchpart);
	sendAjaxRequest("askProductsAfter");
}

function getPaymentList(mode,shipping_id)
{
	createAjaxString("mode="+mode+"&sid="+shipping_id);
	sendAjaxRequest("getPaymentListAfter");
}

function getGroupByManufacturers(mode)
{
	document.getElementById("group_tree").innerHTML = '<br/><br/><br/><br/><img src="img/preloader1.gif" />';
	
	var chkx=document.getElementsByName("manufac");
	var strumien='';
	for(i=0;i<chkx.length;i++)
	{
		if(chkx[i].checked)
			strumien+=chkx[i].value+',';
	}
	createAjaxString("mode="+mode+"&strumien="+strumien);
	sendAjaxRequest("getGroupByManufacturersAfter");
}

function getPayment(mode,payment_id,shipping_id)
{
	createAjaxString("mode="+mode+"&payment_id="+payment_id+"&shipping_id="+shipping_id);
	sendAjaxRequest("getPaymentAfter");
}

function sendQueryToSeller(mode,product_id,text,email)
{
	if(text!="")
	{
		createAjaxString("mode="+mode+"&pid="+product_id+"&text="+text+"&email="+email);
		sendAjaxRequest("sendQueryToSellerAfter");
	}
}


function fillSearchLine(text)
{
	document.getElementById("search-query").value=text;
	askProducts(text);
	document.getElementById("resultarea").style.display="none";
}

function closeResult()
{
	document.getElementById("resultarea").style.display="none";
}

function chkBgk(obj,color)
{
	obj.style.backgroundColor=color;
}



function chkEmail(status)
{
	if((status==1 && document.getElementById("sampleemail").value=="email"))
	{
		document.getElementById("sampleemail").value="";
	}
	if(status==0 && document.getElementById("sampleemail").value=="")
	{
		document.getElementById("sampleemail").value="email";
	}
}


function showPreloader(layer,sw)
{
	if(sw==1)
		document.getElementById('pr'+layer).style.display = 'block';
	else
		document.getElementById('pr'+layer).style.display = 'none';
}

function showSelectedLayer(layer,sw)
{
	if(sw==1)
		document.getElementById(layer).style.display = 'block';
	else
		document.getElementById(layer).style.display = 'none';
}

function searchByProduct()
{
	var chkx = document.getElementsByName("manufac");
	var path = document.getElementById("adv_search_list").value;
	var price_min = document.getElementById("price_min").value;
	var price_max = document.getElementById("price_max").value;
	if(price_min=="")
		price_min = 0;
	if(price_max=="")
		price_max = 100000;
	
	var strumien='';
	for(i=0;i<chkx.length;i++)
	{
		if(chkx[i].checked)
			strumien+=chkx[i].value+',';
	}
	location.href = 'sc.php?part=searchadv&path='+path+'&stream='+strumien+'&price_min='+price_min+'&price_max='+price_max;
}

function enlargePhotoList(elementId,type)
{
	if(type==1)
		document.getElementById(elementId).style.display='block';
	else if(type==0)
		document.getElementById(elementId).style.display='none';
}

function popup(adres,w,h)
{
 window.open(adres, '', 'toolbar=no,menubar=no,resizable=no,status=no,margines=no,location=no,directories=no,copyhistory=no,scrollbars=yes,height='+h+',width='+w+',left=0,top=0');
 // definicja otwieranego okienka przy wej¶ciu
}

function checkPayment()
{
	//var pay_length = document.orderform.payment.length;
	//if(document.orderform.payment[i].checked==true)
	var pay_length = document.getElementById("payment_list").getElementsByTagName("input").length;
	var test=0;
	for(i=0;i<pay_length;i++)
		if(document.getElementById("payment_list").getElementsByTagName("input")[i].checked==true)
			test = 1;	
	if(test == 0)
		alert("Wybierz sposób płatno¶ci");
	else
		document.orderform.submit();
}

function checkForm()
{
	var ship_length = document.orderform.shipping.length;
	var test=0;
	for(i=0;i<ship_length;i++)
		if(document.orderform.shipping[i].checked==true)
			test = 1;
	if(test == 0)
	{
		alert("Wybierz sposób dostawy");
		return false;
	}
	else
	{
		checkPayment();
		return true;
	}
}
