// basket script courtesy of www.javascriptit.com all other javascript and mods
// by Smashing Time Web Design, you're free to use it but please acknowledge its origin

var appversion=parseInt(navigator.appVersion);
max_order_items = 100; //the number of possible items selected for ordering

var itemid_array = new makeArray(max_order_items);
var itemname_array = new makeArray(max_order_items);
var priceU_array = new makeArray(max_order_items);
var priceC_array = new makeArray(max_order_items);
var quantity_array = new makeArray(max_order_items);
var subtotal = 0; //subtotal or order
var modTotal = 0; //modified based on case discount 
var shippingCost = 0; 

var order = ''; //the order result built up as HTML

var HiddenOrder = ''; //the same as order above but for use with possible email transmission


//FUNC
function openOrderForm()
{
  var cart =window.open(document.location,"_self");
  if(navigator.appName == "Netscape")
  {cart.focus();}
}

//FUNC for Cookie
function getCookieVal (offset)
{
 var endstr = document.cookie.indexOf (";", offset);
 if (endstr == -1)
  endstr = document.cookie.length;
 return document.cookie.substring(offset, endstr);
}

//FUNC
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;
}

//FUNC
function addtoCookieArray(cookieName, info)
{
 var tmpString=GetCookie(cookieName);
 if(GetCookie(cookieName) !=null)
 {
  tmpString = GetCookie(cookieName) + escape(info) + ",";
  //append to the current cookie values
  document.cookie = cookieName + "=" + tmpString;
 }
 else
 {
  tmpString = escape(info) + ",";
  document.cookie = cookieName + "=" + tmpString;
 }
}

//FUNC
function parseIt(cookieName, array)
{
 config=GetCookie(cookieName);
 config+='';           // convert to a string if it wasn't before
 var y = 1;
 while(config.indexOf(",") >= 0)
 {
   var pos = config.indexOf(",");
   if (pos==0)
     array[y]="";
   else
     array[y]=unescape(config.substring(0,pos));
   y++;
   config=config.substring(pos+1,config.length);
 }
 return y-1;
}

//FUNC
function makeArray(n)
{
 this.length = n;
 for (var k = 1; k <= n; k++)
 {
  this[k] = 0;
 }
 return this;
}

//FUNCs for Basket
function fmtPrice(value)
{
amount = Math.round(value*Math.pow(10,2))/Math.pow(10,2);
amount -= 0;
return (amount == Math.floor(amount)) ? amount + '.00' : ( (amount*10 == Math.floor(amount*10)) ? amount + '0' : amount);
}

//FUNC
function displaySum(index)
{
 x=index;
 cases=Math.floor(quantity_array[x] / 12);
 looseBottles=quantity_array[x] - (cases * 12);

 if (looseBottles==0)
  {modTotal= cases * parseInt(priceC_array[x]);}
  else
     {modTotal = (cases * parseInt(priceC_array[x])) + (looseBottles * parseInt(priceU_array[x]));}

 eval("document.basket.sum"+index+".value=fmtPrice("+modTotal+")");
 //eval("document.basket.sum"+index+".value=fmtPrice("+quantity_array[index]*priceU_array[index]+")");
 

 document.basket.formshippingCost.value=fmtPrice(shippingCost);
 document.basket.formsubtotal.value=fmtPrice(subtotal);
 //document.basket.formFinalTotal.value=fmtPrice(shippingCost+subtotal);
}

//FUNC
function isInt(elm)
{
    var elmstr = '' + elm;
    if (elmstr == '')
        return false;
    for (var i = 0; i < elmstr.length; i++)
    {
        if (elmstr.charAt(i) < "0" || elmstr.charAt(i) > "9" || elmstr.charAt(i) == ".")
            { return false; }
    }
    return true;
}

//FUNC
function RoundQty(elm)
{
    var elmstr = "" + elm;
    if (elmstr == "")
        return 0;
    DotExist=0;
    DigitAfterDecimal=0;
    for (var i = 0; i < elmstr.length; i++)
    {
        if (elmstr.charAt(i) < "0" || elmstr.charAt(i) > "9") {
            if ((elmstr.charAt(i) == ".")&&(DotExist == 0))
                DotExist = 1;
            else
                return 0;
        }
        else if (DotExist == 1){
            if (DigitAfterDecimal < 2)
                DigitAfterDecimal = DigitAfterDecimal + 1 ;
            else {
                if (elmstr.charAt(i)>="5"){
                   var sTmp100 = elmstr.substring(0, i-3) + elmstr.substring(i-2, i);
     nTmp = Number( sTmp100 ) ;
     nTmp = nTmp + 1;
           var sTmp = "" + nTmp;
     if (sTmp.length < 2)
   sTmp = sTmp.substring(0, sTmp.length - 2) + ".0" + sTmp.substring(sTmp.length - 2, sTmp.length );
     else
   sTmp = sTmp.substring(0, sTmp.length - 2) + "." + sTmp.substring(sTmp.length - 2, sTmp.length );
                   return sTmp ;
                }
                else
                   return Number( elmstr.substring(0, i) );
            }
        }
    }

    return elm;
}

//FUNC
function validateQuantity(accindex,productQuantity)
{
   Qty=RoundQty(productQuantity);
   if (Qty >=10000 || Qty==0 || !isInt(Qty))
   {
    alert("Input must be a valid whole number greater than 1 and less than 9999!");
    eval("document.buynow.qty_"+accindex+".value=document.buynow.hqty_"+accindex+".value");
    return;
   }
   eval("document.buynow.hqty_"+accindex+".value = Qty");
   eval("document.buynow.qty_"+accindex+".value=Qty");
}

//FUNC
function updateQuantity(Qty, index, acceptZero)
{
    if (!acceptZero && (Qty>=10000 || Qty==0 || !isInt(Qty)))
 {
    alert("Input must be a valid whole number greater than 1 and less than 9999!");
    eval("document.basket.hqty_"+index+".value=quantity_array[index]");
        }
        else
        {
     quantity_array[index]=Qty;
     // remove existing cookie
     document.cookie = "quantity=; expires=Thu, 01-Jan-70 00:00:01 GMT";

     // convert from array to cookie
     for (i=1; eval(priceU_array[i])!= 0; i++)
         addtoCookieArray("quantity", quantity_array[i]);

     // update hidden variable as well
     document.basket.Order_ItemQuantity.value=GetCookie("quantity");
     calcNow();
     displaySum(index);
        }
}

//FUNC
function posInArray(cookieName, element)
{
 var tmp_array = new makeArray(max_order_items);
 total_count=parseIt(cookieName, tmp_array);
 if (total_count >= max_order_items)
   return -1;
 for (i=1; i<=total_count; i++)
 {
  if (tmp_array[i]==element)
   return i;
 }
 return 0;
}

//FUNC
function addValueInArray(cookieName, index, element)
{
 var tmp_array = new makeArray(max_order_items);
 total_count=parseIt(cookieName, tmp_array);
 tmp_array[index] = eval(tmp_array[index]) + eval(element);
 tmp_array[index] = RoundQty( tmp_array[index] );
 if (tmp_array[index] > 9999.99) return 0;
 // remove existing cookie
 document.cookie = cookieName + "=; expires=Thu, 01-Jan-70 00:00:01 GMT";
 // convert from array to cookie
 for (i=1; i<=total_count; i++)
     addtoCookieArray(cookieName, tmp_array[i]);
 return tmp_array[index];
}

//FUNC priceU  =unit price PriceC = case price
function addtoBasket(productID, productName, productPriceU, productPriceC,productQuantity)
{
   Qty=RoundQty(productQuantity);
   if (Qty >=10000 || Qty==0 || !isInt(Qty) )
  {
    alert("Input must be a valid whole number greater than 1 and less than 9999!");
    eval("document.buynow.qty_"+accindex+".value = document.buynow.hqty_"+accindex+".value");
    return;
  }
  // test if browser supports cookie
  document.cookie = "testcookie=mytestvalue";
  if (GetCookie("testcookie")!="mytestvalue")
  {
    alert("\nNO COOKIE SUPPORT\n \nYou will not be able to use the shopping basket without cookie support.\n \nFor more information on Cookie Support and turning it on please see your Browsers help section.");
    return;
  }
  // if product already in shopping basket
  search_index = posInArray("productID", productID);
  if (search_index==-1)
  {
   alert("The shopping basket is full. No more items can be added.");
   return;
  }
  if (search_index!=0)
  {
   total_quantity=addValueInArray("quantity", search_index, productQuantity);
  }
  else
  {
      addtoCookieArray("productID", productID);
      addtoCookieArray("product", productName);
      addtoCookieArray("priceU", productPriceU);
      addtoCookieArray("priceC", productPriceC);
      addtoCookieArray("quantity", productQuantity);
      total_quantity=productQuantity;
  }
  if (total_quantity > 1)
   {tmpText=" bottles "}
  else	
   {tmpText=" bottle "}
  if (total_quantity == 0)
   {
      alert(productQuantity + " x " + unescape(productName) + " " + "cannot be added to your shopping basket \n\n REASON:\n The maximium number of these items that can be added to your basket is 9999.99");
   }
   else if(productQuantity == 1)
   {
      alert(productQuantity + " x " + unescape(productName) + " " + "has been added to your shopping basket \n\nAltogether, you have "+
 total_quantity + tmpText + "of this wine in your basket");
  }
  else
  {
      alert(productQuantity + " x " + unescape(productName) + " " + "have been added to your shopping basket \n\nAltogether, you have "+
 total_quantity + tmpText + "of this wine in your basket");
   }
}

//FUNC
function calcNow()
{
//update information from the ordering cookies
 parseIt("productID", itemid_array);
 parseIt("product", itemname_array);
 parseIt("priceU", priceU_array);
 parseIt("priceC", priceC_array);
 parseIt("quantity", quantity_array);
//clear global calculation variables
 subtotal = 0;
 modTotal = 0;
 modItemPrice = 0;
 cases = 0;
 looseBottles = 0;

 totalCases = 0;
 totalBottles = 0;
 totalLooseBottles = 0;

 order = '';
 HiddenOrder = '';

//start loop
 for (x=1; eval(priceU_array[x]) != 0; x++)
 {
  if (quantity_array[x]!=0)
  {

  if (quantity_array[x] > 11)
  {ind='<span class="aster">&nbsp;*</span>';}
      else
  {ind='';}

  totalBottles=(totalBottles *1) + (quantity_array[x] * 1);

  cases= Math.floor(quantity_array[x] / 12);

  looseBottles= + quantity_array[x] - (cases * 12);

  if (looseBottles==0)
     {modTotal= cases * parseInt(priceC_array[x]);}
  else
     {modTotal = (cases * parseInt(priceC_array[x])) + (looseBottles * parseInt(priceU_array[x]));}

  //assemble HTML that will display the order info
  order += '<tr>';
  order += '<td class="bask">' + itemname_array[x] + '&nbsp;</td>';
  order += '<td class="bask">' + unescape(itemid_array[x]) + '</td>';
  order += '<td class="bask"> $' + fmtPrice(priceU_array[x]) + '</td>';
  order += '<td class="bask"> $' + fmtPrice(priceC_array[x]) + '</td>';
  order += '<td class="bask"><input type="TEXT" name="hqty_' + x + '" size="3" value="' + quantity_array[x] + '" onchange="this.value=RoundQty(this.value),updateQuantity(this.value,' + x + ',false)" maxlength="7"></td>';
  order += '<td class="bask" nowrap><input type="TEXT" name="sum' + x + '" size="6" value="' + fmtPrice(modTotal) + '" onchange="displaySum(' + x + ')">' + ind + '</td>';
  order += '<td class="bask"><input type="BUTTON" onclick="updateQuantity(0,' + x + ',true); openOrderForm()" value="Remove"></td>';
  order += '</tr>';
  order += '<tr>';

  order += '<td class="bask" colspan="7"><hr size="1" width="100%" color="#000000" noshade></td></tr>';

  //calculate the subtotal for the whole lot of items
  if (priceU_array[x] == "")
     {priceU_array[x] = "0";}

  tmpamount  = Math.round(modTotal*Math.pow(10,2))/Math.pow(10,2);
  tmpamount -= 0;
  subtotal  += tmpamount;

  tmptitems  = Math.round(1 * cases);
  tmptitems -= 0;
  totalCases  += tmptitems;


  tmptitems  = Math.round(1 * looseBottles);
  tmptitems -= 0;
  totalLooseBottles  += tmptitems;

  HiddenOrder += "Ref/Description=" + itemid_array[x] + "/" + unescape(itemname_array[x]) + ";   Online Bottle Price=$"  + fmtPrice(priceU_array[x]) + ";   Online Case Price=$"  + fmtPrice(priceC_array[x]) + ";   Quantity Ordered=" + quantity_array[x] + ";   Cost=$" + fmtPrice(modTotal) + "\r\n" + "\r\n";
  }
}
//end loop

temp = totalBottles % 12; //temp is remainder

totalCases=Math.floor(totalBottles / 12);

if (temp > 0)
   {totalCases = totalCases + 1;}


// WOONGARRA shipping costs
shippingCost=(totalCases * 1000) / 100;
if ((totalCases==0) && (totalLooseBottles==0))
    {shippingCost=0;}

// subtot line
order += '<tr><td align="right" colspan="5" class="baskbar"><b>Subtotal $</b></td><td class="baskbar" align="left" colspan="2" nowrap><input type="TEXT" size="8" name="formsubtotal" value="' + fmtPrice(subtotal) + '" ' +  'onchange="document.basket.formsubtotal.value=fmtPrice(subtotal)"><input type="hidden" name="OrderSubTotal" Value = "$' + fmtPrice(subtotal) + '"</td></tr>';

// spacer
order += '<tr><td colspan="7" height="10">&nbsp;</td></tr>';

// dummy shipping cost line
order += '<tr><td class="basksub" align="right" colspan="5" height="40"><b>Melbourne Postage $</b></td><td class="bask" colspan="2" nowrap ><input type="TEXT" size="8" name="melbshippingCost" value="FREE" ' + 'onchange="document.basket.melbshippingCost.value=\'   FREE\'"></td></tr>';

// shipping cost line
order += '<tr><td class="basksub" align="right" colspan="5" height="40"><b>Australian Postage $</b></td><td class="bask" colspan="2" nowrap ><input type="TEXT" size="8" name="formshippingCost" value="' + fmtPrice(shippingCost) + '" ' + 'onchange="document.basket.formshippingCost.value=fmtPrice(shippingCost)"><input type="hidden" name="OrdershippingCost" Value = "$' + fmtPrice(shippingCost) + '"</td></tr>';

// Grand Total line
//order += '<tr><td class="basksub" align="right" colspan="5" height="40"><b>TOTAL for this order $</b></td><td class="bask" colspan="2" nowrap><input type="TEXT" size="8" name="formFinalTotal" value="' + fmtPrice(subtotal+shippingCost) + '" ' + 'onchange="document.basket.formFinalTotal.value=fmtPrice(subtotal+shippingCost)"><input type="hidden" name="OrderFinalTotal" Value = "$' + fmtPrice(subtotal+shippingCost) + '"</td></tr>';

HiddenOrder += 'Total for this order is $' + fmtPrice(subtotal) + ' (excluding shipping)\r\n' + '\r\n';
HiddenOrder += 'Shipping cost is FREE within Melbourne and $' + fmtPrice(shippingCost) + ' elsewhere in Australia for this order\r\n' + '\r\n';

}

// FUNC This is almost the same as calcNow except that it does not display
// text entry fields and it supresses the shipping info for overseas customers

function calcNowBlank(buyerFrom)
{
 //update information from the ordering cookies
 parseIt("productID", itemid_array);
 parseIt("product", itemname_array);
 parseIt("priceU", priceU_array);
 parseIt("priceC", priceC_array);
 parseIt("quantity", quantity_array);

//clear global calculation variables
 subtotal = 0;
 modTotal = 0;
 modItemPrice = 0;
 cases = 0;
 looseBottles = 0;

 totalCases = 0;
 totalBottles = 0;
 totalLooseBottles = 0;

 order = '';
 HiddenOrder = '';

 //start loop
 for (x=1; eval(priceU_array[x]) != 0; x++)
 {
  if (quantity_array[x]!=0)
  {

  if (quantity_array[x] > 11)
  {ind='<span class="aster">&nbsp;*</span>';}
      else
  {ind='';}

  totalBottles=(totalBottles *1) + (quantity_array[x] * 1);

  cases=Math.floor(quantity_array[x] / 12);
  looseBottles=quantity_array[x] - (cases * 12);

  if (looseBottles==0)
     {modTotal= cases * parseInt(priceC_array[x]);}
  else
     {modTotal = (cases * parseInt(priceC_array[x])) + (looseBottles * parseInt(priceU_array[x]));}

  //assemble HTML that will display the order info
  order += '<tr>';
  order += '<td class="fax">' + itemname_array[x] + '&nbsp;</td>';
  order += '<td class="fax">' + unescape(itemid_array[x]) + '</td>';
  order += '<td class="fax"> $' + fmtPrice(priceU_array[x]) + '</td>';
  order += '<td class="fax"> $' + fmtPrice(priceC_array[x]) + '</td>';
  order += '<td class="fax">&nbsp;&nbsp;&nbsp;&nbsp;' + quantity_array[x] + '</td>';
  order += '<td class="fax" nowrap> $' + fmtPrice(modTotal) + '</td>';
  order += '<td class="fax">&nbsp;</td>';
  order += '</tr>';
  order += '<tr>';

  order += '<td class="fax" colspan="7"><hr size="1" width="100%" color="#000000" noshade></td></tr>';

  //calculate the subtotal for the whole lot of items
  if (priceU_array[x] == "")
     {priceU_array[x] = "0";}

  tmpamount  = Math.round(modTotal*Math.pow(10,2))/Math.pow(10,2);
  tmpamount -= 0;
  subtotal  += tmpamount;

  tmptitems  = Math.round(1 * cases);
  tmptitems -= 0;
  totalCases  += tmptitems;

  tmptitems  = Math.round(1 * looseBottles);
  tmptitems -= 0;
  totalLooseBottles  += tmptitems;

  HiddenOrder += "Ref/Description=" + itemid_array[x] + "/" + unescape(itemname_array[x]) + ";   Online Bottle Price=$"  + fmtPrice(priceU_array[x]) + ";   Online Case Price=$"  + fmtPrice(priceC_array[x]) + ";   Quantity Ordered=" + quantity_array[x] + ";   Cost=$" + fmtPrice(modTotal) + "\r\n" + "\r\n";
  }
}
//end loop

temp = totalBottles % 12; //temp is remainder

totalCases=Math.floor(totalBottles / 12);

if (temp > 0)
   {totalCases = totalCases + 1;}


// WOONGARRA shipping costs
shippingCost=(totalCases * 1000) / 100;
if ((totalCases==0) && (totalLooseBottles==0))
    {shippingCost=0;}

// subtot line
order += '<tr><td align="right" colspan="5" class="faxbar"><b>Subtotal&nbsp;</b></td><td class="faxbar" align="left" colspan="2" nowrap>$' + fmtPrice(subtotal) + '</td></tr>';

// spacer
order += '<tr><td colspan="7" height="10">&nbsp;</td></tr>';

// dummy shipping cost line
order += '<tr><td class="faxsub" align="right" colspan="5" height="40"><b>Melbourne Postage&nbsp;</b></td><td class="fax" colspan="2" nowrap >$0 - FREE</td></tr>';

// shipping cost line
order += '<tr><td class="faxsub" align="right" colspan="5" height="40"><b>Australian Postage&nbsp;</b></td><td class="fax" colspan="2" nowrap >$' + fmtPrice(shippingCost) + '</td></tr>';

// Grand Total line
//order += '<tr><td class="faxsub" align="right" colspan="5" height="40"><b>TOTAL for this order&nbsp;</b></td><td class="fax" colspan="2" nowrap>$' + fmtPrice(subtotal+shippingCost) + '</td></tr>';

HiddenOrder += 'Total for this order is $' + fmtPrice(subtotal) + ' (excluding shipping)\r\n' + '\r\n';
HiddenOrder += 'Shipping cost is FREE within Melbourne and $' + fmtPrice(shippingCost) + ' elsewhere in Australia for this order\r\n' + '\r\n';

}

//FUNC
function initHiddens()
{
// Set hidden variables with values of cookies
 document.basket.Order_ItemID.value = '' + GetCookie("productID");
 document.basket.Order_ItemName.value = '' + GetCookie("product");
 document.basket.Order_ItemUnitPrice.value = '' + GetCookie("priceU");
 document.basket.Order_ItemCasePrice.value = '' + GetCookie("priceC");
 document.basket.Order_ItemQuantity.value = '' + GetCookie("quantity");
}
