function checkDiscountCode(srcObj) {
	sR.post('/index.php','cmd=getDiscount&code=discount&ret=json&handler=displayBasket',rSC);
}
function applyDiscount(discount) {
	if(discount) {
		alert("ok");
		//apply
	}else{
		alert("failed");
		//incorrect code
	}
}
function loadMicroBasket() {
	var vars='cmd=getMyBasket&ret=json&handler=updateMicroBasket';
	sR.post('/index.php',vars,rSC);
}
function loadMiniBasket() {
	var vars='cmd=getMyBasket&ret=json&handler=displayMiniBasket';
	sR.post('/index.php',vars,rSC);
}
function loadFullBasket() {
	var vars='cmd=getMyBasket&ret=json&handler=displayBasket';
	sR.post('/index.php',vars,rSC);
}
function addToBasket(productID) {
	var vars='cmd=addToMyBasket&productId='+productID+'&templateName=product&ret=json&handler=displayMiniBasket';
	if (ob("quantity_select")) vars+='&quantity='+ob('quantity_select').value;
	sR.post('/index.php',vars,rSC);
}
var processingProductID=null;
function removeFromBasket(productID) {
	processingProductID=productID;
	var vars='cmd=removeFromMyBasket&productId='+productID+'&templateName=product&ret=json&handler=display'+(ob("basket")?"":"Mini")+'Basket';
	fader(ob("productid"+productID),50);
	fader(ob("baskettotal"),50);
	sR.post('/index.php',vars,rSC);
}
function decreaseInMyBasket(productID) {
	processingProductID=productID;
	var vars='cmd=decreaseInMyBasket&productId='+productID+'&templateName=product&ret=json&handler=display'+(ob("basket")?"":"Mini")+'Basket';
	fader(ob("productid"+productID),50);
	fader(ob("baskettotal"),50);
	sR.post('/index.php',vars,rSC);
}
function increaseInMyBasket(productID) {
	processingProductID=productID;
	var vars='cmd=addToMyBasket&productId='+productID+'&templateName=product&ret=json&handler=display'+(ob("basket")?"":"Mini")+'Basket';
	fader(ob("productid"+productID),50);
	fader(ob("baskettotal"),50);
	sR.post('/index.php',vars,rSC);
}
var currentBasket=null;
var discounts=null;
var deliveryCost=null;
var productCount=0;
var confirmation=false;
function displayMiniBasket(reply) {
	currentBasket=reply[0];
	discounts=reply[1];
	deliveryCost=reply[2];
	fillInMicroBasket();
	promptBasket();
	//listDiscounts();
}
function displayBasket(reply) {
	if (reply===null && ordered!==null) {
		reply=ordered;
		confirmation=true;
	}
	currentBasket=reply[0];
	discounts=reply[1];
	deliveryCost=reply[2];
	sIH(ob("basket"+(confirmation?"Confirmation":"")),BasketContent(false));
	listDiscounts();
}
function updateMicroBasket(reply) {
	currentBasket=reply[0];
	discounts=reply[1];
	deliveryCost=reply[2];
	if (ob("microbasket")) fillInMicroBasket();
	listDiscounts();
}
function fillInMicroBasket() {
	var op='';
	var itemCount=0;
	var totalNet=0;
	var totalVAT=0;
	var totalPrice=0;
	for(key in currentBasket) {
		itemCount+=1*currentBasket[key]["qty"];
		var product=currentBasket[key]['object'];
		totalNet+=currentBasket[key]["qty"]*(product['price']-product['vat']);
		totalVAT+=currentBasket[key]["qty"]*(product['vat']);
		totalPrice+=currentBasket[key]["qty"]*(product['price']);
	}
	if (itemCount>0) 	op=itemCount+" item"+((itemCount==1)?'':'s')+" at &pound;"+totalPrice.toFixed(2);
	ob('microbasket').innerHTML=op;
	ob('microbasket').style.display=(op.length>0)?"block":"none";
		
}
function promptBasket() {
	var b="<div id='minibasket'>"+BasketContent(true)+"</div>";
	if(ob("dialogContent")) {
		sIHCentered(ob("dialogContent"),b,"dialog");
		if (ob("productid"+processingProductID)) fadeObject.fade(ob("productid"+processingProductID),50,100,2,null);
		fadeObject.fade(ob("baskettotal"),50,100,2,null);
	}else{
		showdialog("Basket",b,null,600);
	}
}
function BasketContent(mini) {
	var special=(typeof(specialBasket)!="undefined");
	var op="";
	var itemCount=0;
	var totalNet=0;
	var totalVAT=0;
	var totalPrice=0;
	if (!mini && !confirmation) op+="<div id='basketheader' class='basketheader'>"+BasketDiscount()+(special?"Check order &amp; Delivery":"Basket Summary")+"</div>";
		if(mini) {
			op+="<div class='blank'></div>";
		}else{
			op+="<div id='baskethead'>";
		}
	op+="<div class='incvat'>Price <div>inc VAT</div></span></div>";
	if (!mini) {
		op+="<div class='vat'>VAT*</div>";
		op+="<div class='net'>NET</div>";
	}
	op+="<div class='quantity'>Quantity</div>";
	op+="<div class='item' >Product</div>";
	op+=mini?"":"</div>";
	for(key in currentBasket) {
		var q=currentBasket[key]["qty"];
		itemCount+=q;
		var product=currentBasket[key]['object'];
		var vatrate=1*product['vat_details']['vat_rate'];
		var thisPrice=1*((q*product['price']).toFixed(2));
		var thisInc=thisPrice;
		if (currentBasket[key]["discount"]) thisInc-=currentBasket[key]["discount"];
		thisInc=1*(1*thisInc).toFixed(2);
		var discPC=thisInc/thisPrice;
		var thisNet=(q*(product['price']*discPC/((100+vatrate)/100)).toFixed(2));
		var thisVAT=(thisNet*vatrate/100).toFixed(2);
		//var thisNet=1*(q*(discPC*(product['price']-product['vat'])).toFixed(2));
		//var thisVAT=1*(q*(discPC*product['vat']).toFixed(2));
		totalNet+=1*thisNet;
		totalVAT+=1*thisVAT;
		totalPrice+=1*thisInc;
		op+='<div class="basket_row" id="productid'+product["productID"]+'">';
		prices=thisInc.toString().split('.');
		pence=((prices.length>1)?prices[1]:"00").substring(0,2);
		while (pence.length<2) pence+="0";
		if (mini) op+="<div class='remove' title='remove' onclick='removeFromBasket("+product["productID"]+")' onmousedown='buttondown(this)' onmouseup='buttonup(this)'></div>";
		op+="<div class='incvat'";
		if (thisPrice!=thisInc) {
			op+=" title='reduced from £"+thisPrice+"' style='color:#91EA14'";
		}
		op+=">&#163;"+prices[0]+"<span>."+pence+"</span></div>";
		if (!mini) {
			prices=thisVAT.toString().split('.');
			pence=((prices.length>1)?prices[1]:"00").substring(0,2);
			while (pence.length<2) pence+="0";
			op+="<div class='vat'>&#163;"+prices[0]+"<span>."+pence+"</span></div>";
			prices=thisNet.toString().split('.');
			pence=((prices.length>1)?prices[1]:"00").substring(0,2);
			while (pence.length<2) pence+="0";
			op+="<div class='net'>&#163;"+prices[0]+"<span>."+pence+"</span></div>";
		}
		op+="<div class='quantity'>"+quantity(product["productID"],currentBasket[key]["qty"],mini)+"</div>";
		if (mini) {
			op+="<div class='item'>"+product["name"]+"</div>";
		}else{
			var imgsrc=product["image"]["source"];
			op+="<div class='item'>";
			op+="<img src='/admin/image-resizer.php?h=62&amp;keepAspect=y&amp;img="+imgsrc+"' style='float:left;padding:0px 10px 0px 0px' />";
			op+="<strong>"+product["name"]+"</strong>";
			op+="<div>"+product["type"]["name"]+"</div>";
			op+="<span class='spanlink' style='color:#999999' onclick='removeFromBasket("+product["productID"]+")' >remove</span>";
			op+="</div>";
		}
		op+="</div>";
	}
	op+='<div class="basket_row">';
	op+="<div class='blank'></div>";
	prices=totalPrice.toString().split('.');
	pence=((prices.length>1)?prices[1]:"00").substring(0,2);
	while (pence.length<2) pence+="0";
	op+="<div class='incvat' id='baskettotal'>&#163;"+prices[0]+"<span>."+pence+"</span></div>";
	if (special) {
	
		prices=totalVAT.toString().split('.');
		pence=((prices.length>1)?prices[1]:"00").substring(0,2);
		while (pence.length<2) pence+="0";
		op+="<div class='vat' >&#163;"+prices[0]+"<span>."+pence+"</span></div>";
	
		prices=totalNet.toString().split('.');
		pence=((prices.length>1)?prices[1]:"00").substring(0,2);
		while (pence.length<2) pence+="0";
		op+="<div class='net' >&#163;"+prices[0]+"<span>."+pence+"</span></div>";
	
		op+="<div class='item' style='text-align:right'><div style='margin-top:20px'>Basket total&nbsp;&nbsp;</div>";
		//op+="<div style='color:#999999'>*VAT is only applicable to countries within the EU&nbsp;&nbsp;</div>";
		op+="</div>";
		
		//op+="<select onchange='sR.post(\"/index.php\",\"cmd=setDeliveryOption&ret=json&handler=display"+(ob("basket")?"":"Mini")+"Basket&deliveryID=\"+this.value,rSC)'><option value='1'>First class</option><option value='3'>Second class</option></select>";
		if (deliveryCost) {
			prices=deliveryCost['cost'].toString().split('.');
			pence=((prices.length>1)?prices[1]:"00").substring(0,2);
			while (pence.length<2) pence+="0";
			op+="<div style='clear:both'><div class='net' title='to "+deliveryCost["destination"]+"' style='color:#fff'>&#163;"+prices[0]+"<span>."+pence+"</span></div><div class='net'></div><div class='net'></div>";
			op+="<div class='item' style='text-align:right'><div style='margin-top:4px'>Postage &amp; Packing&nbsp;&nbsp;</div><div style='color:#999999'>to "+deliveryCost["destination"]+"&nbsp;&nbsp;</div></div></div>";
		}
		var topay=(1*deliveryCost['cost']);
		if (deliveryCost['EU']=='1') {
			topay+=(1*totalPrice);
		}else{
			topay+=(1*totalNet);
		}
		prices=topay.toString().split('.');
		pence=((prices.length>1)?prices[1]:"00").substring(0,2);
		while (pence.length<2) pence+="0";
		op+='<div class="basket_row" style="width:201px;float:right">';
		
		op+='<div style="font-size:24px;color:#fff;float:right;line-height:72px;padding-right:10px">&#163;'+prices[0]+"<span style='font-size:16px'>."+pence+"</span></div>";
		op+='<div style="float:right;width:110px;text-align:right;font-size:12px;color:#fff;padding:10px 10px 0px 0px">';
		if (deliveryCost['EU']=='1') {
			op+='Total amount including<br />VAT and P&amp;P';
		}else{
			op+='Total amount including<br />P&amp;P (excluding VAT)';
		}
		op+='</div>';
		op+='</div>';
	}else{
		op+="<div class='quantity' style='color:#fff'>Total</div>";
	}
	op+="<div style='color:#999999;font-size:10px;padding:4px'>*VAT is only applicable to countries within the EU&nbsp;&nbsp;</div>";
	op+="<div id='redeemed'></div>";
	op+="</div>";
	var canProceed=false;
	if (itemCount>0) canProceed=true;
	if (!special) {
		op+="<div style='clear:both;padding:20px'>";
		if (canProceed) op+="<div class='proceed' style='float:right' onmousedown='buttondown(this)' onmouseup='buttonup(this)' onclick='window.location=\"/"+(mini?"basket.php":"delivery.php")+"\";'>"+(mini?"Checkout":"Continue with order")+"</div>";
		op+="<div class='back' onmousedown='buttondown(this)' onmouseup='buttonup(this)' onclick='"+(mini?"closeDialog()":"window.location=\"/online-shop.php\"")+"'>Continue shopping</div>";
		op+="</div>";
	}
	op+="<div style='clear:both'></div>";
	productCount=itemCount;
	var cb=null;
	if (cb=ob('chequeButton')) cb.style.display=(deliveryCost['cheque']=='1')?"block":"none";
	return op;
}
function quantity(pid,q,mini) {
	var op="";
	if (!confirmation) {
		op+="<table cellpadding=0 cellspacing=0><tr><td rowspan=2>x"+q+"</td>";
		op+="<td class='quantityUp' onclick='increaseInMyBasket("+pid+")' "+(!mini?"style='height:36px'":"")+">&nbsp;</td></tr><tr>";
		op+="<td class='quantityDown' onclick='decreaseInMyBasket("+pid+")' "+(!mini?"style='height:36px'":"")+">&nbsp;</td>";
		op+="</tr></table>";
	}else{
		op="x"+q;
	}
	return op;
}
function BasketDiscount() {
	var op="<div id='discountBox'><div class='okbutton' style='float:right' onclick='findDiscount(this)' onmousedown='buttondown(this)' onmouseup='buttonup(this)'>OK</div>";
	op+="<input id='discount_code' type='text' value='Discount code' onfocus='if (this.value==\"Discount code\") this.value=\"\";' onblur='if (this.value==\"\") this.value=\"Discount code\";' onkeyup='pressingEnterOrEscape(this,event,\"findDiscount\",null)' />";
	op+="</div>";
	return op;
}
function findDiscount(srcObj) {
	var vars='cmd=getDiscountCode&handler=gotDiscounts&code='+ob("discount_code").value;
	var db=ob("discountBox");
	db.style.width=db.clientWidth+"px";
	db.style.height=db.clientHeight+"px";
	db.innerHTML="<img src='/project/skin/imgloading.gif' /> finding discount";
	sR.post('/index.php',vars,rSC);
}
function getMyDiscounts() {
	var vars='cmd=getMyDiscounts&handler=gotDiscounts';
	sR.post('/index.php',vars,rSC);
}
function gotDiscounts(disc) {
	if (disc!==null) {
		displayBasket(disc);
	}
}
function listDiscounts() {
	var op='';
	for(var code in discounts) op+="<div>"+discounts[code]["attributes"]["publish_name"]+"</div>";
	if (op!="") op="<div style='margin:5px'><b style='display:block'>Redeemed discounts</b>"+op+"</div>";
	if (ob("redeemed")) sIH(ob("redeemed"),op);
}
function saveValuesToSessions(container,command,ret,handler) {
	var ips=container.getElementsByTagName("input");
	var sels=container.getElementsByTagName("select");
	var vars='cmd=storePOSTsToSession';
	for(var i=0;i<ips.length;i++) {
		if (ips[i].getAttribute("type")=="checkbox") {
			vars+="&"+ips[i].id+"="+encodeUpload(ips[i].checked?"on":"off");
		}else{
			vars+="&"+ips[i].id+"="+encodeUpload(ips[i].value);
		}
	}
	for(i=0;i<sels.length;i++) vars+="&"+sels[i].id+"="+encodeUpload(sels[i].value);
	if (command) vars+="&nextcmd="+command;
	if (ret) vars+="&ret="+ret;
	if (handler) vars+="&handler="+handler;
	sR.post('/index.php',vars,rSC);
}
function toggleSameAs() {
	tE("deliveryinput",false,true,"");
	if(!ob("sameas").checked) {
		ob("delcountry").selectedIndex=ob("invcountry").selectedIndex;
	}else{
		saveValuesToSessions(ob("deliveryDetails"),"setDeliveryCountry&countrycode="+ob("invcountry").value,"json","displayBasket");
	}
}
function submitDeliveryDetails(pay) {
	if (ob("confirmed").checked) {
		var errs=[];
		var validateInvoice=[["invfirstname","first name"],["invlastname","surname"],["invad1","invoice address"],["invtown","town/city"],["invpostcode","postcode"],["invemail","email address","email"]];
		if (!ob("sameas").checked) {
			validateInvoice.push(["delad1","delivery address"]);
			validateInvoice.push(["deltown","delivery town/city"]);
			validateInvoice.push(["delpostcode","delivery postcode"]);
		}
		if (productCount>0) {
			var validated=true;
			for(var i=0;i<validateInvoice.length;i++) {
				var valtype=(validateInvoice[i][2]?validateInvoice[i][2]:"dorequire");
				if (validateInput(ob(validateInvoice[i][0]),valtype)) {
					// if validated
				}else{
					validated=false;
					errs.push(validateInvoice[i][1]);
				}
			}
			if (!validated) {
				var err="We still require a valid ";
				for(var i=0;i<errs.length;i++) {
					var sep=", ";
					if (i==errs.length-2) sep=" and ";
					if (i==errs.length-1) sep=".";
					err+=errs[i]+sep;
				}
				dropThisMessage(err);
			}else{
				sendDeliveryDetails(pay);
			}
		}else{
			dropThisMessage("Your basket is empty");
		}
	}else{
		dropThisMessage("Please confirm that you have checked the details by ticking the box");
	}
}
function sendDeliveryDetails(pay) {
	var container=ob('deliveryDetails');
	var ips=container.getElementsByTagName("input");
	var sels=container.getElementsByTagName("select");
	// set to true when secure
	var secure=false;
	var temp="<div style='height:1px;overflow:hidden'><form action='/confirm.php' method='POST' name='processDelivery' id='processDelivery'>";
	temp+="<input type='text' name='cmd' value='confirmDelivery' />";
	for(var i=0;i<ips.length;i++) {
		if (ips[i].type=="checkbox") {
			temp+="<input type='text' name='"+ips[i].id+"' value='"+(ips[i].checked?"on":"")+"' />";
		}else{
			temp+="<input type='text' name='"+ips[i].id+"' value='"+ips[i].value+"' />";
		}
	}
	for(i=0;i<sels.length;i++)  {
		temp+="<input type='text' name='"+sels[i].id+"' value='"+sels[i].value+"' />";
	}
	if (pay) temp+="<input type='text' name='pay' value='1' />";
	temp+="</form></div>";
	pRH(temp,document.body);
	ob('processDelivery').submit();
}

