//=====================================================================||
//               NOP Design JavaScript Shopping Cart                   ||
//                                                                     ||
// For more information on SmartSystems, or how NOPDesign can help you ||
// Please visit us on the WWW at http://www.nopdesign.com              ||
//                                                                     ||
// Javascript portions of this shopping cart software are available as ||
// freeware from NOP Design.  You must keep this comment unchanged in  ||
// your code.  For more information contact FreeCart@NopDesign.com.    ||
//                                                                     ||
// JavaScript Shop Module, V.4.4.0                                     ||
//=====================================================================||

//---------------------------------------------------------------------||
//                       Global Options                                ||
//                      ----------------                               ||
// Shopping Cart Options, you can modify these options to change the   ||
// the way the cart functions.                                         ||
//                                                                     ||
// Language Packs                                                      ||
// ==============                                                      ||
// You may include any language pack before nopcart.js in your HTML    ||
// pages to change the language.  Simply include a language pack with  ||
// a script src BEFORE the <SCRIPT SRC="nopcart.js">... line.          ||
//  For example: <SCRIPT SRC="language-en.js"></SCRIPT>                ||
//                                                                     ||
// Options For Everyone:                                               ||
// =====================                                               ||
// * MonetarySymbol: string, the symbol which represents dollars/euro, ||
//   in your locale.                                                   ||
// * DisplayNotice: true/false, controls whether the user is provided  ||
//   with a popup letting them know their product is added to the cart ||
// * DisplayShippingColumn: true/false, controls whether the managecart||
//   and checkout pages display shipping cost column.                  ||
// * DisplayShippingRow: true/false, controls whether the managecart   ||
//   and checkout pages display shipping cost total row.               ||
// * DisplayTaxRow: true/false, controls whether the managecart        ||
//   and checkout pages display tax cost total row.                    ||
// * TaxRate: number, your area's current tax rate, ie: if your tax    ||
//   rate was 7.5%, you would set TaxRate = 0.075                      ||
// * TaxByRegion: true/false, when set to true, the user is prompted   ||
//   with TaxablePrompt to determine if they should be charged tax.    ||
//   In the USA, this is useful to charge tax to those people who live ||
//   in a particular state, but no one else.                           ||
// * TaxPrompt: string, popup message if user has not selected either  ||
//   taxable or nontaxable when TaxByRegion is set to true.            ||
// * TaxablePrompt: string, the message the user is prompted with to   ||
//   select if they are taxable.  If TaxByRegion is set to false, this ||
//   has no effect. Example: 'Arizona Residents'                       ||
// * NonTaxablePrompt: string, same as above, but the choice for non-  ||
//   taxable people.  Example: 'Other States'                          ||
// * MinimumOrder: number, the minium dollar amount that must be       ||
//   purchased before a user is allowed to checkout.  Set to 0.00      ||
//   to disable.                                                       ||
// * MinimumOrderPrompt: string, Message to prompt users with when     ||
//   they have not met the minimum order amount.                       ||
//                                                                     ||
// Payment Processor Options:                                          ||
// ==========================                                          ||
// * PaymentProcessor: string, the two digit payment processor code    ||
//   for support payment processor gateways.  Setting this field to    ||
//   anything other than an empty string will override your OutputItem ||
//   settings -- so please be careful when receiving any form data.    ||
//   Support payment processor gateways are:                           ||
//    * Authorize.net (an)                                             ||
//    * Worldpay      (wp)                                             ||
//    * LinkPoint     (lp)
//                                                                     ||
// Options For Programmers:                                            ||
// ========================                                            ||
// * OutputItem<..>: string, the name of the pair value passed at      ||
//   checkouttime.  Change these only if you are connecting to a CGI   ||
//   script and need other field names, or are using a secure service  ||
//   that requires specific field names.                               ||
// * AppendItemNumToOutput: true/false, if set to true, the number of  ||
//   each ordered item will be appended to the output string.  For     ||
//   example if OutputItemId is 'ID_' and this is set to true, the     ||
//   output field name will be 'ID_1', 'ID_2' ... for each item.       ||
// * HiddenFieldsToCheckout: true/false, if set to true, hidden fields ||
//   for the cart items will be passed TO the checkout page, from the  ||
//   ManageCart page.  This is set to true for CGI/PHP/Script based    ||
//   checkout pages, but should be left false if you are using an      ||
//   HTML/Javascript Checkout Page. Hidden fields will ALWAYS be       ||
//   passed FROM the checkout page to the Checkout CGI/PHP/ASP/Script  ||
//---------------------------------------------------------------------||

//Options for Everyone:
MonetarySymbol        = '$';
DisplayNotice         = true;
DisplayShippingColumn = false;
DisplayShippingRow    = false;
DisplayTaxRow         = false;
TaxRate               = 0.125;
TaxByRegion           = false;
TaxPrompt             = '';
TaxablePrompt         = '';
NonTaxablePrompt      = 'All prices are in NZ$, and include GST';
MinimumOrder          = 0.00;
MinimumOrderPrompt    = 'Your order is below our minimum order of $' + moneyFormat(MinimumOrder) + ', please order more before checking out.';

//Payment Processor Options:
PaymentProcessor      = '';

//Options for Programmers:
OutputItemId          = 'ID_';
OutputItemQuantity    = 'QUANTITY_';
OutputItemPrice       = 'PRICE_';
OutputItemName        = 'NAME_';
OutputItemSize        = 'SIZE_';
OutputItemShipping    = 'SHIPPING_';
OutputItemLtotal      = 'LINETOTAL_';
OutputItemAddtlInfo   = 'ADDTLINFO_';
OutputOrderSubtotal   = 'SUBTOTAL';
OutputOrderShipping   = 'SHIPPING';
OutputOrderTax        = 'GST';
OutputOrderTotal      = 'TOTAL';
OutputFreightArea     = 'FREIGHTAREA';
AppendItemNumToOutput = true;
HiddenFieldsToCheckout = true;


//=====================================================================||
//---------------------------------------------------------------------||
//    YOU DO NOT NEED TO MAKE ANY MODIFICATIONS BELOW THIS LINE        ||
//---------------------------------------------------------------------||
//=====================================================================||


//---------------------------------------------------------------------||
//                      Language Strings                               ||
//                     ------------------                              ||
// These strings will not be used unless you have not included a       ||
// language pack already.  You should NOT modify these, but instead    ||
// modify the strings in language-**.js where ** is the language pack  ||
// you are using.                                                      ||
//---------------------------------------------------------------------||
if ( !bLanguageDefined ) {
   strSorry  = "I'm Sorry, your cart is full, please proceed to checkout.";
   strAdded  = " has been added to your shopping cart. To proceed to Manage your current shopping cart please press OK, else press Canel to continue Shopping.";
   strRemove = "Click 'Ok' to remove this product from your shopping cart.";
   strILabel = "Product Id";
   strDLabel = "Product Name/Description";
   strQLabel = "Quantity";
   strPLabel = "Price";
   strLLabel = "Total";
   strSLabel = "Shipping";
   strRLabel = "Remove From Cart";
   strRButton= "Remove";
   strSUB    = "SUBTOTAL";
   strSHIP   = "SHIPPING";
   strTAX    = "TAX";
   strGST    = "TAX";
   strTOT    = "TOTAL";
   strErrQty = "Invalid Quantity.";
   strNewQty = 'Please enter new quantity:';
   bLanguageDefined = true;
}

//---------------------------------------------------------------------||
// FUNCTION:    getTimeZone                                            ||
// PARAMETERS:  N/A                                                    ||
// RETURNS:     Number of hours from GMT                               ||
// PURPOSE:     Check user (browser) location in NZ                    ||
//---------------------------------------------------------------------||
function getTimeZone()
{
        var d=new Date()
        var gmtHours = -d.getTimezoneOffset() /60;
        // alert("The local time zone is: GMT " + gmtHours);
        return gmtHours;
}


//---------------------------------------------------------------------||
// FUNCTION:    CKquantity                                             ||
// PARAMETERS:  Quantity to                                            ||
// RETURNS:     Quantity as a number, and possible alert               ||
// PURPOSE:     Make sure quantity is represented as a number          ||
//---------------------------------------------------------------------||
function CKquantity(checkString) {
   var strNewQuantity = "";

   for ( i = 0; i < checkString.length; i++ ) {
      ch = checkString.substring(i, i+1);
      if ( (ch >= "0" && ch <= "9") || (ch == '.') )
         strNewQuantity += ch;
   }

   if ( strNewQuantity.length < 1 )
      strNewQuantity = "1";

   return(strNewQuantity);
}


//---------------------------------------------------------------------||
// FUNCTION:    AddToCart                                              ||
// PARAMETERS:  Form Object                                            ||
// RETURNS:     Cookie to user's browser, with prompt                  ||
// PURPOSE:     Adds a product to the user's shopping cart             ||
//---------------------------------------------------------------------||
function AddToCart(thisForm) {
	var iNumberOrdered = 0;
	var bAlreadyInCart = false;
	var notice = "";
	iNumberOrdered = GetCookie("NumberOrdered");


	if ( iNumberOrdered == null )
		iNumberOrdered = 0;

	if ( thisForm.CODE == null )
		strID_NUM    = "";
	else
		strCODE    = thisForm.CODE.value;

	if ( thisForm.NAME == null )
		strNAME      = "";
	else
		strNAME      = thisForm.NAME.value;

	if ( thisForm.QUANTITY == null )
		strQUANTITY  = "1";
	else
		strQUANTITY  = thisForm.QUANTITY.value;

	if ( thisForm.PRICE_1 == null )
		strPRICE_1      = "";
	else
		strPRICE_1      = thisForm.PRICE_1.value;

	if ( thisForm.PRICE_2 == null )
		strPRICE_2      = "";
	else
		strPRICE_2      = thisForm.PRICE_2.value;

	if ( thisForm.PRICE_3 == null )
		strPRICE_3      = "";
	else
		strPRICE_3      = thisForm.PRICE_3.value;

	if ( thisForm.PRICE_4 == null )
		strPRICE_4      = "";
	else
		strPRICE_4      = thisForm.PRICE_4.value;

	if ( thisForm.PRICE_5 == null )
		strPRICE_5      = "";
	else
		strPRICE_5      = thisForm.PRICE_5.value;

	if ( thisForm.SIZE == null ) {
		strSIZE = "";
		strPRICE = strPRICE_1;
		strPOSITION = "1";
	} else {
		X = RadioChecked(thisForm.SIZE);
		Y = X.split("~");
		strPOSITION = Y[0]; strSIZE = Y[1];
		strPRICE = eval("strPRICE_" + strPOSITION); 
	}

	//Is this product already in the cart?  If so, increment quantity instead of adding another.
	for ( i = 1; i <= iNumberOrdered; i++ ) {
		NewOrder = "Order." + i;
		database = "";
		database = GetCookie(NewOrder);

		Token0 = database.indexOf("|", 0);		// CODE
		Token1 = database.indexOf("|", Token0+1);		// NAME
		Token2 = database.indexOf("|", Token1+1);		// QUANTITY
		Token3 = database.indexOf("|", Token2+1);		// PRICE
		Token4 = database.indexOf("|", Token3+1);		// SIZE

		fields = new Array;
		fields[0] = database.substring( 0, Token0 );		// CODE
		fields[1] = database.substring( Token0+1, Token1 );	// NAME
		fields[2] = database.substring( Token1+1, Token2 );	// QUANTITY
		fields[3] = database.substring( Token2+1, Token3 );	// PRICE
		fields[4] = database.substring( Token3+1, database.length ); // SIZE
	
		if ( fields[0] == strCODE   &&
			fields[1] == strNAME   &&
			fields[3] == strPRICE  &&
			fields[4] == strSIZE
		) {
			bAlreadyInCart = true;
			dbUpdatedOrder = strCODE			+ "|" +
				strNAME					+ "|" +
				(parseInt(strQUANTITY)+parseInt(fields[2])) + "|" +
				strPRICE				+ "|" +
				strSIZE;

			strNewOrder = "Order." + i;
			DeleteCookie(strNewOrder, "/");
			SetCookie(strNewOrder, dbUpdatedOrder, null, "/");
	
			Xnotice = "";
			if ( strSIZE != ""  )
				Xnotice = strSIZE;
			notice = strQUANTITY + " x " + Xnotice + " - " + strNAME + strAdded;
         		break;
		}
	}

	if ( !bAlreadyInCart ) {
		iNumberOrdered++;

		if ( iNumberOrdered > 12 ) {
			alert( strSorry );
			location.replace('cart.php');
			notice = "Please proceed to Checkout. You can raise another order for additional products";
		} else {
			dbUpdatedOrder = strCODE	+ "|" + 
				strNAME			+ "|" +
				strQUANTITY		+ "|" +
				strPRICE		+ "|" +
				strSIZE;

			strNewOrder = "Order." + iNumberOrdered;
			SetCookie(strNewOrder, dbUpdatedOrder, null, "/");
			SetCookie("NumberOrdered", iNumberOrdered, null, "/");

			Xnotice = "";
			if ( strSIZE != ""  )
				Xnotice = strSIZE;
			notice = strQUANTITY + " x " + Xnotice + " - " + strNAME + strAdded;
		}
	}

	if ( DisplayNotice )
		alert(notice);
}


//---------------------------------------------------------------------||
// FUNCTION:    getCookieVal                                           ||
// PARAMETERS:  offset                                                 ||
// RETURNS:     URL unescaped Cookie Value                             ||
// PURPOSE:     Get a specific value from a cookie                     ||
//---------------------------------------------------------------------||
function getCookieVal (offset) {
   var endstr = document.cookie.indexOf (";", offset);

   if ( endstr == -1 )
      endstr = document.cookie.length;
   return(unescape(document.cookie.substring(offset, endstr)));
}


//---------------------------------------------------------------------||
// FUNCTION:    FixCookieDate                                          ||
// PARAMETERS:  date                                                   ||
// RETURNS:     date                                                   ||
// PURPOSE:     Fixes cookie date, stores back in date                 ||
//---------------------------------------------------------------------||
function FixCookieDate (date) {
   var base = new Date(0);
   var skew = base.getTime();

   date.setTime (date.getTime() - skew);
}


//---------------------------------------------------------------------||
// FUNCTION:    GetCookie                                              ||
// PARAMETERS:  Name                                                   ||
// RETURNS:     Value in Cookie                                        ||
// PURPOSE:     Retrieves cookie from users browser                    ||
//---------------------------------------------------------------------||
function GetCookie (name) {
   var arg = name + "=";
   var alen = arg.length;
   var clen = document.cookie.length;
   var i = 0;

   while ( i < clen ) {
      var j = i + alen;
      if ( document.cookie.substring(i, j) == arg ) return(getCookieVal (j));
      i = document.cookie.indexOf(" ", i) + 1;
      if ( i == 0 ) break;
   }

   return(null);
}


//---------------------------------------------------------------------||
// FUNCTION:    SetCookie                                              ||
// PARAMETERS:  name, value, expiration date, path, domain, security   ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Stores a cookie in the users browser                   ||
//---------------------------------------------------------------------||
function SetCookie (name,value,expires,path,domain,secure) {
   document.cookie = name + "=" + escape (value) +
                     ((expires) ? "; expires=" + expires.toGMTString() : "") +
                     ((path) ? "; path=" + path : "") +
                     ((domain) ? "; domain=" + domain : "") +
                     ((secure) ? "; secure" : "");
}


//---------------------------------------------------------------------||
// FUNCTION:    DeleteCookie                                           ||
// PARAMETERS:  Cookie name, path, domain                              ||
// RETURNS:     null                                                   ||
// PURPOSE:     Removes a cookie from users browser.                   ||
//---------------------------------------------------------------------||
function DeleteCookie (name,path,domain) {
   if ( GetCookie(name) ) {
      document.cookie = name + "=" +
                        ((path) ? "; path=" + path : "") +
                        ((domain) ? "; domain=" + domain : "") +
                        "; expires=Thu, 01-Jan-70 00:00:01 GMT";
   }
}


//---------------------------------------------------------------------||
// FUNCTION:    MoneyFormat                                            ||
// PARAMETERS:  Number to be formatted                                 ||
// RETURNS:     Formatted Number                                       ||
// PURPOSE:     Reformats Dollar Amount to #.## format                 ||
//---------------------------------------------------------------------||
function moneyFormat(input) {
   var dollars = Math.floor(input);
   var tmp = new String(input);

   for ( var decimalAt = 0; decimalAt < tmp.length; decimalAt++ ) {
      if ( tmp.charAt(decimalAt)=="." )
         break;
   }

   var cents  = "" + Math.round(input * 100);
   cents = cents.substring(cents.length-2, cents.length)
           dollars += ((tmp.charAt(decimalAt+2)=="9")&&(cents=="00"))? 1 : 0;

   if ( cents == "0" )
      cents = "00";

   return(dollars + "." + cents);
}


//---------------------------------------------------------------------||
// FUNCTION:    RemoveFromCart                                         ||
// PARAMETERS:  Order Number to Remove                                 ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Removes an item from a users shopping cart             ||
//---------------------------------------------------------------------||
function RemoveFromCart(RemOrder) {
   if ( confirm( strRemove ) ) {
      NumberOrdered = GetCookie("NumberOrdered");
      for ( i=RemOrder; i < NumberOrdered; i++ ) {
         NewOrder1 = "Order." + (i+1);
         NewOrder2 = "Order." + (i);
         database = GetCookie(NewOrder1);
         SetCookie (NewOrder2, database, null, "/");
      }
      NewOrder = "Order." + NumberOrdered;
      SetCookie ("NumberOrdered", NumberOrdered-1, null, "/");
      DeleteCookie(NewOrder, "/");
      location.href=location.href;
   }
}

//---------------------------------------------------------------------||
// FUNCTION:    CustomerPickup                                         ||
// PARAMETERS:  None                                                   ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Removes Freight from a users shopping cart             ||
//---------------------------------------------------------------------||
function CustomerPickup() {
	SetCookie ("CustomerPickup", "true", null, "/");
	location.href=location.href;
}

//---------------------------------------------------------------------||
// FUNCTION:    setFreightArea                                         ||
// PARAMETERS:  Freight Area                                           ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Sets Freight Area cookie                               ||
//---------------------------------------------------------------------||
function setFreightArea(Area) {
	SetCookie ("freightArea", Area, null, "/");
	location.href=location.href;
}

//---------------------------------------------------------------------||
// FUNCTION:    FreightGoods                                           ||
// PARAMETERS:  None                                                   ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Negates Customer Pickup                                ||
//---------------------------------------------------------------------||
function FreightGoods() {
	DeleteCookie ("CustomerPickup", "/");
	location.href=location.href;
}


//---------------------------------------------------------------------||
// FUNCTION:    ChangeQuantity                                         ||
// PARAMETERS:  Order Number to Change Quantity                        ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Changes quantity of an item in the shopping cart       ||
//---------------------------------------------------------------------||
function ChangeQuantity(OrderItem,NewQuantity) {
	if ( isNaN(NewQuantity) ) {
		alert( strErrQty );
	} else {
		NewOrder = "Order." + OrderItem;
		database = "";
		database = GetCookie(NewOrder);

		Token0 = database.indexOf("|", 0);			// CODE
		Token1 = database.indexOf("|", Token0+1);		// NAME
		Token2 = database.indexOf("|", Token1+1);		// QUANTITY
		Token3 = database.indexOf("|", Token2+1);		// PRICE
		Token4 = database.indexOf("|", Token3+1);		// SIZE
	
		fields = new Array;
		fields[0] = database.substring( 0, Token0 );		// CODE
		fields[1] = database.substring( Token0+1, Token1 );	// NAME
		fields[2] = database.substring( Token1+1, Token2 );	// QUANTITY
		fields[3] = database.substring( Token2+1, Token3 );	// PRICE
		fields[4] = database.substring( Token3+1, database.length ); // SIZE
		

         	dbUpdatedOrder = fields[0]      + "|" +
                          fields[1]      + "|" +
                          NewQuantity    + "|" +
                          fields[3]      + "|" +
                          fields[4];
		strNewOrder = "Order." + OrderItem;
		DeleteCookie(strNewOrder, "/");
		SetCookie(strNewOrder, dbUpdatedOrder, null, "/");
		location.href=location.href;      
	}
}


//---------------------------------------------------------------------||
// FUNCTION:    GetFromCart                                            ||
// PARAMETERS:  Null                                                   ||
// RETURNS:     Product Table Written to Document                      ||
// PURPOSE:     Draws current cart product table on HTML page          ||
//              **DEPRECATED FUNCTION, USE ManageCart or Checkout**    ||
//---------------------------------------------------------------------||
function GetFromCart( fShipping ) {
   ManageCart( );
}


//---------------------------------------------------------------------||
// FUNCTION:    RadioChecked                                           ||
// PARAMETERS:  Radio button to check                                  ||
// RETURNS:     True if a radio has been checked                       ||
// PURPOSE:     Form fillin validation                                 ||
//---------------------------------------------------------------------||
function RadioChecked( radiobutton ) {
   var bChecked = false;
   var bValue = "";
   var bPosition = "";
   var rlen = radiobutton.length;
   for ( i=0; i < rlen; i++ ) {
      if ( radiobutton[i].checked ) {
        bChecked = true;
	bPosition = i + 1;
	bValue = bPosition + "~" + radiobutton[i].value ;
	break;
	}
   }    
   return bValue;
} 


//---------------------------------------------------------------------||
// FUNCTION:    QueryString                                            ||
// PARAMETERS:  Key to read                                            ||
// RETURNS:     value of key                                           ||
// PURPOSE:     Read data passed in via GET mode                       ||
//---------------------------------------------------------------------||
QueryString.keys = new Array();
QueryString.values = new Array();
function QueryString(key) {
   var value = null;
   for (var i=0;i<QueryString.keys.length;i++) {
      if (QueryString.keys[i]==key) {
         value = QueryString.values[i];
         break;
      }
   }
   return value;
} 

//---------------------------------------------------------------------||
// FUNCTION:    QueryString_Parse                                      ||
// PARAMETERS:  (URL string)                                           ||
// RETURNS:     null                                                   ||
// PURPOSE:     Parses query string data, must be called before Q.S.   ||
//---------------------------------------------------------------------||
function QueryString_Parse() {
   var query = window.location.search.substring(1);
   var pairs = query.split("&"); for (var i=0;i<pairs.length;i++) {
      var pos = pairs[i].indexOf('=');
      if (pos >= 0) {
         var argname = pairs[i].substring(0,pos);
         var value = pairs[i].substring(pos+1);
         QueryString.keys[QueryString.keys.length] = argname;
         QueryString.values[QueryString.values.length] = value;
      }
   }
}


//---------------------------------------------------------------------||
// FUNCTION:    ManageCart                                             ||
// PARAMETERS:  Null                                                   ||
// RETURNS:     Product Table Written to Document                      ||
// PURPOSE:     Draws current cart product table on HTML page          ||
//---------------------------------------------------------------------||
function ManageCart( ) {
	var iNumberOrdered = 0;    //Number of products ordered
	var lTotal         = 0;    //Line Total cost of order
	var fTotal         = 0;    //Total cost of order
	var fTax           = 0;    //Tax amount
	var fShipping      = 0;    //Shipping amount
	var strTotal       = "";   //Total cost formatted as money
	var strTax         = "";   //Total tax formatted as money
	var strShipping    = "";   //Total shipping formatted as money
	var strOutput      = "";   //String to be written to page
	var bDisplay       = true; //Whether to write string to the page (here for programmers)
	var timeZoneHours  = 0;
	var userOutsideNZ  = "false";
	var customerPickup = "false";
	var ans            = false;

	iNumberOrdered = GetCookie("NumberOrdered");
	if ( iNumberOrdered == null )
		iNumberOrdered = 0;

	customerPickup = GetCookie("CustomerPickup");
	if ( customerPickup == null )
		customerPickup = "false";

	userOutsideNZ = GetCookie("userOutsideNZ");
	if ( userOutsideNZ == null ) {
		timeZoneHours = getTimeZone();
		if ( timeZoneHours < 12 ) { 
			ans = confirm("You appear to be outside of New Zealand, please confirm.");
		}
		if ( ans ) { userOutsideNZ == "true" } else { userOutsideNZ == "false" }
		SetCookie("userOutsideNZ", ans, null, "/");
	}

	if ( bDisplay )
		strOutput = "<table class=\"nopcart\"><tr>" +
		"<td class=\"nopheader\"><b>"+strDLabel+"</b></td>" +
		"<td class=\"nopheader\"><b>"+strSZLabel+"</b></td>" +
		"<td class=\"nopheader\"><b>"+strQLabel+"</b></td>" +
		"<td class=\"nopheader\"><b>"+strPLabel+"</b></td>" +
		"<td class=\"nopheader\"><b>"+strLLabel+"</b></td>" +
		(DisplayShippingColumn?"<td class=\"nopheader\"><b>"+strSLabel+"</b></td>":"") +
		"<td class=\"nopheader\"><b>"+strRLabel+"</b></td></tr>";

	if ( iNumberOrdered == 0 ) {
		strOutput += "<tr><td colspan=6 class=\"nopentry\"><center><br /><b>Your cart is empty</b><br /><br /></center></td></tr>";
	}

	for ( i = 1; i <= iNumberOrdered; i++ ) {
		NewOrder = "Order." + i;
		database = "";
		lTotal = 0;						//Line Total
		database = GetCookie(NewOrder);

		Token0 = database.indexOf("|", 0);			// CODE
		Token1 = database.indexOf("|", Token0+1);		// NAME
		Token2 = database.indexOf("|", Token1+1);		// QUANTITY
		Token3 = database.indexOf("|", Token2+1);		// PRICE
		Token4 = database.indexOf("|", Token3+1);		// SIZE

		fields = new Array;
		fields[0] = database.substring( 0, Token0 );		// CODE
		fields[1] = database.substring( Token0+1, Token1 );	// NAME
		fields[2] = database.substring( Token1+1, Token2 );	// QUANTITY
		fields[3] = database.substring( Token2+1, Token3 );	// PRICE
		fields[4] = database.substring( Token3+1, database.length ); // SIZE
	

		lTotal     += (parseInt(fields[2]) * parseFloat(fields[3]) );	//Line Total
		fTotal     += (parseInt(fields[2]) * parseFloat(fields[3]) );	//Running Total
		// fTax        = (fTotal * TaxRate);				//Running Tax
		strTotal    = moneyFormat(fTotal);				//Running total string
		// strTax      = moneyFormat(fTax);				//Running tax string

		if ( bDisplay ) {
			strOutput += "<tr>";
			strOutput += "<td class=\"nopentry\">"  + fields[1] + "</td>";		// Name
			strOutput += "<td class=\"nopentry\">"  + fields[4] + "</td>";		// Size

			strOutput += "<td class=\"nopentry\"><input type=text name=Q size=2";
			strOutput += " value=\"" + fields[2] + "\" onChange=\"ChangeQuantity("+i+", this.value);\"></td>";

			strOutput += "<td class=\"nopentry\">"+ MonetarySymbol + moneyFormat(fields[3]) + "</td>";
			strOutput += "<td class=\"nopentry\">"+ MonetarySymbol + moneyFormat(lTotal) + "</td>";

			strOutput += "<td class=\"nopentry\" align=center><input type=button";
			// strOutput += " value=\" "+strRButton+" \" onClick=\"RemoveFromCart("+i+")\" class=\"nopbutton button\"";
			strOutput += " value=\"\" onClick=\"RemoveFromCart("+i+")\" class=\"nopbutton button\"";
			strOutput += " style=\"background-image:url('/images/removefromCart.png'); width:107px;height:23px ;display:block;\"></td></tr>";
		}

		if ( AppendItemNumToOutput ) {
			strFooter = i;
		} else {
			strFooter = "";
		}
		if ( HiddenFieldsToCheckout ) {
			// Field 0 Item_id
			// Field 1 Name
			// Field 2 Quanity
			// Field 3 Price
			// Field 4 Size
			strOutput += "<input type=hidden name=\"" + OutputItemId        + strFooter + "\" value=\"" + fields[0] + "\">";
			strOutput += "<input type=hidden name=\"" + OutputItemName      + strFooter + "\" value=\"" + fields[1] + "\">";
			strOutput += "<input type=hidden name=\"" + OutputItemQuantity  + strFooter + "\" value=\"" + fields[2] + "\">";
			strOutput += "<input type=hidden name=\"" + OutputItemPrice     + strFooter + "\" value=\"" + fields[3] + "\">";
			strOutput += "<input type=hidden name=\"" + OutputItemSize      + strFooter + "\" value=\"" + fields[4] + "\">";
			strOutput += "<input type=hidden name=\"" + OutputItemLtotal    + strFooter + "\" value=\"" + moneyFormat(lTotal) + "\">";
		}

	}

	// Totals

/*
	// Shipping
	if ( userOutsideNZ == "true" ) {
		strShipping = "TBA";
	} else { 
		if ( customerPickup == "true" ) {
			strShipping = "N/A"; 
		} else {
   			if ( iNumberOrdered == 0 ) {
				fShipping = 0;
			} else {
				if ( freightArea == "Auckland" )
					fShipping += 7.00;
				if ( freightArea == "NorthIsland" )
					fShipping += 12.00;
				if ( freightArea == "SouthIsland" )
					fShipping += 15.00;
			}
		}
		strShipping = moneyFormat(fShipping);
	}
*/

	if ( bDisplay ) {
		strOutput += "<tr><td class=\"noptotal\" colspan=5>&nbsp</td></tr>";
		strOutput += "<tr><td class=\"noptotal\" colspan=4><b>"+strSUB+"</b></td>";
		strOutput += "<td class=\"noptotal\" colspan=1><b>" + MonetarySymbol + strTotal + "</b></td>";
		strOutput += "</tr>";

		if ( DisplayShippingRow ) {
			strOutput += "<tr><td class=\"noptotal\" colspan=5><b>"+strSHIP+"</b></td>";
			if ( userOutsideNZ == "true" || customerPickup == "true" ) {
				strOutput += "<td class=\"noptotal\" colspan=1><span style=\"color: red;\">" + strShipping + "</span></td>";
			} else {
				strOutput += "<td class=\"noptotal\" colspan=1><b>" + MonetarySymbol + strShipping + "</b></td>";
			}
			strOutput += "</tr>";
		}

		//GST Content
		if ( userOutsideNZ == "true" ) {
			strOutput += "<tr><td class=\"noptotal\" colspan=5>&nbsp</td></tr>";
		} else {
			strOutput += "<tr><td class=\"noptotal\" colspan=4><b>"+strGST+"</b></td>";
			gstTotal = (fTotal + fShipping) * TaxRate;
			strOutput += "<td class=\"noptotal\" colspan=1><b>" + MonetarySymbol + moneyFormat(gstTotal) + "</b></td>";
			strOutput += "</tr>";
		}
	
		strOutput += "<tr><td class=\"noptotal\" colspan=4><b>"+strTOT+"</b></td>";
		strOutput += "<td class=\"noptotal\" colspan=1><b>" + MonetarySymbol + moneyFormat((fTotal + fShipping + gstTotal)) + "</b></td>";
		strOutput += "</tr>";

		strOutput += "</table>";

		if ( HiddenFieldsToCheckout ) {
			strOutput += "<input type=hidden name=\""+OutputOrderSubtotal+"\" value=\""+ MonetarySymbol + strTotal + "\">";
			strOutput += "<input type=hidden name=\""+OutputOrderShipping+"\" value=\""+ MonetarySymbol + strShipping + "\">";
			strOutput += "<input type=hidden name=\""+OutputOrderTax+"\"      value=\""+ MonetarySymbol + strTax + "\">";
			strOutput += "<input type=hidden name=\""+OutputOrderTotal+"\"    value=\""+ MonetarySymbol + moneyFormat((fTotal + fShipping + fTax)) + "\">";
		}

		if ( userOutsideNZ == "true" ) {
			strOutput += "<p>Freight Charges: Customers outside New Zealand will be contacted to advise Freight charges pertaining to this Order. </p>"
		} else {
			strOutput += "<p>All prices are in NZ$, and EXCLUDE GST.</p>"
			strOutput += "<p>Freight charges - minimum $5.50 per 25Kg within Auckland City (freight charges will be confirmed by email on acceptance of order.)</p>"
		/*	
			if ( customerPickup == "false" ) {
				strOutput += "<p>You can choose to pick up the goods by clicking &nbsp<input type=\"button\" value=\" Here \" class=\"nopentry\" align=\"center\" onClick=\"CustomerPickup()\">";
			} else {
				strOutput += "<p>Customer Pick Up chosen. You can negate this by clicking &nbsp<input type=\"button\" value=\" Here \" class=\"nopentry\" align=\"center\" onClick=\"FreightGoods()\">";
			}
		*/
		}


	}

	g_TotalCost = (fTotal + fShipping + fTax);
	if ( MinimumOrder >= 0.00 ) {
		if ( g_TotalCost < MinimumOrder) {
			alert( MinimumOrderPrompt );
		} else {
			if ( g_TotalCost > 0) {
				strOutput += "<p class=\"center\" style=\"font-size: 10pt\">";
				strOutput += "<a href=\"checkout.php\" class=\"button\" title=\"Check Out\"";
				strOutput += " style=\"background-image:url('/images/proceedtoCheckout.png'); width:166px;height:38px ;display:block;\">";
				strOutput += "</a>";
				strOutput += "</p>";
			}
		}
   	}

	document.write(strOutput);
	document.close();
}

//---------------------------------------------------------------------||
// FUNCTION:    ValidateCart                                           ||
// PARAMETERS:  Form to validate                                       ||
// RETURNS:     true/false                                             ||
// PURPOSE:     Validates the managecart form                          ||
//---------------------------------------------------------------------||
var g_TotalCost = 0;
function ValidateCart( theForm ) {
   if ( TaxByRegion ) {
      if ( !RadioChecked(eval("theForm."+OutputOrderTax)) ) {
         alert( TaxPrompt );
         return false;
      }
   }

   if ( MinimumOrder >= 0.01 ) {
      if ( g_TotalCost < MinimumOrder ) {
         alert( MinimumOrderPrompt );
         return false;
      }
   }

   return true;
}

//---------------------------------------------------------------------||
// FUNCTION:    CheckoutCart                                           ||
// PARAMETERS:  Null                                                   ||
// RETURNS:     Product Table Written to Document                      ||
// PURPOSE:     Draws current cart product table on HTML page for      ||
//              checkout.                                              ||
//---------------------------------------------------------------------||
function CheckoutCart( ) {
var iNumberOrdered = 0;    //Number of products ordered
var lTotal         = 0;    //Line Total cost of order
var fTotal         = 0;    //Total cost of order
var fTax           = 0;    //Tax amount
var fShipping      = 0;    //Shipping amount
var strTotal       = "";   //Total cost formatted as money
var strTax         = "";   //Total tax formatted as money
var strShipping    = "";   //Total shipping formatted as money
var strOutput      = "";   //String to be written to page
var bDisplay       = true; //Whether to write string to the page (here for programmers)
var strPP          = "";   //Payment Processor Description Field
var timeZoneHours  = 0;
var userOutsideNZ  = "false";
var ans            = false;
var freightArea    = "";

	iNumberOrdered = GetCookie("NumberOrdered");
	if ( iNumberOrdered == null )
		iNumberOrdered = 0;

	customerPickup = GetCookie("CustomerPickup");

	userOutsideNZ = GetCookie("userOutsideNZ");
	if ( userOutsideNZ == null ) {
		timeZoneHours = getTimeZone();
	if ( timeZoneHours < 12 ) { 
		ans = confirm("You appear to be outside of New Zealand, please confirm.");
	}
	if ( ans ) { userOutsideNZ = "true" } else { userOutsideNZ = "false" }
		SetCookie("userOutsideNZ", ans, null, "/");
	}

	if ( bDisplay )
		strOutput = "<table class=\"nopcart\"><tr>" +
		"<td class=\"nopheader\"><b>"+strDLabel+"</b></td>" +
		"<td class=\"nopheader\"><b>"+strSZLabel+"</b></td>" +
		"<td class=\"nopheader\"><b>"+strQLabel+"</b></td>" +
		"<td class=\"nopheader\"><b>"+strPLabel+"</b></td>" +
		"<td class=\"nopheader\"><b>"+strLLabel+"</b></td>" +
		(DisplayShippingColumn?"<td class=\"nopheader\"><b>"+strSLabel+"</b></td>":"") +
		"<td class=\"nopheader\"><b>"+strRLabel+"</b></td></tr>";


	if ( iNumberOrdered == 0 ) {
		strOutput += "<tr><td colspan=6 class=\"nopentry\"><center><br /><b>Your cart is empty</b><br /><br /></center></td></tr>";
	}

	for ( i = 1; i <= iNumberOrdered; i++ ) {
		NewOrder = "Order." + i;
		lTotal = 0;
		database = "";
		database = GetCookie(NewOrder);

		Token0 = database.indexOf("|", 0);			// CODE
		Token1 = database.indexOf("|", Token0+1);		// NAME
		Token2 = database.indexOf("|", Token1+1);		// QUANTITY
		Token3 = database.indexOf("|", Token2+1);		// PRICE
		Token4 = database.indexOf("|", Token3+1);		// SIZE

		fields = new Array;
		fields[0] = database.substring( 0, Token0 );		// CODE
		fields[1] = database.substring( Token0+1, Token1 );	// NAME
		fields[2] = database.substring( Token1+1, Token2 );	// QUANTITY
		fields[3] = database.substring( Token2+1, Token3 );	// PRICE
		fields[4] = database.substring( Token3+1, database.length ); // SIZE
	
		lTotal     += (parseInt(fields[2]) * parseFloat(fields[3]) );
		fTotal     += (parseInt(fields[2]) * parseFloat(fields[3]) );
		strTotal    = moneyFormat(fTotal);
		fTax        = (fTotal * TaxRate);
		strTax      = moneyFormat(fTax);

		if ( bDisplay ) {
			strOutput += "<tr>";
			strOutput += "<td class=\"nopentry\">"  + fields[1] + "</td>";		// Name
			strOutput += "<td class=\"nopentry\">"  + fields[4] + "</td>";		// Size
			strOutput += "<td class=\"nopentry\">" + fields[2] + "</td>";		// Quantity
			strOutput += "<td class=\"nopentry\">"+ MonetarySymbol + moneyFormat(fields[3]) + "</td>"; // Price
			strOutput += "<td class=\"nopentry\">"+ MonetarySymbol + moneyFormat(lTotal) + "</td>";	// Line Total
         		strOutput += "</tr>";
		}

		if ( AppendItemNumToOutput ) {
			strFooter = i;
		} else {
			strFooter = "";
		}


		if ( PaymentProcessor != '' ) {
		//Process description field for payment processors instead of hidden values.
		//Format Description of product as:
		// ID, Name, Qty X
			strPP += fields[0] + ", " + fields[3];
			if ( fields[5] != "" )
				strPP += " - " + fields[5];
			strPP += ", Qty. " + fields[1] + "\n";
		} else {
		// Field 0 Item_id
		// Field 1 Name
		// Field 2 Quanity
		// Field 3 Price
		// Field 4 Size
			strOutput += "<input type=hidden name=\"" + OutputItemId       + strFooter + "\" value=\"" + fields[0] + "\">";
			strOutput += "<input type=hidden name=\"" + OutputItemName     + strFooter + "\" value=\"" + fields[1] + "\">";
			strOutput += "<input type=hidden name=\"" + OutputItemQuantity + strFooter + "\" value=\"" + fields[2] + "\">";
			strOutput += "<input type=hidden name=\"" + OutputItemPrice    + strFooter + "\" value=\"" + fields[3] + "\">";
			strOutput += "<input type=hidden name=\"" + OutputItemSize     + strFooter + "\" value=\"" + fields[4] + "\">";
			strOutput += "<input type=hidden name=\"" + OutputItemLtotal   + strFooter + "\" value=\"" + moneyFormat(lTotal) + "\">";
		} 

	}	// End of Line Items



	// Sub Totals
	g_TotalCost = (fTotal + fShipping + fTax);
	if ( MinimumOrder >= 0.01 ) {
		if ( g_TotalCost < MinimumOrder ) {
			//alert( MinimumOrderPrompt );
			location.replace('cart.php');
		}
	}

	if ( bDisplay ) {
		strOutput += "<tr><td class=\"noptotal\" colspan=5>&nbsp</td>";
		strOutput += "<tr><td class=\"noptotal\" colspan=4><b>"+strSUB+"</b></td>";		// SUBTotal
		strOutput += "<td class=\"noptotal\" colspan=1 align=right><b>" + MonetarySymbol + strTotal + "</b></td>";
		strOutput += "</tr>";
		// Shipping 
		if ( DisplayShippingRow ) {
			strOutput += "<tr><td class=\"noptotal\" colspan=4><b>"+strSHIP+"</b></td>";		// Shipping
			if ( userOutsideNZ == "true" || customerPickup == "true" ) {
				strOutput += "<td class=\"noptotal\" colspan=1><span style=\"color: red;\">" + strShipping + "</span></td>";
			} else {
				strOutput += "<td class=\"noptotal\" colspan=1><b>" + MonetarySymbol + strShipping + "</b></td>";
		}

		strOutput += "</tr>";
	}


	//GST Content
	if ( userOutsideNZ == "true") {
		strOutput += "<tr><td class=\"noptotal\" colspan=5> </td></tr>";
	} else {
		strOutput += "<tr><td class=\"noptotal\" colspan=4><b>"+strGST+"</b></td>";
		gstTotal = (fTotal + fShipping) * TaxRate;
		strOutput += "<td class=\"noptotal\" colspan=1><b>" + MonetarySymbol + moneyFormat(gstTotal) + "</b></td>";
		strOutput += "</tr>";
	}

	// Grand Totals
	strOutput += "<tr><td class=\"noptotal\" colspan=4><b>"+strTOT+"</b></td>";		// Grand Total
	strOutput += "<td class=\"noptotal\" colspan=1><b>" + MonetarySymbol + moneyFormat((fTotal + fShipping + gstTotal)) + "</b></td>";
	strOutput += "</tr>";

	strOutput += "</table>";

	if ( PaymentProcessor == 'an') {
		//Process this for Authorize.net WebConnect
		strOutput += "<input type=hidden name=\"x_Version\" value=\"3.0\">";
		strOutput += "<input type=hidden name=\"x_Show_Form\" value=\"PAYMENT_FORM\">";
		strOutput += "<input type=hidden name=\"x_Description\" value=\""+ strPP + "\">";
		strOutput += "<input type=hidden name=\"x_Amount\" value=\""+ moneyFormat((fTotal + fShipping + fTax)) + "\">";
	} else if ( PaymentProcessor == 'wp') {
		//Process this for WorldPay
		strOutput += "<input type=hidden name=\"desc\" value=\""+ strPP + "\">";
		strOutput += "<input type=hidden name=\"amount\" value=\""+ moneyFormat((fTotal + fShipping + fTax)) + "\">";
	} else if ( PaymentProcessor == 'lp') {
		//Process this for LinkPoint         
		strOutput += "<input type=hidden name=\"mode\" value=\"fullpay\">";
		strOutput += "<input type=hidden name=\"chargetotal\" value=\""+ moneyFormat((fTotal + fShipping + fTax)) + "\">";
		strOutput += "<input type=hidden name=\"tax\" value=\""+ MonetarySymbol + strTax + "\">";
		strOutput += "<input type=hidden name=\"subtotal\" value=\""+ MonetarySymbol + strTotal + "\">";
		strOutput += "<input type=hidden name=\"shipping\" value=\""+ MonetarySymbol + strShipping + "\">";
		strOutput += "<input type=hidden name=\"desc\" value=\""+ strPP + "\">";
	} else {
		strOutput += "<input type=hidden name=\""+OutputOrderSubtotal+"\" value=\""+ MonetarySymbol + strTotal + "\">";
		strOutput += "<input type=hidden name=\""+OutputOrderShipping+"\" value=\""+ MonetarySymbol + strShipping + "\">";
		strOutput += "<input type=hidden name=\""+OutputOrderTotal+"\"    value=\""+ MonetarySymbol + moneyFormat((fTotal + fShipping + fTax)) + "\">";
		strOutput += "<input type=hidden name=\""+OutputOrderTax+"\"    value=\""+ MonetarySymbol + moneyFormat(gstTotal) + "\">";
	}

	// Check out Notes
	strOutput += "<fieldset class=\"fieldset\" style=\"margin: 6px;\">";
	strOutput += "<legend id=\"checkout_notes\">Check Out Notes:</legend>"; 
	strOutput += "<p>All prices are in NZ$, and EXCLUDE GST.</p>"
	strOutput += "<p>Freight charges - minimum $5.50 per 25Kg within Auckland City (Freight charges will be confirmed by email on acceptance of order.)</p>"
	strOutput += "</fieldset>"

	strOutput += "<fieldset class=\"fieldset\" style=\"margin: 6px;\">";
	strOutput += "<legend id=\"payment_instructions\">Payment Instructions</legend>"; 
        strOutput += "<input type=hidden name=\"Customer_Pickup\" value=\"" + customerPickup + "\">";
        strOutput += "<input type=hidden name=\"UserOutsideNZ\" value=\"" + userOutsideNZ + "\">";
	strOutput += "<p>";
	strOutput += "IF YOU ARE AN EXISTING ACCOUNT HOLDER, YOUR ORDER WILL BE DESPATCHED AND INVOICED TO YOU IN THE USUAL MANNER.";
	strOutput += "</p>";
	strOutput += "<p>";
	strOutput += "ALL STATE FUNDED EDUCATIONAL INSTITUTIONS ARE AUTOMATICALLY GRANTED AN ACCOUNT WITH US.";
	strOutput += "</p>";
	strOutput += "<p>";
	strOutput += "FOR NON ACCOUNT HOLDERS, - WE WILL CONTACT YOU BY EMAIL WITHIN 24 HOURS TO CONFIRM: <br />";
	strOutput += "1) STOCK AVAILABILITY <br />";
	strOutput += "2) FREIGHT CHARGES <br />";
	strOutput += "3) TOTAL PRICE <br />";
	strOutput += "</p>";
	strOutput += "<p>";
	strOutput += "GOODS WILL BE DESPATCHED ON RECEIPT OF PAYMENT BY WAY OF DIRECT CREDIT TO OUR BANK ACCOUNT. <br />";
	strOutput += "IF UPLIFTING GOODS IN PERSON WE WILL ACCEPT CASH. <br />";
	strOutput += "</p>";
	strOutput += "<p>";
	strOutput += "PLEASE DO NOT FORWARD PAYMENT UNTIL YOUR ORDER HAS BEEN CONFIRMED BY EMAIL.";
	strOutput += "</p>";
	strOutput += "</fieldset>";
   }

   document.write(strOutput);
   document.close();

}

//=====================================================================||
//               END NOP Design SmartPost Shopping Cart                ||
//=====================================================================||

