// To do

// advert

var productArray = new Array();
var basketArray = new Array();
var sum = 0.0;

var titleIndex=0;
var title='';
var firstName='';
var familyName='';
var line1='';
var line2='';
var town='';
var postCode='';
var country='';
var email='';
var phone='';
var monthIndex=0;
var month='';
var yearIndex=0;
var year='';
var startMonthIndex=0;
var startMonth='';
var startYearIndex=0;
var startYear='';
var cc='';
var cardTypeIndex=0;
var cardType='';

var shippingString = '<P><P>Shipping will be charged at the following rates (per order):Local Area Maryborough & Hervey Bay free delivery for orders over $25.00,  1 - 5kg $8.00 </P><P>5 - 10kg $12.00, 10 - 20kg $18.00, over 20kg P.O.A.</P></p>';

initProdList();


function productLine(productCode, productDescription, price, group) {
  this.productCode = productCode;
  this.productDescription = productDescription;
  this.price = price;
  this.group = group;
}

function orderLine(productCode, productDescription, price, quantity) {
  this.productCode = productCode;
  this.productDescription = productDescription;
  this.price = price;
  this.quantity = quantity;
}

function initProdList() {
 productArray[0] = new productLine('SPICO140','140 AMP INVERTER 240V',1450,'WELDING'); productArray[1] = new productLine('SB6211150','150AMP MIG WELDER',850,''); productArray[2] = new productLine('SB6211175','175AMP MIG WELDER',1200,''); productArray[3] = new productLine('SB6211255','250 AMP MIG WELDER REMOTE',2450,''); productArray[4] = new productLine('SWB02710-PR','WIRE BRUSH 6 ROW',7.85,''); productArray[5] = new productLine('SWB02710-GR','WIRE BRUSH 6 ROW S/STEEL',9.65,''); productArray[6] = new productLine('S61400','WIRE BRUCH 4 ROW',4.25,''); productArray[7] = new productLine('S105001','OXY ACET STARTER PACK',415,'OXY/ACET'); productArray[8] = new productLine('S105002','OXY ACET MASTER PACK',535,''); productArray[9] = new productLine('SBOCTW0505A','OXY/ACET TWIN HOSE 5M ',59,''); productArray[10] = new productLine('S300FLWKT','GLOVE BIG REDS',10,'GLOVES'); productArray[11] = new productLine('S743373','GLOVE BLACK & GOLD',3.95,''); productArray[12] = new productLine('SGGL012','GLOVE RIGGER',6,''); productArray[13] = new productLine('SKB436A','GLOVE FIGHTER STYLE H/DUTY',2.4,''); productArray[14] = new productLine('SGUARD-101','SAFETY GUARD SYSTEM',295,'SAFETY'); productArray[15] = new productLine('STB19U85','BARRIER MESH H/DUTY',95,''); productArray[16] = new productLine('siltmesh','SILT STOP MESH 100M',85,''); productArray[17] = new productLine('STCONE450S','TRAFFIC CONES 450MM',15,''); productArray[18] = new productLine('S901TAPED','DANGER TAPE 50M',9.5,''); productArray[19] = new productLine('S901TAPEC','CAUTION TAPE 50M',9.5,''); productArray[20] = new productLine('SHVD2','VESTS LIME OR ORANGE ',8.95,''); productArray[21] = new productLine('SCV102','VESTS LIME OR ORANGE (NIGHT USE)',32,''); productArray[22] = new productLine('SVF105','CLEAR VISOR LIFT FRONT',22,''); productArray[23] = new productLine('S132C','KNOCK OFF BARRIER CREAM',7.5,''); productArray[24] = new productLine('S055C','BARRIER CREAM 500ML',7.5,''); productArray[25] = new productLine('SMW38M','MEASURE WHEEL 0 - 10000M LUFKIN',185,'TRADE TOOLS'); productArray[26] = new productLine('S431808','LUFKIN 8M TAPE MEASURE',16.5,''); productArray[27] = new productLine('SCHALKIT','CHALK LINE COMBINATION KIT',19.95,''); productArray[28] = new productLine('SCHALKALL','CHALK LINE POWDER 112g',12,''); productArray[29] = new productLine('SCHALKALL2','CHALK LINE POWDER 224g',22.5,''); productArray[30] = new productLine('SPT010','AIR HOSE 10MM X 30M COIL',39.95,''); productArray[31] = new productLine('SETC-1200LBB','LEVEL 1200MM',19.95,''); productArray[32] = new productLine('SSL-200','NAIL BAG 2 POCKET',25,''); productArray[33] = new productLine('SSL-029','NAIL BAG 3 POCKET & HOLSTER',30,''); productArray[34] = new productLine('SSL-055','SHAW BAG 2 POCKET ',42,''); productArray[35] = new productLine('qikalum','EPOXY REPAIR FOR ALUMIMUM',30.25,'EPOXY PRODUCTS'); productArray[36] = new productLine('qikaqua','EPOXY REPAIR FOR BOATIES',30.25,''); productArray[37] = new productLine('qikcopper','EPOXY REPAIR FOR COPPER',30.25,''); productArray[38] = new productLine('qikcrete','EPOXY REPAIR FOR CONCRETE',30.25,''); productArray[39] = new productLine('qikplastic','EPOXY REPAIR FOR PLASTIC',30.25,''); productArray[40] = new productLine('qiksteel','EPOXY REPAIR FOR STEEL',30.25,''); productArray[41] = new productLine('qikwood','EPOXY REPAIR FOR WOOD',30.25,''); 
}



function money(val) {
  if (val == 0) return("FREE");
  var inputVal = ("" + val);
  if (inputVal.indexOf(".") == -1) inputVal += ".00";
  var i = inputVal.indexOf(".");
  var pounds = inputVal.substring(0, i);
  var pence = inputVal.substring(i+1, i+3);
  if (pence.length == 1) pence += "0";
  return('$' + pounds + '.' + pence);
}

function td(str) {
  return('<td>' + str + '</td>');
}

function tdr(str) {
  return('<td align="right">' + str + '</td>');
}

function pp(str) {
  return('<P>' + str + '</P>');
}

function th(str) {
  return('<th bgcolor="lightBlue">' + str + '</th>');
}

function boughtWithCode(code){
  for (var i=0; i<basketArray.length; i++) {
    if (basketArray[i].productCode == code) {
      return i;
    }
  }
  return -1;
}

function addBasket(productCode, productDescription, price) {
  // CHANGE TO JUST USE PRODUCT CODE- can look the rest up.
  // If there is already one item, ask how many to add, else add just one
  var i = boughtWithCode(productCode);
  if (i > -1) {
    var n = basketArray[i].quantity + 1;
    basketArray[i].quantity = n;
  }
  else {
    basketArray[basketArray.length] = 
             new orderLine(productCode, productDescription, price, 1);
  }
  this.refreshBasket();
}

function refreshBasketString() {
  sum = 0.0;
  s = mainFrameHeader();
  s = s + '<h1 align="center">Shopping Basket</h1>';
  s = s + '<form name="f">';
  s = s + '<table width="100%">';
  s = s + '<tr>' + th('Quantity') + th('Description') + th('Unit Price Inc G.s.t') + th('Total') + '</tr>';
  for (var i=0; i< basketArray.length; i++) {
    var p = basketArray[i];
    s = s + '<tr>';
    s = s + td('<input type="text" size=4 value=\"' + p.quantity + 
			'\" name=\"' + p.productCode + 
			'\" onMouseOut=\"parent.changeQuantity(this.name, this.value)\"' +
			'\" onBlur=\"parent.changeQuantity(this.name, this.value)\">');
    s = s + td(p.productDescription);
    s = s + tdr(money(p.price));
    var total = p.price * p.quantity;
    s = s + tdr(money(total));
    s = s + td('<input type="button" value="Cancel" onClick="parent.removeBasket(' + i + ')">');
    s = s + '</tr>';
    sum = sum + total;
  }
  s = s + '<tr><th colspan=3 bgcolor="lightBlue">Total (excluding shipping)</th>' + '<th align="right" bgcolor="lightBlue">' +
			money(sum) + '</th></tr>';
  s = s + '</table>';
  s = s + '<input type="button" value="Select More Products" onClick="parent.refreshList()">';
  s = s + '<input type="button" value="Proceed to Checkout" onClick="parent.refreshClose()">';
  s = s + '</form>' + mainFrameFooter();
  return s;
}

function refreshBasket() {
  var doc = parent.frames['mainFrame'].document;
  doc.open();
  doc.writeln(refreshBasketString());
  doc.close();
}


function removeBasket(n) {
  // If quantity > 1 then ask how many to remove.
  var newArray = new Array(basketArray.length - 1);
  for (var i=0; i< n; i++) {
    newArray[i] = basketArray[i];
  }
  for (var j=n+1; j < basketArray.length; j++) {
    newArray[j-1] = basketArray[j];
  }
  basketArray = newArray;
  this.refreshBasket();
}

function changeQuantity(productID, quantity) {
  // Field name is a product ID. Find the right basket item.
  for (var i=0; i< basketArray.length; i++) {
    var p = basketArray[i];
    if (p.productCode == productID) {
      // has the quantity changed?
      if (quantity != p.quantity) {
        // if it has changed, is it to a valid number ?
	if (isNaN(quantity)) {
		this.refreshBasket();
	}
	else {
     	 	p.quantity = parseInt(quantity);
		if (p.quantity <= 0) {
			this.removeBasket(i);
		}
		else {
        		this.refreshBasket();
		}
	}
      }
    }
  }
}

function mainFrameHeader(){
  return '<body bgColor="lightGreen" LINK="blue" ALINK="blue" vlink="blue">';
}

function mainFrameFooter(){
  return '</body>';
}

function refreshListString() {
  s = mainFrameHeader() + '<h1 align="center">Products</h1> <P> </P> <table width="100%"> <form>';
  for (var i=0; i< productArray.length; i++) {
    var p = productArray[i];
    if (p.group != "") {
      s = s + '<tr><th colspan=3 bgcolor="lightBlue"><B>' + p.group + '</b></th></tr>';
    }    
    s = s +'<tr>';
    // Create a hyper link to the virtual page for the long description and picture
    s = s + td('<A HREF=\"' + p.productCode + '.html\">' + p.productDescription + '</A>');
    s = s + tdr(money(p.price));
    s = s + '<td><input type="button" value="Add to Basket" onClick="parent.addBasket(\'' + p.productCode + '\',\'' + p.productDescription + '\',' + p.price + ')"></td>';
    s = s + '</tr>';
  }
  s = s + '</table> </form>';
  s = s + mainFrameFooter();
  return s;
}

function refreshList() {
  var doc = parent.frames['mainFrame'].document;
  doc.open();
  doc.writeln(refreshListString());
  doc.close();
}

function ipRow(label,field) {
 return '<tr><td>' + label +'</td><td><input name=\"' + field + '\" type="text" size=30></td></tr>'
}

function refreshClose() {
  var doc = parent.frames['mainFrame'].document;
  doc.open();
  doc.writeln('<body bgColor="lightGreen" LINK="blue" ALINK="blue" vlink="blue">');
  doc.writeln('<h1 align="center">Checkout</h1>');
  doc.writeln(pp('To process your order, all boxes must be properly filled in.&nbsp; To reduce the possibility of credit card fraud, we will only ship orders to the same address that the credit card statement is sent to'));
  doc.writeln('<form name="order"><table>');
  doc.writeln('<tr><th bgcolor="lightBlue" colspan="2" align="left">Name exactly as it appears on your Credit Card</th></tr>');
//  doc.writeln('<tr><td>Title</td><td><select name="title"><option>Mr<option>Mrs<option>Miss<option>Ms<option>Dr<option>Prof</select></td></tr>');
//  doc.writeln(ipRow('First Name (or initials)', 'firstName'));
  doc.writeln(ipRow('Name / Company', 'familyName'));
  doc.writeln('<tr><th bgcolor="lightBlue" colspan="2" align="left">Shipping Address - Must be the same as credit card billing address or purchase order</th></tr>');
  doc.writeln(ipRow('Delivery Address', 'line1'));
  doc.writeln(ipRow('', 'line2'));
  doc.writeln(ipRow('City / State/ Post Code','town'));
  doc.writeln(ipRow('Order Number', 'postCode'));
  doc.writeln('<tr><td></td><td></td></tr>');
  if ('Contact Name / Department' != '') doc.writeln(ipRow('Contact Name / Department','country'));
  doc.writeln(ipRow('Email Address','email'));
  doc.writeln(ipRow('Phone number', 'phone'));
  doc.writeln('<tr><th bgcolor="lightBlue" colspan="2" align="left">Payments</th></tr>');
  doc.writeln('<tr><td>Total Excluding Shipping</td><td><b>' + money(sum) + '</b></td></tr>');
  doc.writeln('<tr><td colspan="2">' + shippingString + '</td></tr>');
  if (true) {
  	doc.writeln('<tr><td colspan="2"><P>Your credit card number will be disguised as ordinary text before transmission to your ISP, to help prevent credit card fraud. </P></td></tr>');
  	doc.writeln('<tr><td>Card Type</td><td><select name="cardType"><option>Visa<option>Mastercard<option>American Express</select></td></tr>');
  	doc.writeln('<tr><td>Card Number (no spaces)</td><td><input name="cc" type="text" size=16></td></tr>');
  	doc.writeln('<tr><td>Valid from</td><td><table><tr><td><select name="startMonth"><option>Jan<option>Feb<option>Mar<option>Apr<option>May<option>Jun<option>Jul<option>Aug<option>Sep<option>Oct<option>Nov<option>Dec</select></td><td><select name="startYear"><option>1996<option>1997<option>1998<option>1999<option>2000<option>2001<option>2002<option>2003<option>2004<option>2005</select></td></tr></table></td></tr>');
  	doc.writeln('<tr><td>Thru</td><td><table><tr><td><select name="month"><option>Jan<option>Feb<option>Mar<option>Apr<option>May<option>Jun<option>Jul<option>Aug<option>Sep<option>Oct<option>Nov<option>Dec</select></td><td><select name="year"><option>2000<option>2001<option>2002<option>2003<option>2004<option>2005<option>2006<option>2007</select></td></tr></table></td></tr>');
  }	
  doc.writeln('<tr><td colspan="2"></td></tr>');
  doc.writeln('<tr><td colspan="2"><P>Delivery within 5 working days in Queensland.</P></td></tr>');
  doc.writeln('<tr><td><input type="button" value="Proceed" onClick="parent.validateAndClose(this.form)"</td></tr>');
  doc.writeln('</form></table>');
  doc.writeln(mainFrameFooter());
  //loadForm(doc.order);
  doc.close();
}

function validateAndClose(f) {
  // validate the fields of the form
  // open Missing Information frame if needed with field name
  // write the confirmation page with form including hidden fields for the order
  // that will do the actual mail-to
  saveForm(f);
  if ( validateForm(f) ) {
    refreshConfirmation(f);
  }
}

function saveForm(f) {
  // save the form state to variables
//  titleIndex = f.title.selectedIndex;
//  title = f.title.options[titleIndex].text;
//  firstName = f.firstName.value;
  familyName = f.familyName.value;
  line1 = f.line1.value;
  line2 = f.line2.value;
  town = f.town.value;
  postCode = f.postCode.value;
  if ('Contact Name / Department' != '') country = f.country.value;
  email = f.email.value;
  phone = f.phone.value;
  if (true) {
    cc = f.cc.value;
    cardTypeIndex = f.cardType.selectedIndex;
    cardType = f.cardType.options[cardTypeIndex].text;
    monthIndex = f.month.selectedIndex;
    month = f.month.options[monthIndex].text;
    yearIndex = f.year.selectedIndex;
    year = f.year.options[yearIndex].text;
    startMonthIndex = f.startMonth.selectedIndex;
    startMonth = f.startMonth.options[startMonthIndex].text;
    startYearIndex = f.startYear.selectedIndex;
    startYear = f.startYear.options[startYearIndex].text;
  }
}

function loadForm(f) {
//  f.title.selectedIndex = titleIndex;
//  f.firstName.value = firstName;
  f.familyName.value = familyName;
  f.line1.value = line1;
  f.line2.value = line2;
  f.town.value = town;
  f.postCode.value = postCode;
  if ('Contact Name / Department' != '')   f.country.value = country;
  f.email.value = email;
  f.phone.value = phone;
  f.cc.value = cc;
  f.cardType.selectedIndex = cardTypeIndex;
  f.month.selectedIndex = monthIndex;
  f.year.selectedIndex = yearIndex;
  f.startMonth.selectedIndex = startMonthIndex;
  f.startYear.selectedIndex = startYearIndex;
}

function validateField(field, minSize, longName, extraText) {
  if (field.value.length < minSize) {
    alert("Please complete the  " + longName + " field " + extraText);
    field.focus();
    return true;
  }
  return false;
}

function validateForm(f) {
  // make sure all mandatory fields have something in them
  if (validateField(f.familyName, 2, "Name / Company", "")) { return false;}
  if (validateField(f.line1, 1, "Delivery Address", "")) { return false;}
  if (validateField(f.town, 2, "City / State/ Post Code", "")) { return false;}
  if (validateField(f.postCode, 2, "Order Number", "")) { return false;}
  if ('Contact Name / Department' != '') 
	if (validateField(f.country, 2, "Contact Name / Department", "")) { return false;}
  if (true) {
	if (validateField(f.cc, 12, "Card Number (no spaces)", "(at least 12 digits)")) { return false;}
  }
  return true;
}

function hidden(name,value) {
  return '<input name=\"' + name + '\" type="hidden" value=\"' + value + '\">';
}

function refreshConfirmation(f) {
  // cr = "%0D%0A";
  cr = "\n";
  var doc = parent.frames['mainFrame'].document;
  doc.open();
  doc.writeln('<body bgColor="lightGreen" LINK="blue" ALINK="blue" vlink="blue">');
  doc.writeln('<h1 align="center">Order Confirmation</h1>');
  doc.writeln('<p>Please check your order carefully before clicking on the <I>Send Order</I> button</p>');
  doc.writeln("<form name='confirm' method='POST' action='http://www.shopwriter.co.uk/formmail/SendMail.asp'>");
  doc.writeln("<input type='hidden' name='recipient' value='jock64@bigpond.com'> <table>");
  doc.writeln("<input type='hidden' name='subject' value='ShopWriter Order'> <table>");
  doc.writeln(hidden("email","jock64@bigpond.com"));
  doc.writeln('<tr>' + th('Description') + th('Quantity') + '</tr>');
  for (var i=0; i< basketArray.length; i++) {
    var p = basketArray[i];
    doc.writeln('<tr>')
    doc.writeln(td(p.productDescription));
    doc.writeln(tdr(p.quantity));
    doc.writeln('</tr>');
  }
  doc.writeln('</table>');
  doc.writeln('<BR><BR><P>To be sent to the following address:</P>');
  doc.writeln(familyName + '<BR>');
  doc.writeln(line1 + '<BR>' + line2 +'<BR>' + town + '<BR>' + postCode +'<BR>');
  if ('Contact Name / Department' != '') doc.writeln(country + '<BR><BR>');
  doc.writeln(pp('Total order ' + money(sum)));
  doc.writeln(pp(shippingString));
  // construct hidden form anyway.
  bodyString = familyName + cr + line1 + cr + line2 + cr + town + cr +
			postCode + cr;
  if ('Contact Name / Department' != '') bodyString = bodyString + country + cr;
  bodyString = bodyString + cardType.substring(0,1) + " " + numberAsString(cc) + cr +
			startMonth + '-' + startYear + " to " + month + '-' + year + cr +
			email + cr + phone + cr;

  for (var i=0; i< basketArray.length; i++) {
    var p = basketArray[i];
    bodyString = bodyString + p.quantity + ' ' + p.productCode + ' ' + p.productDescription +
			 ' ' + p.price + ' ' + (p.price * p.quantity) + cr;
  }
  bodyString = bodyString + "total " + sum;
  doc.writeln(hidden("body",urlString(bodyString)));
  doc.writeln(pp('<p>Please check your order carefully before clicking on the <I>Send Order</I> button</p>'));
  doc.writeln('<input type="submit" value="Send Order">');
  doc.writeln('<input type="button" value="Cancel Order" onClick="parent.refreshBasket()">');
  doc.writeln('</form>' + mainFrameFooter());
  doc.close();
}

function urlString(s) 
{
  return s;
}

function numberAsString(n) {
  // encode a number as a string
  var s='';
  for (var i=0; i < n.length; i++) {
    d = n.substring(i,i+1);
    e = digitToString(d);
    if (e != "Z") {
      s = s + e;
    }
    // confirm("s=" + s + " d=" + d + " e=" + e);    
  }
  return s;
}

function digitToString(d) {
  var keyString='encryptdig';
  var n=parseInt(d);
  if ( (n >= 0) && (n <= 9) ) {
    return keyString.substring(n,n+1);
  }
  else {
    return "Z";
  }
}

function buttons() {
  s = '<BODY BGCOLOR="white" LINK="green" ALINK="green" vlink="green"> <form><font color="green"> ' +
	'<H1 align=center>BIG SAVINGS NOW ON LINE @ HANDY HIRE</H1>' +
	'<P align="center">' +
	'' +
	'<table bgcolor="white" CELLSPACING=10 width="80%">';
	if (true)
	{
		s = s +'<tr align="center"><td bgcolor="orange"><font size=5 color="red"><A href="javascript:parent.welcome()" target="mainFrame">Welcome</font></td></tr>';
	}
	s = s + '<tr align="center"><td bgcolor="orange"><font size=5 color="red"><A href="javascript:parent.refreshListString()" target="mainFrame">Products</A></font></td></tr>' +
	'<tr align="center"><td bgcolor="orange"><font size=5 color="red"><A href="javascript:parent.refreshBasketString()" target="mainFrame">Basket</A></font></td></tr>' +
	'<tr align="center"><td bgcolor="orange"><font size=5 color="red"><A href="help.html" target="mainFrame"">Help</A></font></td></tr>' +
	'</table>' +
	'<br>' +
        '<A href="http://www.shopwriter.co.uk" target="openwindow"><img src= "ad.gif"></A>' +
	'</p></font></form></body>';
	return s;
}

function welcome() {
	if (true)
	{
  		return mainFrameHeader() + '<H1 align=center></H1>' +
		'<h1 align="center">Welcome</h1>' + 
		'<P>Welcome to the handyhire shop on line from this site you can purchase at the best competitive prices for selected products directly from this web site, using your credit card.</P><P>Account customers company purchase orders accepted.</P><P>If You Have Any Questions Please Call 0418797172 </P><P></P><P>All Prices Quoted Include G.s.t.</P><P></P><P>PRODUCT RANGE:</P><P></P><P>SAFETY - WELDING - BUILDING - SIGNS - ABRASIVES - DIAMOND BLADES</P><P>AIR TOOLS - HAND TOOLS - PRESSURE WASHERS UNITS - AND LOTS MORE</P><P></P><P></P>' + 
		mainFrameFooter();
	}
	else
	{
		return refreshListString();
	}
}


var help = mainFrameHeader() + '<h1 align="center">Help</h1>' +
	'<h2>Selecting a Product</h2>' +
	'<p>To select a product to buy, go to our Products page and click on the ' +
	'<I>Add to Basket</I> button next to the product. This will add one of the' +
	'items to your shopping basket and take you to the Shopping Basket page.</p>' +
	'<p>If you want to find out more information about the product, click on the' +
	'products name and if there is any further information on this product, ' +
	'it will be displayed.' +
	'<h2>Selecting further products</h2>' +
	'<p>To select other products, turn back to the Products page and click on the' +
	'<I>Add to Basket</I> button next to the product.</p>' +
	'<p>If you select a product that is already in your basket then 1 will be added ' +
	'to the quantity for that item.</p>' +
	'<p>You can also change the quantity of a product simply by changing the number' +
	'in its quantity column on the Shopping Basket page and if you decide that you do' +
	'not want a particular product, you can click on the <I>Cancel this item</I> button</p>' +
	'<h2>Paying for your Goods</h2>'+
	'<p>When you have added all the products that you wish to buy to your shopping ' +
	'basket, you can move on to the <I>Checkout</I> page to arrange payment and ' +
	'delivery. Prior to clicking on the <I>Submit</I> button you can at any time go back ' +
	'to the <I>Products</I> or <I>Shopping Basket</I> pages ' +
	'to change your purchases.</p>' +
	'<p>You must complete all fields marked with a * for the order to be processed.</p>' +
        mainFrameFooter();




