/* --------------- STUDIO CONNECTIONS EXTERNAL JAVASCRIPT FILE -------------- */
/*                                                                            */
/*    Description: Shopping functions                                         */
/*         Client: Cloud Studios - info@cloudstudios.com                      */
/*        Website: www.cloudstudios.com                                       */
/*         Author: Colin Abrahams - colin@studioconnections.net.au            */
/*      Copyright: 2008 Colin Abrahams, Studio Connections                    */
/*       Location: Wyong, NSW, Australia                                      */
/*        Version: SC-5.8                                                     */
/*   Last Updated: 2008-11-25                                                 */


// Calculated variables
SCSubTotal = 0;
SCNetWght = 0;
SCTrolley = false;
SCPkgWght = 0;
SCPkgCost = 0;
SCTotWght = 0;
SCPostChrg = 0;
SCFrtTotal = 0;
SCInvTotal = 0;

function ShopAdd(Desc) {
  if (top.ShopList && top.SiteInit && document.forms) {
    for (var i = 0; i < ShopList.length; i++) {
      if (ShopList[i].Desc.indexOf(Desc) != -1) {
        ShopList[i].Quan = 1;
        window.alert('One "' + ShopList[i].Desc
                   + '" has been added to your shopping cart.\nTo check '
                   + 'or change your order, go to Shopping Centre page.');

        // Recalculate totals
        ShopCalc();

        // Update shopping status indicator
        ShopTrolley();
      }
    }
  }
  else if (!top.Main) {
    window.alert("To order an item, you must go to the full site.");
  }
}

// The following functions assume that the Shop... arrays and user variables 
// (SU...) have been loaded by ShopList.js, the site has completed loading and
// the browser supports the document.forms array.

function ShopCalc() {
  SCSubTotal = 0;
  SCNetWght = 0;
  SCTrolley = false;
  for (var j = 0; j < ShopCat.length; j++) {
    ShopCat[j].Quan = 0;
  }
  for (var i = 0; i < ShopList.length; i++) {                   // Shopping list
    if (ShopList[i].Quan > 0) {                            // Ordered items only

      // Shopping trolley has something in it!
      SCTrolley = true;

      // Add to goods total
      SCSubTotal += ShopList[i].Quan * ShopList[i].Cost;

      for (var j = 0; j < ShopCat.length; j++) {              // Item Categories
        if (ShopCat[j].Type == ShopList[i].Type) {     // Matching category only

          // Add item quantity to item category quantity total
          ShopCat[j].Quan += ShopList[i].Quan;

          // Add item weight to net weight total
          SCNetWght += ShopCat[j].Wght * ShopList[i].Quan;
        }
      }
    }
  }

  // Select package and get weight and cost
  SCPkgWght = 0;
  SCPkgCost = 0;
  for (var j = 0; j < ShopCat.length; j++) {                  // Item Categories
    for (var k = 0; k < ShopPkg.length; k++) {                       // Packages
      if (ShopPkg[k].Type == ShopCat[j].Type) {        // Matching category only

        // Skip packages for larger quantities
        if (ShopPkg[k].RMin > ShopCat[j].Quan) {
          break;
        }

        // Get greatest package weight
        if (parseInt(ShopPkg[k].Wght) > SCPkgWght) {
          SCPkgWght = parseInt(ShopPkg[k].Wght);
        }

        // Get greatest package cost
        if (ShopPkg[k].Cost > SCPkgCost) {
          SCPkgCost = eval(ShopPkg[k].Cost);
        }
      }
    }
  }

  // Total package weight
  SCTotWght = SCNetWght + SCPkgWght;

  // Postage charges
  SCPostChrg = 0;
  if (SCTrolley) {
    for (var l = 0; l < ShopPost.length; l++) {               // Postage Charges

      // Get code from Postage Options array according to user's choice and
      // use code to address correct field of Postage Charges array
      SCPostChrg = eval(eval("ShopPost[l]." + ShopPostOpt[SUPostOpt].Code));

      // Skip charges for higher weights
      if (SCTotWght < parseInt(ShopPost[l].WMax)) {
        break;
      }
    }
  }

  // Freight charges
  SCFrtTotal = SCPostChrg + SCPkgCost;

  // Invoice total
  SCInvTotal = SCSubTotal + SCFrtTotal;
}

function ShopTrolley() {
  ShopThing = top.Upper && document.getElementById ?
              top.Upper.document.getElementById("ShopThing") : null;
  if (ShopThing) {
    if (SCTrolley) {
      ShopThing.style.display = "block";
    }
    else {
      ShopThing.style.display = "none";
    }
  }
}

function ShopClear() {

  // Reset all array quantity fields and form quantity fields
  for (var i = 0; i < ShopList.length; i++) {
    ShopList[i].Quan = 0;
    QtyField = eval("top.Main.document.ShopCentre.Qty" + i);
    QtyField.value = 0;
  }

  // Recalculate totals
  ShopCalc();

  // Update Goods Total field
  top.Main.document.ShopCentre.SubT.value = ShopFmtC(SCSubTotal);

  // Update shopping status indicator
  ShopTrolley();
}

function ShopFmtC(Num) {            // Convert number to currency format ($n.nn)

  // Extract $ portion of number and force display of "0" for < 1
  var St1 = parseInt(Num);

  // Extract ¢ portion of number and force 2 digit display including when zero
  // The space character forces data conversion to string
  var St = Num == 0 ? "00" : " " + parseInt(Num * 100);
  var St2 = St.substr(St.length - 2);

  return("$" + St1 + "." + St2);
}


// Validation functions for Shopping Centre page

function ShopCheck() {
  if (SCTrolley) {

    // Delay page loading to allow button to return to correct state
    setTimeout("top.Main.location = 'Site/Shop/ShopCheck.html'", 250);
  }
  else {
    alert("You need to order something first!");
  }
}

function ShopUpdt(QtyField) {
  var Qty = 0;

  // Validate form quantity field
  if (isNaN(QtyField.value) || QtyField.value.indexOf(".") != -1) {
    QtyField.value = 0;
    window.alert("Please enter an integer between 1 and 10.");
  }
  else if (QtyField.value > 10) {
    var Msg = 'Aw, shucks guys! That is real nice of you!\n'
            + 'But are you sure you really want to order '
            + QtyField.value + ' of these?\n'
            + 'For large orders, please contact Cloud Studios directly.';
    QtyField.value = 0;
    window.alert(Msg);
  }
  else if (QtyField.value >= 1) {
    Qty = parseInt(QtyField.value, 10);   // Ensure Qty taken as decimal integer
  }

  // Update array quantity field
  ShopList[QtyField.name.substr(3)].Quan = Qty;

  // Update form quantity field (remove any leading zeros)
  QtyField.value = Qty;

  // Recalculate totals
  ShopCalc();

  // Update Goods Total field
  top.Main.document.ShopCentre.SubT.value = ShopFmtC(SCSubTotal);

  // Update shopping status indicator
  ShopTrolley();
}


// Validation functions for User Details page

function ShopPostChk() {
  UsrForm = top.Main.document.UsrDetails;

  // Restrict options according to country
  for (var m = 0; m < top.ShopPostOpt.length; m++) {
    var OzCat = ShopPostOpt[m].Desc.toUpperCase().indexOf("INSIDE") != -1;
    var OzCunt = UsrForm.Country.value.toUpperCase() == "AUSTRALIA";
    if (OzCat != OzCunt) {
      UsrForm.PostOpt[m].checked = false;
      UsrForm.PostOpt[m].disabled = true;
    }
    else {
      UsrForm.PostOpt[m].disabled = false;
    }
  }

  // Check if anything now selected
  var Sel = false;
  for (var m = 0; m < top.ShopPostOpt.length; m++) {
    if (UsrForm.PostOpt[m].checked) {
      Sel = true;
    }
  }

  // Autoset an option
  if (!Sel) {
    for (var m = 0; m < top.ShopPostOpt.length; m++) {
      OzCat = ShopPostOpt[m].Desc.toUpperCase().indexOf("INSIDE") != -1;
      OzCunt = UsrForm.Country.value.toUpperCase() == "AUSTRALIA";
      if (OzCat == OzCunt) {
        UsrForm.PostOpt[m].checked = true;
        break;
      }
    }
  }

  // Update User Postage Option
  for (var m = 0; m < top.ShopPostOpt.length; m++) {
    if (UsrForm.PostOpt[m].checked == true) {
      top.SUPostOpt = m;
    }
  }

  // Recalculate totals
  ShopCalc();
}

function ShopOptIn(ChkBox) {
  if (ChkBox.checked && top.Main.document.UsrDetails.Email.value == "") {
    window.alert("Whilst we admire your enthusiasm, you need to enter an "
               + "email address first!");
  top.SUOptIn = false;
  ChkBox.checked = false;
  }
}

function ShopOrder() {
  if (SUName == "") {
    window.alert("We need to know who to send the goods to!\n"
                + "Please enter your name in the Contact field");
  }
  else if (SUAddr1 == "") {
    window.alert("We need to know where to send the goods to!\n" +
                 "Please enter your street address in the Address 1 field.");
  }
  else if (SUCity == "") {
    window.alert("We also need to know your City, State and Post Code\n" +
                 "Please fill in these fields.");
  }
  else if (SUState == "") {
    window.alert("We really need to know your full address!\n" +
                 "Please fill in the State field.");
  }
  else if (SUPCode == "") {
    window.alert("Please fill in the Post Code field.");
  }
  else {

    // Delay page loading to allow button to return to correct state
    setTimeout("top.Main.location = 'Site/Shop/ShopOrder.html'", 250);
  }
}

