var arrowClickDir = 0;
var kartItems = new Array();
var curOrderTab = '';
var curOrderTabn = 0;
var featured = new Array();
var curfeatured = -1;
var featurePanel = '';
var showRow = 'inline';
var delTBC = false;

if ( navigator.appName != 'Microsoft Internet Explorer'){ showRow = 'table-row'; }

function roundNumber(rnum,ndp)
{
	var rlength = 2; // The number of decimal places to round to
	if (rnum > 8191 && rnum < 10485) {
		rnum = rnum-5000;
		var newnumber = Math.round(rnum*Math.pow(10,ndp))/Math.pow(10,ndp);
		newnumber = newnumber+5000;
	} else {
		var newnumber = Math.round(rnum*Math.pow(10,ndp))/Math.pow(10,ndp);
	}
	return newnumber;
}


function nextFeatured()
{
	if ( featurePanel == '' ){ return; }
  fPanel = document.getElementById(featurePanel);
	if ( !fPanel ){ return; }
	if ( featured.length == 0 ){
	  fPanel.innerHTML = "No featured items to display";
	} else {
    ++curfeatured;
	  if ( curfeatured == featured.length ){ curfeatured = 0; }
	  fPanel.innerHTML = '<table cellspacing="0" cellpadding="3" width="100%">'+
		                   '<tr><td valign="top"><img src="'+featured[curfeatured][3]+'" alt=""></td><td valign="top"><table width="100%">'+
											 '<tr><td colspan="2"><b>'+featured[curfeatured][1]+'</b></td></tr>'+
											 '<tr><td colspan="2">'+featured[curfeatured][2]+'</td></tr>'+
											 '<tr><td>'+addCurrency(featured[curfeatured][4])+'</td><td align="right">&nbsp;</td></tr>'+
											 '</table>';
//											 '<tr><td>'+addCurrency(featured[curfeatured][4])+'</td><td align="right">Buy&nbsp;<input type="text" style="width:30;"></td></tr>'+
//											 '</table>';
  }
}			
			
function searchForItems()
{
  document.forms.shoppingForm.thePath.value = '_search';
  document.forms.shoppingForm.theSearch.value = document.getElementById('searchBox').value;
  document.shoppingForm.submit();
}
function viewShopCatagoryItems(path,anc)
{
  if ( document.forms.shoppingForm.thePath.value == path ){ return; }
	if ( anc ){ document.shoppingForm.action = document.shoppingForm.action+'#'+anc; }
  document.forms.shoppingForm.thePath.value = path;
  document.forms.shoppingForm.theSearch.value = '';
//alert( 'calling submit' );
  document.shoppingForm.submit();
}

function saveShoppingKart(basketID)
{
  document.forms.shoppingForm.thePath.value = '_basket';
	document.forms.shoppingForm.basketID.value = basketID;
  document.forms.shoppingForm.nextAction.value='save';
  document.forms.shoppingForm.theSearch.value = '';
  document.shoppingForm.submit();
}

function clearShoppingKart()
{
  document.forms.shoppingForm.thePath.value = '';
  document.forms.shoppingForm.theBasket.value = '';
  document.forms.shoppingForm.theSearch.value = '';
  document.forms.shoppingForm.nextAction.value = 'empty';
  document.shoppingForm.submit();
}

function viewCustomerOrders(orderNum)
{
  document.forms.shoppingForm.thePath.value = '_shopOrderDetail';
  document.forms.shoppingForm.nextAction.value = orderNum;
  document.forms.shoppingForm.theSearch.value = '';
  document.shoppingForm.submit();
}

function textArea2kartItems()
{
  ta = document.getElementById('theBasket');
	if ( !ta ){ return -1; }
  items = String(ta.value).split('|');
	j = 0;
	for ( i = 0 ; i < items.length ; ++i ){
	  bits = items[i].split(',');
		if ( bits.length == 3 ){
		  kartItems['k'+bits[0]] = Array(bits[1],bits[2]);
			j++;
		}
	}
	return j;
}
function kartItems2textArea()
{
/*  ta = document.getElementById('theBasket');
	if ( !ta ){ return -1; }
	delim='';
	ta.value = '';
	j = 0;
  for (var iid in kartItems){
	  ta.value = ta.value+delim+'k'+iid+','+kartItems[iid][0]+','+kartItems[iid][1];
		delim = '|';
		j++;
	}
alert(ta.value);
	return j;
*/
}
function setArrowClickDir(val)
{
  arrowClickDir = val;
}
function IncrementQuantity(id,maxQ,cost,pcost)
{
//alert(id+', '+maxQ+', '+cost);
  if ( pcost && pcost > 0 && pcost < cost ){ cost = pcost; }
  curQuantity = parseInt(document.getElementById('quanity_'+id).value,10) + arrowClickDir;
  if ( curQuantity < 0 ){ curQuantity = 0; }
	if ( arrowClickDir == 1 && ( !maxQ || maxQ == '' || curQuantity == parseInt(maxQ,10)+1 )){
	  if ( !confirm('Only '+parseInt(maxQ,10)+' in stock\n\rYou may order more but this may delay your delivery') ){
		  return;
		}
	}
	
//	if ( curQuantity >= 0 && ( !maxQ || maxQ == '' || curQuantity <= parseInt(maxQ,10) ) ){
	  document.getElementById('quanity_'+id).value = curQuantity;
		if ( document.getElementById('basketCount').value == "" ){
		  basketTotal = arrowClickDir;
		  basketVal = arrowClickDir*cost;
    } else {
		  basketTotal = parseInt(document.getElementById('basketCount').value,10) + arrowClickDir;
		  basketVal = parseFloat(document.getElementById('basketValue').value) + arrowClickDir*cost;
		}
		document.getElementById('basketCount').value=basketTotal;
		document.getElementById('basketValue').value=basketVal;
		updateBasket(id,curQuantity,curQuantity*cost);
    if ( basketTotal < 1 ){
		  document.getElementById('emptyBasket').style.display = 'inline';
		  document.getElementById('oneItemBasket').style.display = 'none';
		  document.getElementById('manyItemBasket').style.display = 'none';
		  document.getElementById('totalBasketValue').style.display = 'none';
		  document.getElementById('basketLinks').style.display = 'none';
		} else {
		  document.getElementById('emptyBasket').style.display = 'none';
			if ( basketTotal == 1 ){
		    document.getElementById('oneItemBasket').style.display = 'inline';
		    document.getElementById('manyItemBasket').style.display = 'none';
			} else {
		    document.getElementById('oneItemBasket').style.display = 'none';
		    document.getElementById('manyItemBasket').style.display = 'inline';
				document.getElementById('manyItemBasket').childNodes[0].innerHTML = 'Your basket has '+basketTotal+' items';
			}
		  document.getElementById('totalBasketValue').style.display = 'inline';
			document.getElementById('totalBasketValue').childNodes[0].innerHTML = 'Total value is '+addCurrency(basketVal);
		  document.getElementById('basketLinks').style.display = 'inline';
		}
//	}
}
function updateBasket(idd,num,val)
{
//alert(idd+', '+num+', '+val);
//  var idd = document.getElementById('itemid_'+id).value;
  var curBasket = String(document.getElementById('theBasket').value);
	if ( curBasket == '' ){
	  if ( num == 0 ){ return; }
	  document.getElementById('theBasket').value= '|'+idd+','+num+','+val+'|'; return;
	}
	bits = curBasket.split('|'+idd+',');
	if ( bits.length == 1 ){
	  if ( num == 0 ){ return; }
	  document.getElementById('theBasket').value = curBasket+idd+','+num+','+val+'|'; return;
	}
	bits1 = bits[1].split('|');
	if ( num == 0 ){ curBasket = bits[0]+'|';}
	else { curBasket = bits[0]+'|'+idd+','+num+','+val+'|';}
	for ( i = 1 ; i < bits1.length ; ++i ){
	  if ( bits1[i] != '' ){ curBasket = curBasket + bits1[i]+'|';}
	}
	document.getElementById('theBasket').value = curBasket;
}
function addCurrency(val)
{
  val = roundNumber(val,2);
  var bits = String('&pound;'+val).split('.');
	if ( bits.length > 1){ return bits[0]+'.'+String(bits[1]+'00').substr(0,2);}
  return bits[0]+'.00';
}

function setPaymentOption(obj)
{
  document.getElementById('paymentMessage').innerHTML = 'Payment method: <b>'+obj.value+'</b>';
}

function setDeliveryOption(obj,conf)
{
// display any delivery type selections required
  document.getElementById('noAddDelOptions').style.display = 'none';
  document.getElementById('collectionFrom').style.display = 'none';
  document.getElementById('courierSelection').style.display = 'none';
	if ( obj.value == 'coll' ){ 
	  document.getElementById('collectionFrom').style.display = showRow;
	  if ( conf ){
		  alert('If you wish to collect items please enter the venue and date of agreed pick up\nOR the venue and date of the course you are attending.');
	    document.getElementById('collectionOpts').focus();
		}
	  document.getElementById('invoiceDelOpt').innerHTML = 'Items to be collected';
		
	} else if ( obj.value == 'cour' ){ document.getElementById('courierSelection').style.display = showRow;}
	else { document.getElementById('noAddDelOptions').style.display = showRow;}
// check out the associated delivery charge
	totalOrderWeight = document.getElementById('totalWeight').value;
  delChargeModel = "";
  for ( i = 0 ; i < deliveryCosts.length ; ++i ){
	  if ( deliveryCosts[i][0] == obj.value ){
		  delChargeModel = deliveryCosts[i][1];
			i = deliveryCosts.length;
		}
	}
	var totalVal = parseFloat(document.getElementById('totalValue').value);
	var delCharge = 0.0;
	var sevCharge = 0.0;
	var bits = delChargeModel.split('|');
	var cmpVal = document.getElementById('deliveryValue').value;
	
	delTBC = false;
	switch ( bits[0] ){
	  case 'free':
			document.getElementById('deliveryCost').innerHTML = 'free';
			break;
	  case 'tbc':
			document.getElementById('deliveryCost').innerHTML = 'TBC';
			document.getElementById('invoiceDelOpt').innerHTML = 'Delivery options to be quoted';
			delTBC = true;
			break;
	  case 'fixed':
//	    document.getElementById('invoiceDelCost').innerHTML = addCurrency(bits[1]);
		  delCharge = parseFloat(bits[1]);
//			totalCharge = totalVal + delCharge;
//	    document.getElementById('invoiceTotalCost').innerHTML = addCurrency(''+totalCharge);
			document.getElementById('deliveryCost').innerHTML = addCurrency(''+delCharge);
			break;
	  case 'byweight':
	    cmpVal = document.getElementById('totalWeight').value;
			// intentionally no break
	  case 'byval':
		  var i = bits.length-1;
	    delCharge = parseFloat(bits[i--]);
			while ( cmpVal <= parseFloat(bits[i]) && i > 0 ){
			  delCharge = parseFloat(bits[--i]);
				--i;
			}
			if ( cmpVal == 0.0 ){ delCharge = 0.0; }
//			document.getElementById('invoiceDelCost').innerHTML = addCurrency(delCharge);

/*
		  totalCharge = totalVal + delCharge + sevCharge;
			document.getElementById('deliveryCharge').value = delCharge;
			document.getElementById('serviceCharge').value = sevCharge;
			document.getElementById('grandTotalValue').value = totalCharge;
*/
//	    document.getElementById('invoiceTotalCost').innerHTML = '<b>'+addCurrency(''+totalCharge)+'</b>';
	    document.getElementById('invoiceDelOpt').innerHTML = 'Items to be delivered by '+obj.options[obj.selectedIndex].text;
//			document.paypalForm.amount.value=totalCharge;
			document.getElementById('deliveryCost').innerHTML = addCurrency(''+delCharge);
			document.getElementById('deliveryCost').title=cmpVal;
			break;
	  default:
			document.getElementById('deliveryCost').innerHTML = '&nbsp;';
			break;
	}

	totalCharge = totalVal + delCharge + sevCharge;
	document.getElementById('serviceCharge').value = sevCharge;

	if ( delTBC ){
	  document.getElementById('deliveryCharge').value = 'TBC';
	  document.getElementById('grandTotalValue').value = 'TBC';
	  document.getElementById('invoiceDelCost').innerHTML = 'TBC';
	  document.getElementById('invoiceTotalCost').innerHTML = 'TBC';
	} else {
	  document.getElementById('deliveryCharge').value = delCharge;
	  document.getElementById('grandTotalValue').value = totalCharge;
		document.getElementById('invoiceDelCost').innerHTML = addCurrency(''+delCharge);
	  document.getElementById('invoiceTotalCost').innerHTML = addCurrency(''+(totalVal+delCharge));
	}
	document.paypalForm.amount.value=roundNumber(totalVal+delCharge, 2);
//	document.paypalForm.no_shipping.value=1;




  payOps = document.getElementById('paymentOption').options;
	while ( payOps.length > 0 ){ payOps[0] = null; } //remove(0); }
  for ( i = 0 ; i < paymentOptions.length ; ++i ){
	  if ( paymentOptions[i][0] == obj.value ){
			opt = new Option('Select payment method','');
			payOps.add(opt);
		  for ( jop = 1; jop < paymentOptions[i].length ; ++jop ){
			  opt = new Option(paymentOptions[i][jop],paymentOptions[i][jop]);
				payOps.add(opt);
			}
			return;
		}
	}
	opt = new Option('Select delivery method first','');
	payOps.add(opt);
}

function payPalNow(siteName,website,orderNum,totalValue)
{
  if ( !confirm('Note - this link is displayed until payment has been confirmed to '+siteName+' from PayPal.\n\rPlease do not re-submit payment for an order you have already successfully paid for.\n\rDo you want to continue with payment?')){
	  return;
	}
	document.paypalForm.item_name.value='Order number : '+orderNum+' from '+website;
	document.paypalForm.amount.value=roundNumber(totalValue, 2);
	document.paypalForm.submit();
}

function setCollectionOption(obj)
{
  if ( obj.value == '' ){
	  document.getElementById('invoiceDelOpt').innerHTML = 'Items to be collected, but not specified when or where';
	} else {
	  document.getElementById('invoiceDelOpt').innerHTML = '<p>Order to be collected in person from:<br>&nbsp;&nbsp;&nbsp;<b>'+obj.value+'</b></p><p>Please bring a copy of this invoice with you</p>';
	}
	document.getElementById('invoiceDelCost').innerHTML = '?0.00';
	document.getElementById('invoiceTotalCost').innerHTML = document.getElementById('kartItemTotal').innerHTML;
}

function makePurchase()
{
// check purchase method
  switch (document.getElementById('paymentOption').value) {
	  case 'Cash on collection':
		break;
    case 'Personal Cheque':
		break;
    case 'Postal Order':
		break;
		case 'Credit Card (Pay Pal)':
		  if ( !delTBC ){
		    ppForm = document.paypalForm;
			  if ( ppForm ){ ppForm.submit();	}
			}
		break;
	}
	viewShopCatagoryItems('_confirm',null);
}

function nextFromCheckout1()
{
  if ( document.getElementById('customerName').value == '' ){
	  alert('You must supply your name');
		document.getElementById('customerName').focus();
		return;
	}
  if ( document.getElementById('customerAddress').value == '' ){
	  alert('You must supply your address');
		document.getElementById('customerAddress').focus();
		return;
	}
  if ( document.getElementById('customerEmail').value == '' ){
	  alert('You must supply your email');
		document.getElementById('customerEmail').focus();
		return;
	}
  if ( document.getElementById('deliveryOption').value == '' ){
	  alert('You must choose a delivery option');
		document.getElementById('deliveryOption').focus();
		return;
	}
//	if ( document.getElementById('deliveryOption').value == 'coll' && document.getElementById('collectionOpts').value == '' ){
//	  alert('You must choose a collection point');
//		document.getElementById('collectionOpts').focus();
//		return;
//	}

  if ( document.getElementById('paymentOption').value == '' ){
	  alert('You must choose a payment option');
		document.getElementById('paymentOption').focus();
		return;
	}
	re = RegExp('\n','g');
	document.getElementById('invoiceCustomerName').innerHTML = '<nobr><b>'+document.getElementById('customerName').value+'</b></nobr><br>'+String(document.getElementById('customerAddress').value).replace(re,'<br>');

// calculate the delivery charge
  if ( document.getElementById('invoiceDelOpt').innerHTML == 'Items to be collected' ){
	  if ( document.getElementById('collectionOpts').value == '' ){ document.getElementById('invoiceDelOpt').innerHTML = 'Items to be collected - collection point to be agreed'; }
	  else { document.getElementById('invoiceDelOpt').innerHTML = 'Items to be collected from '+document.getElementById('collectionOpts').value; }
	}


	checkOutPage(2);

}
function checkOutPage(page)
{
  switch ( page ){
	  case 1:  // Customer details
      document.getElementById('customerDetails').style.display = 'inline';
	    document.getElementById('saleinvoice').style.display = 'none';
			break;
	  case 2:  // Invoice
      document.getElementById('customerDetails').style.display = 'none';
	    document.getElementById('saleinvoice').style.display = 'inline';
			break;
	}
}

function PrintInvoice()
{
  var divs = document.getElementsByTagName("div");
  for ( i=0 ; i < divs.length ; i++ ){
    if ( divs[i].className == 'ShopInvoice' ){
//		alert('found Invoice');
      divs[i].className = 'ShopInvoice printme';
      ipar = divs[i];
      while ( ipar && ipar.tagName != 'BODY' ){
        ipar.className = ipar.className+' printme';
        if ( ipar.parentNode.childNodes.length > 1 ){
          ipSib = ipar.previousSibling;
          while ( ipSib ){ ipSib.className = ipSib.className+' noPrintMe'; ipSib = ipSib.previousSibling; }
          inSib = ipar.nextSibling;
          while ( inSib ){ inSib.className = inSib.className+' noPrintMe'; inSib = inSib.nextSibling; }
        }
        ipar = ipar.parentNode;
      }
    }
  }
  print();
}
function changeOrder(orderID)
{
  bits = String(document.location).split('&ord=');
	if ( bits.length > 1 ){
	  document.location=bits[0]+'&ord='+orderID;  // presumes the order id is always the last argument
	} else {
	  document.location=document.location+'&ord='+orderID;
	}
}
function changeOrderTab(tab,itab)
{
  if ( curOrderTab != "" ){ document.getElementById(curOrderTab).style.display = 'none'; }
  curOrderTab = tab;
	document.getElementById(curOrderTab).style.display = 'inline';
  if ( curOrderTabn != -1 ){ document.getElementById('tabCell'+curOrderTabn).className = 'wbTabsUnSelected';}
	curOrderTabn = itab;
	document.getElementById('tabCell'+curOrderTabn).className = 'wbTabsSelected';
}
function checkAccountDetails(act)
{
  if ( document.getElementById('customerName').value == '' ){
	  alert('You must supply your name');
		document.getElementById('customerName').focus();
		return;
	}
  if ( document.getElementById('customerAddress').value == '' ){
	  alert('You must supply your address');
		document.getElementById('customerAddress').focus();
		return;
	}
  if ( document.getElementById('customerEmail').value == '' ){
	  alert('You must supply your email');
		document.getElementById('customerEmail').focus();
		return;
	}
	if ( act != 'Update Details' || document.getElementById('customerPass1').value != '' ){
    if ( String(document.getElementById('customerPass1').value).length < 6 ){
	    alert('You must specify a password of at least 6 characters');
		  document.getElementById('customerPass1').focus();
		  return;
	  }
	  if ( document.getElementById('customerPass1').value != document.getElementById('customerPass2').value ){
	    alert('The password and confirmation do not match');
		  document.getElementById('customerPass1').value = '';
		  document.getElementById('customerPass1').value = '';
		  document.getElementById('collectionOpts').focus();
		  return;
		}
	}
// create the notification flag
  var not = 0;
	if ( document.forms.shoppingForm.offerNotification.checked ){ not = 1;}
	if ( document.forms.shoppingForm.newNotification.checked ){ not = not+2;}
  document.forms.shoppingForm.notifications.value = not;
	
// okay create the account
  if ( act == 'Create Account' ){
    document.forms.shoppingForm.thePath.value = '_createAccount';
	} else {
    document.forms.shoppingForm.thePath.value = '_updateAccount';
	}
  document.forms.shoppingForm.theSearch.value = '';
  document.shoppingForm.submit();
}
function loginToAccount()
{
  document.forms.shoppingForm.thePath.value = '_doLogin';
  document.forms.shoppingForm.theSearch.value = '';
  document.shoppingForm.submit();
}
function showChangePassword(show)
{
	document.getElementById('customerPass1').value = '';
	document.getElementById('customerPass2').value = '';
  if ( show ){
    document.getElementById('changePasswordRow').style.display = '';
    document.getElementById('noChangePasswordRow').style.display = 'none';
		document.getElementById('customerPass1').focus();
	} else {
    document.getElementById('changePasswordRow').style.display = 'none';
    document.getElementById('noChangePasswordRow').style.display = '';
	}

}

