API Docs for: WebTemplate API v2.0
Show:

File: /data/www/webtemplate/wtv2/codedoc/wtCart.php

<?php
/**
 *  WebTemplate Core
 *
 *  @version 2.1
 *  @module WebTemplate Core
 */



class WTCartItem 
{
  var $m_quantity;
  var $m_productGuid;
  var $m_notes;
}



function orderItemCallback($data, $args = NULL) 
{
  
}

$GLOBALS["WTCARTDISCOUNTFUNCTION"] = null;


/**
 *  The class used to store and order before it reaches the checkout<br/>
 *  example:<br/>
 *  $cart = new WTCart();
 *
 *  @class WTCart
 *
 **/
class WTCart 
{
  var $m_cartName;


  /**
   *  Register a custom function to calculate the discount to apply to the cart<br/>
   *  The custom function should return the discount in dollars and cents
   *
   *  @method registerCartDiscountFunction
   *  @static
   *  @param {Function} function The custom function to call when calculating discount
   */
  static function registerCartDiscountFunction($function)
  {
    $GLOBALS["WTCARTDISCOUNTFUNCTION"] = $function;

  }


//  function WTCart() 
  function __construct()
  {
    $this->m_cartName = "WTCART" . $GLOBALS["WTSITEID"]; 
    $this->m_orderName = "WTORDER" . $GLOBALS["WTSITEID"];

    if(!WTSession::get($this->m_cartName)) {
      WTSession::set($this->m_cartName, Array());
    }

  }

  function __destruct() 
  {
  }

  function add($id, $attributes) 
  {
    $this->set($product, $quantity);
    
  }


  function set($id, $attributes) 
  {
    if(array_key_exists("quantity", $attributes) && $attributes["quantity"] == 0) {
      $this->remove($id);
    } else {
      $cart = WTSession::get($this->m_cartName);
      $cart[$id] = $attributes;
      WTSession::set($this->m_cartName, $cart);

    }

  }

  function getAttributes($id) {
    $cart = WTSession::get($this->m_cartName);
    if(array_key_exists($id, $cart)) {
      return $cart[$id];
    } else {
      return Array();
    }
  }

  function remove($id)
  {
    $cart = WTSession::get($this->m_cartName);
    unset($cart[$id]);

    WTSession::set($this->m_cartName, $cart);

  }

  function getItems() 
  {
    return WTSession::get($this->m_cartName);
  }


  /**
   *  Return the quantity of an item in the cart
   *
   *  @method getQuantity
   *  @param {String} id The id of the item in the cart
   *  @return {int} The quantity of the item in the cart
   */
  function getQuantity($id) 
  {
    $cart = WTSession::get($this->m_cartName);
    if(array_key_exists($id, $cart) && array_key_exists("quantity", $cart[$id])) {
      return $cart[$id]["quantity"];
    }
    return 0;
  }

  /**
   *  Return the total number of distinct items in the cart
   *
   *  @method getTotalItemCount
   *  @return {int} The number of distinct items in the cart
   */

  function getTotalItemCount() {
    $cart = WTSession::get($this->m_cartName);
    return count($cart);
  }

  /**
   *  Return the total number of items in the cart
   *
   *  @method getTotalQuantity
   *  @return {int} The number of items in the cart
   */
  function getTotalQuantity() {
    
    $quantity = 0;

    $cart = WTSession::get($this->m_cartName);
    foreach($cart as $item) {
      if(array_key_exists("quantity", $item)) {
        $quantity += $item["quantity"];
      }
    }
    return $quantity;
  }

  /**
   *  Return the total weight of all items in the cart (in grams)
   *
   *  @method getTotalWeight
   *  @return {int} The total weight of all items in the cart (in grams)
   */
  function getTotalWeight($ignoreAbsoluteFreightProducts = false) {
    $weight = 0;
    $cart = WTSession::get($this->m_cartName);

    foreach($cart as $key => $attributes) {
      $productGuid = $attributes["productGuid"];
      if($productGuid) {
        $product = $GLOBALS["WT"]->getNode($productGuid);
        if((!$ignoreAbsoluteFreightProducts) || $product->getAttribute("Freight") != "Absolute Amount") {
          $weight += $product->getAttribute("Weight") * $attributes["quantity"];
        }
      }

    }


    return $weight;
  }

  /**
   *  Clear the cart
   *
   *  @method clear
   */

  function clear() 
  {
    WTSession::set($this->m_cartName, Array());
  }


  /**
   *  Add items to the cart from a post request
   *
   *  @method setFromRequest
   *  @param [addToCurrent=false] If an item is already in the cart, add to its quantity instead of replacing it
   *  @param [requestData=null] If set, use this data instead of the data from the post request
   */
  function setFromRequest($addToCurrent = false, $requestData = null) {

    $hasstock = WTConfig::get("Orders/Stock") == "Yes";
    $optionsHaveStock = WTConfig::get("Orders/Stock/Options Have Stock") == "Yes" || WTConfig::get("Orders/Stock/Combined Options Have Stock") == "Yes";

    $error = false;
    $stockErrors = Array();
    $stockErrorQuantities = Array();
    $stockErrorOptions = Array();

    $productGuid = $GLOBALS["WT"]->getRequestValue("productGuid", 0);
    $quantity = $GLOBALS["WT"]->getRequestValue("quantity");

    if($productGuid != 0) {
      $stockError = false;
      $product = $GLOBALS["WT"]->getNode($productGuid);
      if($product) {
        $stockError = $hasstock && $quantity > $product->getAttribute("Stock");
        if(!$stockError) {
          $this->set($productGuid, Array("quantity" => $quantity, "productGuid" => $productGuid));
        } else {
          $error = true;
          $stockErrors[$productGuid] = $quantity;
        }
      }




    }

    if(!$requestData) {
      $requestData = $_REQUEST;
    }
    $optionKey = "";
    foreach($requestData as $key => $value) {
      if(strpos($key, "productquantity_") === false && strpos($key, "productquantity") !== false) {
        $key = str_replace("productquantity", "productquantity_", $key);
      }
      if(strpos($key, "productquantity_") !== false && $value >= 0) {
        list($p, $productGuid) = explode("_", $key);
        if($productGuid) {
          $stockError = false;
          $price = -1;
          $priceeach = -1;
          $pricealteration = 0;
          $optionlist = "";

          $product = $GLOBALS["WT"]->getNode($productGuid);

/*
          if($product) {
            $options = "";
            if($optionsHaveStock) {
              $options = $key;
            }
            $stockError = $hasstock && $value > $product->getStock($options);
          }
          if($stockError) {
            $error = true;
            $stockErrors[$productGuid] = $value;
          } else {
*/

            $optionKey = "";
            $options = $product->getOptions();
            if($options) {
              foreach($options as $optionSetGuid => $optionsArray) {           
                $optionSet = $GLOBALS["WT"]->getNode($optionSetGuid);
                if($optionSet) {
                  $optionSetName = $optionSet->getName();
//                  if($optionSet->getAttribute("Options are exclusive") == "Yes") {
                  if($optionSet->getAttribute("Type") == "Drop Down List" || $optionSet->getAttribute("Type") == "Radio Buttons") {
                    $optionGuid = $GLOBALS["WT"]->getRequestValue("productoption{$optionSetGuid}_{$productGuid}", 0);
                    if($optionGuid != 0) {
                      $optionKey .= "_" . $optionSetGuid . "_" . $optionGuid;

                      $option = $GLOBALS["WT"]->getNode($optionGuid);
                      $optionname = $option->getName();
                      if($optionSetName == "Value") {
                        $optionname = '$' . $optionname;
                      }

                      if(WTConfig::get("Orders/Options Have Code") == 'Yes') {
                        $optionname = $options[$optionSetGuid][$optionGuid]["code"] . "&nbsp; $optionname";
                      }


                      if($product && ($priceeffect = $product->getOptionPriceEffect($optionSetGuid, $optionGuid))) {
                        switch($priceeffect["effect"]) {
                          case 0:
                            break;
                          case 1:
                            $optionname .= '($' . number_format($priceeffect["price"], 2) . ')';
                            $priceeach = $priceeffect["price"];
                            break;
                          case 2:
                            $pricealteration += $priceeffect["price"];
                            $optionname .= '(+$' . number_format($priceeffect["price"], 2) . ')';
                            break;
                        }


                       
                      } else {
                        $priceeffect = $options[$optionSetGuid][$optionGuid]["price"];
                        if($priceeffect != "" && $priceeffect != 0) {
                          if($priceeffect[0] == '+') {
                            $priceeffect = substr($priceeffect, 1);
                            $pricealteration += (int)$priceeffect;
                            $optionname .= '(+$' . number_format($priceeffect, 2) . ')';
                          } else {
                            if($optionSetName != "Value") {
                              $optionname .= '($' . number_format($priceeffect, 2) . ')';
                            }
                            $priceeach = $priceeffect;
                          }
                        }
                      }
                    }
/*
              if($optionsetdata["options"][$optionname]["price"] != "" && $optionsetdata["options"][$optionname]["price"] != 0) {
                $priceeach = $optionsetdata["options"][$optionname]["price"];
                
              }
*/
                    $optionlist .= '<strong>' . $optionSet->getName() . '</strong>' . ":&nbsp;" . $optionname . '<br/>';                
                  } else {
                    $optionValue = "";
                    foreach($optionsArray as $optionGuid => $optionData) {
                      if($GLOBALS["WT"]->getRequestValue("o" . $optionGuid) == 1) {
                        $option = $GLOBALS["WT"]->getNode($optionGuid);
                        if($optionValue != "") {
                          $optionValue .= ", ";
                        }
                        $optionValue .= $option->getName();
                        $priceeffect = $options[$optionSetGuid][$optionGuid]["price"];
                        if($priceeffect != "" && $priceeffect != 0) {
                          if($priceeffect[0] == '+') {
                            $priceeffect = substr($priceeffect, 1);
                            $pricealteration += (int)$priceeffect;
                            $optionValue .= '(+$' . number_format($priceeffect, 2) . ')';
                          }
                        }
                      }
                    }
                    if($optionValue != "") {
                      $optionlist .= '<strong>' . $optionSet->getName() . '</strong>' . ":&nbsp;" . $optionValue . '<br/>';
                    }
   
                  }
                }
              }
            }  

            $productKey = $productGuid;
            $productKey .= $optionKey;
            if($addToCurrent) {
              $cart = WTSession::get($this->m_cartName);
              if(array_key_exists($productKey, $cart)) {
                 if(array_key_exists("quantity", $cart[$productKey])) {
                   $value += $cart[$productKey]["quantity"];
                 }
              }

            }



            if($priceeach > -1) {
              $price = $priceeach * $value;
            }
  
            if($pricealteration != 0) {
              if($priceeach == -1) {
                $product = $GLOBALS["WT"]->getNode($productGuid);
                if($product) {
                  $priceeach = $product->getPrice();
                }
              }
              $priceeach += $pricealteration;
              $price = $priceeach * $value;           
            }
  /*
          }*/

            $productKey = $productGuid;
//            if($GLOBALS["WTSITEID"] == 11358 || $GLOBALS["WTSITEID"] == 11299 || $GLOBALS["WTSITEID"] == 11288) {
              $productKey .= $optionKey;
//            }



          $product = $GLOBALS["WT"]->getNode($productGuid);
          if($product) {
            $options = "";
            if($optionsHaveStock) {
              $options = $productKey;
            }

            $stock = $product->getStock($options);
            $stockError = $hasstock && $value > $stock;
          }
          if($stockError) {
            $error = true;
            $stockErrors[$productGuid] = $value;
            $stockErrorQuantities[$productGuid] = $stock;
            $stockErrorOptions[$productGuid] = $optionlist;
          } else {

            $descriptionTemplate = WTConfig::get("Orders/Order Item Description");
            if($product && $descriptionTemplate != "") {
              $extraDescription = "<br>" . WTTemplate::compileAndEvaluate($descriptionTemplate, $product->getAttributes());
            }

            if($price > -1) {
              if($GLOBALS["WTSITEID"] == 11659) {
                // bendigo gold
                $this->set($productKey, Array("quantity" => $value, "productGuid" => $productGuid, "description" => $optionlist . $extraDescription, "optionpricealteration" => $pricealteration));
              } else {
                $this->set($productKey, Array("quantity" => $value, "productGuid" => $productGuid, "description" => $optionlist . $extraDescription, "price" => $price, "priceeach" => $priceeach, "optionpricealteration" => $pricealteration));
              }
            } else {
              $this->set($productKey, Array("quantity" => $value, "productGuid" => $productGuid, "description" => $optionlist . $extraDescription));
            }
          }
        }  
      }
    }
//    $wtCart->set($productGuid, Array("quantity" => $quantity, "productGuid" => $productGuid) );
//    WTSession::set("WTSTOCKERRORS", $stockErrors);

    $GLOBALS["WTSTOCKERRORS"] = $stockErrors;
    $GLOBALS["WTSTOCKERRORQUANTITIES"] = $stockErrorQuantities;
    $GLOBALS["WTSTOCKERROROPTIONS"] = $stockErrorOptions;
    return !$error;
  }

  function update() {


    $cart = WTSession::get($this->m_cartName);
    $hasStock = WTConfig::get("Orders/Stock") == "Yes";
    $optionsHaveStock = WTConfig::get("Orders/Stock/Options Have Stock") == "Yes" || WTConfig::get("Orders/Stock/Combined Options Have Stock") == "Yes";;

    $stockErrors = Array();
    $stockOptionErrors = Array();


    foreach($cart as $key => $attributes) {
      $quantity = $GLOBALS["WT"]->getRequestValue("q$key");


      if($quantity != "") {
        $stockError = false;
        if($hasStock) {
          $productGuid = $attributes["productGuid"];
          if($productGuid) {
            $product = $GLOBALS["WT"]->getNode($productGuid);
            $options = "";
            if($optionsHaveStock) {
              $options = $key;
            }
            $stockError = $quantity > $product->getStock($options);
          }
        }
        
        if(!$stockError) {

          if(is_numeric($quantity) && $quantity >= 0) {
            if($quantity != 0) {
              $cart[$key]["quantity"] = $quantity;
              if(array_key_exists("priceeach", $attributes)) {
                $cart[$key]["price"] = $quantity * $attributes["priceeach"];
              }
            } else {
              WTSession::set($this->m_cartName, $cart);
              $this->remove($key);
              $cart = WTSession::get($this->m_cartName);                            
            }
          }
        } else {
          if($options != "") {
            $stockOptionErrors[$options] = $quantity;
          }
          $stockErrors[$productGuid] = $quantity;
        }
      }
      $remove = $GLOBALS["WT"]->getRequestValue("r$key");
      if($remove == 1) {
        $this->remove($key);
      }
    }
    WTSession::set($this->m_cartName, $cart);
    $GLOBALS["WTSTOCKERRORS"] = $stockErrors;
    $GLOBALS["WTSTOCKOPTIONERRORS"] = $stockOptionErrors;
    return count($stockErrors) == 0;
  }

  /**
   *  Return the total price of all the items in the cart (not including discount)
   *
   *  @method getTotal
   *  @return {int} The total price of all the items in the cart
   */

  function getTotal() {
    $subtotal = 0;
    $cart = WTSession::get($this->m_cartName);

    foreach($cart as $key => $attributes) {
      $product = NULL;
      $productAttributes = Array();

      $productGuid = $attributes["productGuid"];
      if($productGuid) {
        $product = $GLOBALS["WT"]->getNode($productGuid);
        $productAttributes = $product->getAttributes();
        $productAttributes["Price"] = $product->getPrice(1, $attributes["quantity"]);

        if(array_key_exists("optionpricealteration", $attributes)) {
          $productAttributes["Price"] += $attributes["optionpricealteration"];
        }
        $productAttributes["Total"] = $attributes["quantity"] * $productAttributes["Price"];
      }

      $productAttributes["Key"] = $key;
      $productAttributes["Quantity"] = $attributes["quantity"];
      if(array_key_exists("price", $attributes)) {
        $productAttributes["Price"] = $attributes["priceeach"];
        $productAttributes["Total"] = $attributes["price"];
      }

      $subtotal += $productAttributes["Total"];
    }
    return $subtotal;
  }

  /**
   *  Return the freight for the cart
   *
   *  @method getFreight
   *  @param {Array} args An associative array containing keys for: country, postcode, weight, quantity, order value, Freight Carrier ID
   *  @return {int} The freight for the cart
   */
  function getFreight($args) {


    $cart = WTSession::get($this->m_cartName);

    $allProductsHaveAbsoluteFreight = true;

    // first calculate freight for products with absolute freight set
    $absoluteFreight = 0;
    foreach($cart as $key => $attributes) {
      $productGuid = $attributes["productGuid"];
      if($productGuid) {
        $product = $GLOBALS["WT"]->getNode($productGuid);
        if($product) {
          if($product->getAttribute("Freight") == "Absolute Amount") {


            $absoluteFreight += $product->getAttribute("Freight Amount") * $attributes["quantity"];
          } else {
            $allProductsHaveAbsoluteFreight = false;
          }
        }
      } else {
        $allProductsHaveAbsoluteFreight = false;
      }
    }


    if($allProductsHaveAbsoluteFreight) {
      return $absoluteFreight;
    }
    // next get the weight of products which don't have absolute freight
    $weight = $this->getTotalWeight(true);
    $totalQuantity = $this->getTotalQuantity();


       
    $freight = WTFreight::getCharge(Array("Order ID" => $args["Order ID"], "country" => $args["country"], "postcode" => $args["postcode"], "weight" => $weight, "quantity" => $totalQuantity, "order value" => $args["order value"], "Freight Carrier ID" => $args["Freight Carrier ID"]));

    if($freight !== false) {
      $freight += $absoluteFreight;
    }
    return $freight;
  }

  function setCustomerDetails() 
  {
  }

  function render($args = Array()) {
    $step = $GLOBALS["WT"]->getRequestValue("wtStep");

    if($step == "" && isset($args["type"]) && $args["type"] == "orderform") {
      return $this->renderOrderForm($args);
    }

    $step = $GLOBALS["WT"]->getRequestValue("wtStep");
    switch($step) {
      case 'billingdetails':
        return $this->renderBillingDetails();
        break;
      case 'deliverydetails':
        return $this->renderDeliveryDetails();
        break;
      case 'login':
        return $this->renderLogin();
        break;
      case 'summary':
        return $this->renderSummary();
        break;
      case 'pay':
        return $this->renderCCPayment();
        break;
      case 'successful':
        return $this->renderSuccessful();
        break;
      case 'cart':
      default:
        return $this->renderCart();
        break;
    }
  }

  function getValue($pathElements) {
    switch($pathElements[2]) {
      case 'total':
        return $this->getTotal() - $this->getDiscount();
      case 'count':
        return $this->getTotalItemCount();
        break;
      case 'quantity':
        return $this->getTotalQuantity();
        breka;
      case 'discount':
        return $this->getDiscount();
/*      case 'checkouturl':
        return WTConfig::get("Orders/Checkout URL");
        break;
*/
    }
    return 0;
  }

  function renderCart($args = NULL) {
    $cart = WTSession::get($this->m_cartName);

    if($args != NULL && array_key_exists("Template Function", $args) ) {
      $html = '';
      $template = $args["Template Function"];
      $resultNumber = 1;
      foreach($cart as $key => $attributes) {

        $data = Array();
        $productGuid = $attributes["productGuid"];
        if($productGuid) {
          $product = $GLOBALS["WT"]->getNode($productGuid);
          $data = $product->getAttributes();
          $data["Description"] = $attributes["description"];
          if(array_key_exists("price", $attributes)) {
            $data["Cart Price"] = $attributes["priceeach"];
            $data["Cart Total"] = $attributes["price"];
          } else {
            $data["Cart Price"] = $product->getPrice(1, $attributes["quantity"]);

            if(array_key_exists("optionpricealteration", $attributes)) {
              $data["Cart Price"] += $attributes["optionpricealteration"];
            }

            $data["Cart Total"] = $attributes["quantity"] * $data["Cart Price"];
          }
          $data["Cart Key"] = $key;
          $data["Product ID"] = $productGuid;
        } else {
          $data["Cart Price"] = $attributes["priceeach"];
          $data["Cart Total"] = $attributes["price"];
          $data["Code"] = $attributes["Code"];
          $data["Name"] = $attributes["Name"];
          $data["Description"] = $attributes["Description"];
          $data["Cart Key"] = $key;
        }
        $data["__resultNumber"] = $resultNumber++;
        $data["Cart Quantity"] = $attributes["quantity"];
        $html .= $template($data);
      }
      return $html;
    } else {
      $cartContentsNode = $GLOBALS["WT"]->getNode("/Templates/Cart Layouts/Cart Contents");
      if($cartContentsNode) {
        return $cartContentsNode->evaluate(Array());
      } else {
        $cartTemplate = WTTemplate::load($GLOBALS["WTDIRECTORY"] . "templates/cart/cart2.wt");
        return WTTemplate::compileAndEvaluate($cartTemplate, Array());
      }
    }
  }



  function recordOrder($order) {


    $user = $GLOBALS["WT"]->getCurrentUser();
    if($user) {
      $GLOBALS["WT"]->linkNodes($user->m_guid,$order);
      $groups = $user->getGroups("Member Group");
      if($groups) {
        $groupArray = explode(",", $groups);
        foreach($groupArray as $groupGuid) {
          $group = $GLOBALS["WT"]->getNode($groupGuid);
          if($group) {
            $orders = $GLOBALS["WT"]->getNode($groupGuid . "/Orders");
            if(!$orders) {
              $orders = $group->createChild("wtNode", Array("Node Name" => "Orders"));
            }
            if($orders) {
              $GLOBALS["WT"]->linkNodes($orders->m_guid, $order);
            }
          }
        }
      }
    }

    if(WTConfig::get("Orders/Stock") == "Yes") {
      $results = Array();
      $q = Array(); 
      $q["Node Type"] = "wtOrderItem";
      $q["Path"] = $order->m_guid . "/*";
      $q["Results Array"] = &$results;
      $GLOBALS["WT"]->query($q);
      foreach($results as $result) {
        $productGuid = $result["Product ID"];

        if($productGuid) {
          $product = $GLOBALS["WT"]->getNode($productGuid);
          if($product) {

            $product->alterStock(-$result["Quantity"], $result["Options"]);
          }
        }
      }
    }



    $successfulOrderGroup = WTConfig::get("Orders/Successful Order Member Group");
    if($successfulOrderGroup != "" && $GLOBALS["WT"]->getWTValue("wt.currentuser.ismember") ) {
      $groupNode = $GLOBALS["WT"]->getNode("/Groups/$successfulOrderGroup");
      if($groupNode) {
        $GLOBALS["WT"]->linkNodes($groupNode, $user);
      }
    }
  }

  function orderRequiresQuote() {
    $cart = WTSession::get($this->m_cartName);

    foreach($cart as $key => $attributes) {
      $productGuid = $attributes["productGuid"];
      if($productGuid) {
        $product = $GLOBALS["WT"]->getNode($productGuid);
        if($product->getAttribute("Can be Purchased") == "No") {
          return true;
        }
      }       
    }

    return false;

  }

  function checkoutStep() {
    $wtStep = $GLOBALS["WT"]->getRequestValue("wtStep");
    switch($wtStep) {
      case 'orderformsubmit':
        $this->clear();
        $this->setFromRequest();
        $this->addCartToOrder();

        $order = $this->getOrder();

        $form = $GLOBALS["WT"]->getNode("/Forms/Order Address");
        $formType = "Form" . $form->m_guid;
        $data = $form->requestData(false);
        $delivery = $GLOBALS["WT"]->getNode($order->m_guid . "/Delivery Address");
        if($delivery == NULL) {
          $delivery = $order->createChild($formType, $data);
        } else {
          $delivery->setAttributes($data);
        }
        $delivery->setName("Delivery Address");

        $billing = $GLOBALS["WT"]->getNode($order->m_guid . "/Billing Address");
        if($billing == NULL) {
          $billing = $order->createChild($formType, $data);
        } else {
          $billing->setAttributes($data);
        }
        $billing->setName("Billing Address");

        $emailAddressField = $form->getFieldName("Email Address");
        if($emailAddressField) {
          $customerEmailAddress = $billing->getAttribute($emailAddressField);
          if($customerEmailAddress) {
            $order->setAttributes(Array("Customer Email Address" => $customerEmailAddress));
          }
        }


        $order->setAttributes(Array("Paid ID" => 0, "Order Date" => date("Y-m-d H:i:s"), "Status" => "Pending"));


        $order->sendEmail();
        $page = $GLOBALS["WT"]->getRequestURI();
        $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "successful");
        $page = $GLOBALS["WT"]->setURIParameter($page, "wtCmd", "checkoutstep");
        $page = $GLOBALS["WT"]->setURIParameter($page, "tid", "");
        
        header("Location: $page");
        exit("");
        break;
      case 'ordersubmitnopayment':
        if(WTConfig::get("Orders/Payment Options/Account") == "Yes") {
          $order = $this->getOrder();
          $this->clear();
          $order->setAttributes(Array("Paid ID" => 0, "Order Date" => date("Y-m-d H:i:s"), "Status" => "Pending"));
          $order->sendEmail();
          $this->recordOrder($order);
          $order->orderSubmitted();

          $page = $GLOBALS["WT"]->getRequestURI();
          $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "successful");
          $page = $GLOBALS["WT"]->setURIParameter($page, "wtCmd", "checkoutstep");
          $page = $GLOBALS["WT"]->setURIParameter($page, "tid", "");
          header("Location: $page");
        }

        break;
      case 'ordersubmitquoterequest':
        if(WTConfig::get("Orders/Payment Options/Quote Request") == "Yes") {
          $order = $this->getOrder();
          $this->clear();
          $order->setAttributes(Array("Paid ID" => 0, "Order Date" => date("Y-m-d H:i:s"), "Status" => "Quote Request"));
          $order->sendEmail();
          $this->recordOrder($order);

          $page = $GLOBALS["WT"]->getRequestURI();
          $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "successful");
          $page = $GLOBALS["WT"]->setURIParameter($page, "wtCmd", "checkoutstep");
          $page = $GLOBALS["WT"]->setURIParameter($page, "tid", "");
          header("Location: $page");

        }
        break;
      case 'checkout':
        $uri = $GLOBALS["WT"]->getWTValue("wt.uri");
        $uri = substr($page, strlen($GLOBALS["WT"]->getSiteSetting("Site Base")));

        $checkoutRequiresLogin = WTConfig::get("Orders/Checkout Requires Login") == "Yes";
        if($checkoutRequiresLogin && !$GLOBALS["WT"]->getWTValue("wt.currentuser.ismember") ) {
          $uri = $GLOBALS["WT"]->setURIParameter($uri, "wtCmd", "checkoutstep");
          $uri = $GLOBALS["WT"]->setURIParameter($uri, "wtStep", "login");

        } else {
          $uri = $GLOBALS["WT"]->setURIParameter($uri, "wtCmd", "checkoutstep");
          $uri = $GLOBALS["WT"]->setURIParameter($uri, "wtStep", "billingdetails");
        }
        header("Location: $uri"); 
        exit("");
        break;
      case 'setorder':
        print "set order";
        exit("");
/*
        $guid = $GLOBALS["WT"]->getRequestValue("g");
        $key = $GLOBALS["WT"]->getRequestValue("k");
        if($this->setOrder($guid, $key)) {
          $checkout = $GLOBALS["WT"]->getNode("/Config/Settings/Orders/Checkout URL");
          $checkouturl = $checkout->getAttribute("Value");
          header("Location: $checkouturl");
        }
*/
        break;
      case 'setshipping':

print "set shipping";
exit("");
/*
        $error = '';
        $order = $this->getOrder();

        $emailAddress = $GLOBALS["WT"]->getRequestValue("FieldEmail");
        $subscribe = $GLOBALS["WT"]->getRequestValue("FieldSubscribe");

        $fieldBilling = $GLOBALS["WT"]->getRequestValue("FieldBilling");
        $order->setAttributes(Array("Customer Email Address" => $emailAddress, "Subscribe ID" => $subscribe, "Billing Same As Shipping ID" => $fieldBilling));

        $form = $GLOBALS["WT"]->getNode("/Forms/Order Shipping Form");
        if(!$form) {
          $form = $GLOBALS["WT"]->getNode("/Forms/Order Address");
        }
        $formType = "Form" . $form->m_guid;
        $shipping = $GLOBALS["WT"]->getNode($order->m_guid . "/Shipping Address");
        $data = $form->requestData(false);


        if($shipping == NULL) {
          $shipping = $order->createChild($formType, $data);
        } else {
          $shipping->setAttributes($data);
        }
        $shipping->setName("Shipping Address");

        $postcodeField = $form->getFieldName("Postcode");
        $postcode = $shipping->getAttribute($postcodeField);
        //$weight = $this->getTotalWeight();
//        $freight = WTFreight::getCharge(Array("postcode" => $postcode, "weight" => $weight));

        $orderValue = $order->getTotal(false);
        $freight = $this->getFreight(Array("postcode" => $postcode, "order value" => $orderValue)); 
        if($freight === false) {
          $error .= 'bad postcode';
        }
        $order->setAttributes(Array("Freight" => $freight));


        $form = $GLOBALS["WT"]->getNode("/Forms/Order Billing Form");
        if(!$form) {
          $form = $GLOBALS["WT"]->getNode("/Forms/Order Address");
        }
        $formType = "Form" . $form->m_guid;
        $billing = $GLOBALS["WT"]->getNode($order->m_guid . "/Billing Address");
        $data = $form->requestData(false);
        if($billing == NULL) {
          $billing = $order->createChild($formType, $data);
        } else {
          $billing->setAttributes($data);
        }
        $billing->setName("Billing Address");

        $shippingInstructionsForm = $GLOBALS["WT"]->getNode("/Forms/Order Shipping Instructions");
        

        $form = $GLOBALS["WT"]->getNode("/Forms/Order Shipping Instructions");
        if($form != NULL) {
          $formType = "Form" . $form->m_guid;
          $shippingInstructions = $GLOBALS["WT"]->getNode($order->m_guid . "/Shipping Instructions");

          $formData = $form->getFormDataFromRequest();

          if($shippingInstructions == NULL) {
            $shippingInstructions = $order->createChild($formType, $formData);
          } else {
            $shippingInstructions->setAttributes($formData);
          }
          $shippingInstructions->setName("Shipping Instructions");
        }


        $page = $GLOBALS["WT"]->getRequestURI();
        $fieldBilling = $GLOBALS["WT"]->getRequestValue("FieldBilling");
        if($fieldBilling) {
          $form = $GLOBALS["WT"]->getNode("/Forms/Order Address");
          $formType = "Form" . $form->m_guid;

          $billing = $GLOBALS["WT"]->getNode($order->m_guid . "/Billing Address");
          if($billing == NULL) {
            $billing = $order->createChild($formType, $_REQUEST);
          } else {
            $billing->setAttributes($_REQUEST);
          }
          $billing->setName("Billing Address");

          if($error == '') {
            $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "summary");
          } else {
          }
        } else {
          if($error == '') {
            if(array_key_exists("FieldBilling", $_REQUEST)) {
              $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "billing");
            } else {
              $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "summary");
            }
          }
        }
      //exit(""); 
        header("Location: $page");
        break;
*/
      case 'setbillingdetails':


        $order = $this->getOrder();

        // update the createdby incase someone has logged in since creating the order
        $currentUserGuid = $GLOBALS["WT"]->m_contactGuid;
        $sql = "UPDATE
                  wtNode
                SET
                  __createdByGuid = $currentUserGuid
                WHERE
                  __guid = {$order->m_guid}";
        mysql_query($sql);


        $billingForm = $GLOBALS["WT"]->getNode("/Forms/Order Billing Form");
        if(!$billingForm) {
          $billingForm = $GLOBALS["WT"]->getNode("/Forms/Order Address");
        }        
        $billingData = $billingForm->requestData(false);

        $emailField = $billingForm->getFieldName("Email Address");
        $emailAddress = $billingData[$emailField];


        $customerName = WTConfig::get("Orders/Customer Name");
        if($customerName == "") {
          $firstNameField = $billingForm->getFieldName("First Name");
          $lastNameField = $billingForm->getFieldName("Last Name");        
          $customerName = $billingData[$firstNameField] . " " . $billingData[$lastNameField];
        } else {
          $customerData = $billingForm->getDataWithLabels($billingData);
          $customerName = WTTemplate::compileAndEvaluate($customerName, $customerData);
        }

        $subscribe = $GLOBALS["WT"]->getRequestValue("FieldSubscribe");
        $fieldBilling = $GLOBALS["WT"]->getRequestValue("FieldBilling");
        $freightCarrier = $GLOBALS["WT"]->getRequestValue("FreightCarrier");
        $paymentMethod = $GLOBALS["WT"]->getRequestValue("FieldPaymentMethod");
        if($paymentMethod == "") {
          if(WTConfig::get("Orders/Payment Options/Credit Card") == "Yes") {
            $paymentMethod = "Credit Card";
          } else if(WTConfig::get("Orders/Payment Options/Account") == "Yes") {
            $paymentMethod = WTConfig::get("Orders/Payment Options/Account/Account Method Name");
            if($paymentMethod == "") {
              $paymentMethod = "Account";
            }
          } else if(WTConfig::get("Orders/Payment Options/PayPal") == "Yes") {
            $paymentMethod = "PayPal";
          } else {
            $paymentMethod = "Credit Card";
          }
        }


        if($this->orderRequiresQuote()) {
          $paymentMethod = "Quote Request";
        }

        $order->setAttributes(Array("Customer Email Address" => $emailAddress, "Subscribe ID" => $subscribe, "Billing Same As Shipping ID" => $fieldBilling, "Customer Name" => $customerName, "Payment Method" => $paymentMethod, "Freight Carrier ID" => $freightCarrier));

        $formType = "Form" . $billingForm->m_guid;
  
        $billingAddress = $GLOBALS["WT"]->getNode($order->m_guid . "/Billing Address");
        if($billingAddress == NULL) {
          $billingAddress = $order->createChild($formType, $billingData);
        } else {
          $billingAddress->setAttributes($billingData);
        }
        $billingAddress->setName("Billing Address");

        $billingCountry = "";
        $billingCountryField = $billingForm->getFieldName("Country");
        if($billingCountryField) {
          $billingCountry = $billingAddress->getAttribute($billingCountryField);
        }


        $fieldBilling = $GLOBALS["WT"]->getRequestValue("FieldBilling");

        $requiresDelivery = $order->getAttribute("Order Requires Delivery");
        $deliveryConfig = WTConfig::get("Orders/Orders Have Delivery");
        if($deliveryConfig) {
          $requiresDelivery = $deliveryConfig;
          if($deliveryConfig == "No") {
            $order->setAttributes(Array("Order Requires Delivery" => "No"));
          }
        }


        if($fieldBilling) {


          $deliveryAddress = $GLOBALS["WT"]->getNode($order->m_guid . "/Delivery Address");
          if($deliveryAddress == NULL) {
            $deliveryAddress = $order->createChild($formType, $billingData);
          } else {
            $deliveryAddress->setAttributes($billingData);
          }
          $deliveryAddress->setName("Delivery Address");

          $orderValue = $order->getTotal(false);
          $postcodeField = $billingForm->getFieldName("Postcode");
          if($postcodeField == 'Field') {
            $postcodeField = $billingForm->getFieldName("Company Postcode");
          }


          $postcode = $deliveryAddress->getAttribute($postcodeField);

          $country = "";
          $countryField = $billingForm->getFieldName("Country");
          if($countryField) {
            $country = $deliveryAddress->getAttribute($countryField);
          }
      
          $freightCarrierID = $order->getAttribute("Freight Carrier ID");
          $freight = $this->getFreight(Array("Order ID" => $order->m_guid, "country" => $country, "postcode" => $postcode, "order value" => $orderValue, "Freight Carrier ID" => $freightCarrierID));


          if($freight === false) {
            $page = $GLOBALS["WT"]->getRequestURI();
            $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "billingdetails");
          } else {
            $order->setAttributes(Array("Freight" => $freight));

            // subtract gst if not from australia
            $gstNode = $GLOBALS["WT"]->getNode("/Config/Node Types/wtOrder/GST");
            if($gstNode && $billingCountry != "") {
              $gst = 0; 
              if($billingCountry != "Australia") {
                $orderTotal = $order->getTotal(false, true, false);
                $gst = ($orderTotal / 11);
                $gst = number_format($gst, 2);                   
              } 
              $order->setAttributes(Array("GST" => $gst));

            }
            

            $page = $GLOBALS["WT"]->getRequestURI();
            if(array_key_exists("WTCARTSUMMARYSTEP", $GLOBALS)) {
              $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", $GLOBALS["WTCARTSUMMARYSTEP"]);
            } else {
              $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "summary");
            }
          }
          header("Location: $page");

        } else if($requiresDelivery == "No") {
          $page = $GLOBALS["WT"]->getRequestURI();
          $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "summary");
          header("Location: $page");

        } else {
          $page = $GLOBALS["WT"]->getRequestURI();
          $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "deliverydetails");
          header("Location: $page");
        }
        exit("");
        break;

      case 'setdeliverydetails':
        $order = $this->getOrder();
        $deliveryForm = $GLOBALS["WT"]->getNode("/Forms/Order Delivery Form");
        if(!$deliveryForm) {
          $deliveryForm = $GLOBALS["WT"]->getNode("/Forms/Order Address");
        }
        $deliveryData = $deliveryForm->requestData(false);

        $formType = "Form" . $deliveryForm->m_guid;

        $deliveryAddress = $GLOBALS["WT"]->getNode($order->m_guid . "/Delivery Address");
        if($deliveryAddress == NULL) {
          $deliveryAddress = $order->createChild($formType, $deliveryData);
        } else {
          $deliveryAddress->setAttributes($deliveryData);
        }
        $deliveryAddress->setName("Delivery Address");

        $orderValue = $order->getTotal(false);
        $postcodeField = $deliveryForm->getFieldName("Postcode");
        if($postcodeField == 'Field') {
          $postcodeField = $deliveryForm->getFieldName("Company Postcode");
        }

        $postcode = $deliveryAddress->getAttribute($postcodeField);

        $country = "";
        $countryField = $deliveryForm->getFieldName("Country");
        if($countryField) {
          $country = $deliveryAddress->getAttribute($countryField);
        }

        $freightCarrierID = $order->getAttribute("Freight Carrier ID");
        $freight = $this->getFreight(Array("Order ID" => $order->m_guid, "country" => $country, "postcode" => $postcode, "order value" => $orderValue, "Freight Carrier ID" => $freightCarrierID));
        if($freight === false) {
          $page = $GLOBALS["WT"]->getRequestURI();
          $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "deliverydetails");
        } else {
          $order->setAttributes(Array("Freight" => $freight));


            // subtract gst if not from australia
            $gstNode = $GLOBALS["WT"]->getNode("/Config/Node Types/wtOrder/GST");
            if($gstNode && $billingCountry != "") {
              $gst = 0;
              if($billingCountry != "Australia") {
                $orderTotal = $order->getTotal(false, true, false);
                $gst = ($orderTotal / 11);
                $gst = number_format($gst, 2);
              }
              $order->setAttributes(Array("GST" => $gst));

            }




          $page = $GLOBALS["WT"]->getRequestURI();

          if(array_key_exists("WTCARTSUMMARYSTEP", $GLOBALS)) {
            $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", $GLOBALS["WTCARTSUMMARYSTEP"]);
          } else {
            $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "summary");
          }
        }

        header("Location: $page");
        exit("");
        break;         
        
      case 'setbilling':
print "set billing";
exit("");
/*
        $order = $this->getOrder();
        $addressForm = $GLOBALS["WT"]->getNode("/Forms/Order Address");
        $formType = "Form" . $addressForm->m_guid;
        $billing = $GLOBALS["WT"]->getNode($order->m_guid . "/Billing Address");
        if($billing == NULL) {
          $billing = $order->createChild($formType, $_REQUEST);
        } else {
          $billing->setAttributes($_REQUEST);
        } 
        $billing->setName("Billing Address");
       
        $order->setAttributes(Array("Billing Same As Shipping ID" => 0)); 
        $page = $GLOBALS["WT"]->getRequestURI();
        $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "summary");
        header("Location: $page");
        break;
*/
      case 'ccpayment':
        $order = $this->getOrder();
        $page = $GLOBALS["WT"]->getRequestURI();


       
        $encryptedEmail = WTConfig::get("Orders/Payment Options/Credit Card/Send As Encrypted Email") == "Yes";

        if($order != NULL) {
          $paid = $order->getAttribute("Paid");
          if($paid != "Yes") {

            $debug = $GLOBALS["WT"]->getNode("/Config/Settings/Ctel/Debug");
          
            $args = Array();  
            if($debug->getAttribute("Value") == "Yes") {
              $args["Debug"] = 1;     
 
            }


            $order->setAttributes(Array("Card Type" => $GLOBALS["WT"]->getRequestValue("cardType") ));

  

            $args["Card Type"] = $GLOBALS["WT"]->getRequestValue("cardType");
            $args["CardHolderName"] = $GLOBALS["WT"]->getRequestValue("cardHolderName");
            $args["CardNumber"] = str_replace(" ", "", $GLOBALS["WT"]->getRequestValue("cardNumber"));
            $args["CardExpiry"] = $GLOBALS["WT"]->getRequestValue("expMonth") . $GLOBALS["WT"]->getRequestValue("expYear");
            $args["CardSecurityNumber"] = $GLOBALS["WT"]->getRequestValue("cardSecNum");
	    $args["Amount"] = $order->getTotal();


            $paymentReference = WTConfig::get("Orders/Payment Options/Credit Card/Payment Reference");

            if($paymentReference) {
              $paymentReference = WTTemplate::compileAndEvaluate($paymentReference, $order->getAttributes());
            } else {
              $paymentReference = "Order #: " . $order->getAttribute("Order Number");
            }
            $args["CustomerReference"] = $paymentReference;


//            $args["CustomerReference"] = "Order #: " . $order->getAttribute("Order Number");

            $successful = false;
            if(!$encryptedEmail) {
              $transaction = WTTransaction::ccPayment($args);

              $GLOBALS["WT"]->linkNodes($order, $transaction);

              if($transaction) {
                $successful = $transaction->getAttribute("Successful ID");
              }

/*
              if($_SERVER["REMOTE_ADDR"] == "203.122.246.187") {
                $successful = 1;
              }
*/

            }


            if($successful == 1 || $encryptedEmail) {
              $this->clear();

              if($encryptedEmail) {
                $order->setAttributes(Array("Paid ID" => 0, "Order Date" => date("Y-m-d H:i:s")));
              } else {
                $order->setAttributes(Array("Paid ID" => 1, "Order Date" => date("Y-m-d H:i:s")));
                $order->activateDownloads();
                $this->recordOrder($order);
              }


              $sendEmailAsName = $GLOBALS["WT"]->getWTValue("wt.settings.Orders.Send Email As Name");
              $sendEmailAsAddress = $GLOBALS["WT"]->getWTValue("wt.settings.Orders.Send Email As Address");
              $sendEmailCopyTo = $GLOBALS["WT"]->getWTValue("wt.settings.Orders.Send Email Copy To");

              $subject = WTOrder::getNotificationSubject("payment confirmation email");
              $message = WTOrder::getNotificationMessage("payment confirmation email");

              if($subject == "") {
                $subject = $GLOBALS["WT"]->getWTValue("wt.settings.Orders.Confirmation Email Subject");
                $message = $GLOBALS["WT"]->getWTValue("wt.settings.Orders.Confirmation Email Message");
              }


              $data = Array();
              $data["Order Number"] = $order->getAttribute("Order Number");
              $data["Order Summary"] = $order->render(Array("Inline Styles" => "yes"));
              $data["Payment Method"] = $order->getAttribute("Payment Method");
              $cardType = $order->getAttribute("Card Type");
              if($cardType) {
                $data["Payment Method"] .= " ($cardType)";
              }


              $form = $GLOBALS["WT"]->getNode("/Forms/Order Billing Form");
              if(!$form) {
                $form = $GLOBALS["WT"]->getNode("/Forms/Order Address");
              }
              $billing = $GLOBALS["WT"]->getNode($order->m_guid . "/Billing Address");
              $firstNameField = $form->getFieldName("First Name");
              $data["First Name"] = $billing->getAttribute($firstNameField);
              $lastNameField = $form->getFieldName("Last Name");
              $data["Last Name"] = $billing->getAttribute($lastNameField);
              $emailAddressField = $form->getFieldName("Email Address");
              if($emailAddressField) {
                $customerEmailAddress = $billing->getAttribute($emailAddressField);
                if($customerEmailAddress) {
                  $order->setAttributes(Array("Customer Email Address" => $customerEmailAddress));              
                }
              }
              $subscribeField = $form->getFieldName("Subscribe to our newsletter");
              if($subscribeField) {
                $subscribe = $billing->getAttribute($subscribeField);
                if($subscribe) {
                  $order->setAttributes(Array("Subscribe" => "Yes"));
                }
              }

              $customerEmailAddress = trim($order->getAttribute("Customer Email Address"));
             

              foreach($data as $key => $value) { 
                $subject = str_replace("[$key]", $value, $subject);
                $message = str_replace("[$key]", $value, $message);
              }


              if($GLOBALS["WTSITEID"] == 11482) {
                // TODO: everyone should use $order->sendEmail();
                $order->sendEmail();
              } else {
                $wtMail = new WTMail();
                $wtMail->setTo($customerEmailAddress);
                $wtMail->setFrom($sendEmailAsAddress, $sendEmailAsName);
                $wtMail->setReplyTo($sendEmailAsAddress);
                $wtMail->setContent($subject, "<html><body>" . $message . "</body></html>", true);
                $wtMail->send();
              }


              if($encryptedEmail) {
		/*
                  $ccData = '';
                  $ccData = '<table style="border-collapse: collapse">';
                  foreach($args as $key => $value) {
                    $ccData .= '<tr>';
                    $ccData .= '<th style="border: 1px solid #aaa; text-align: left">' . $key . '</th>';
                    $ccData .= '<td style="border: 1px solid #aaa;">' . $value . '</td>';
                    $ccData .= '</tr>';
                  } 
                  $ccData .= '</table>';

                  $message .= $ccData; 
		*/

		//Text based Email, so we can encrypt it correctly
		$ccData = 'Order'."\n";
		$ccData .= '---------------------------------------------------------------------------'."\n";
		$ccData .= '#:              '.$order->getAttribute("Order Number")."\n";
		$ccData .= 'Date:           '.date("d/m/Y",strtotime($order->getAttribute("Order Date")))."\n";
		$ccData .= 'Amount          '.$order->getTotal()."\n\r";
		$ccData .= 'Credit Card'."\n";
		$ccData .= '---------------------------------------------------------------------------'."\n";
		foreach($args as $key => $value) {
		  if ($key == "Card Type") $ccData .= $key.":".'               '.$value; //15
		  if ($key == "CardHolderName") $ccData .= $key.":".'          '.$value; //10
		  if ($key == "CardNumber") $ccData .= $key.":".'              '.$value; //14
		  if ($key == "CardExpiry") $ccData .= $key.":".'              '.$value; //14
		  if ($key == "CardSecurityNumber") $ccData .= $key.":".'      '.$value; //6
		  if ($key == "Amount") $ccData .= $key.":".'                  '.$value; //18
		  if ($key == "CustomerReference") $ccData .= $key.":".'       '.$value; //7
		  $ccData .= "\n";
		}             
		     
		$ccData .= "\n".'Order Details can be found in the Office'."\n";

                  $key = WTConfig::get("Encryption");

                  $wtMail->setEncrypt(true, $key);
                  //$wtMail->setContent($subject, "<html><body>" . $message . "</body></html>", true);
		  $wtMail->setContent($subject, $ccData);
              }

              $wtMail->setTo($sendEmailCopyTo);
              $wtMail->send();


              $order->setAttributes(Array("Customer Name" => $data["First Name"] . " " . $data["Last Name"], "Status" => "Pending"));
 
              if($order->getAttribute("Subscribe ID") == 1 && $customerEmailAddress != "") {
                $q = Array();
                $q["Criteria"] = "`Email Address` = '" . mysql_escape_string($customerEmailAddress) . "'";
                $q["Select"] = "COUNT(*)";
                $q["Node Type"] = "Contact";
                $customerExists = $GLOBALS["WT"]->query($q, "singleValueCallback");
                if(!$customerExists) {
                  $contacts = $GLOBALS["WT"]->getNode("/Contacts");
                  if($contacts) {
                    $contact = $contacts->createChild("Contact", Array("First Name" => $data["First Name"], "Last Name" => $data["Last Name"], "Email Address" => $customerEmailAddress, "Wants Contact" => "Yes"));
                    $publicGroup = $GLOBALS["WT"]->getNode("/Groups/Public");
                    if(!$publicGroup) {
                      $publicGroup = $GLOBALS["WT"]->getNode("/Groups/Customer");
                    }
                    if($publicGroup) {
                      $GLOBALS["WT"]->linkNodes($publicGroup, $contact);
                    }
                  }
                } 
              }
              $order->orderSubmitted();
           


              $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "successful");            
              if($GLOBALS["WTSITEID"] == 11358) {
                $page = $GLOBALS["WT"]->setURIParameter($page, "type", "creditcard");
              }

              $page = $GLOBALS["WT"]->setURIParameter($page, "tid", "");
            } else {
              $page = $GLOBALS["WT"]->setURIParameter($page, "tid", $transaction->m_guid);
            }
            header("Location: $page");
            exit("");
          } else {
            $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "successful");
            if($GLOBALS["WTSITEID"] == 11358) {
              $page = $GLOBALS["WT"]->setURIParameter($page, "type", "creditcard");
            }


            $page = $GLOBALS["WT"]->setURIParameter($page, "tid", "");
            header("Location: $page");
            exit("");
          }

        }

        break;
    }
  }


  function renderOrderForm($args) {
    $html = "";

    $templateData = Array();
    $templateFunction = "";
    if(array_key_exists("Template Function", $args)) {
      $templateFunction = $args["Template Function"];
      ob_start();
      $templateFunction($args);
      $templateData["Product List"] = ob_get_contents();
      ob_end_clean();
//      $templateData["Product List"] = $templateFunction($args);
    }

    $addressForm = $GLOBALS["WT"]->getNode("/Forms/Order Address");
    if($addressForm) {

      $templateData["Form Submit JS"] = "return wtFormCheck(this, {" . $addressForm->renderJS() . "})";
      $templateData["Customer Details"] = $addressForm->render(Array("submit" => "", "form" => false), Array());
    }

    
    $orderFormTemplate = $GLOBALS["WT"]->getNode("/Templates/Cart Layouts/Order Form");
    if($orderFormTemplate) {
      return $orderFormTemplate->evaluate($templateData);
    } else {
      $orderFormTemplate = WTTemplate::load($GLOBALS["WTDIRECTORY"] . "templates/cart/orderForm.wt");
      return WTTemplate::compileAndEvaluate($orderFormTemplate, $templateData);
    }
    return $html;
  }  

  function renderSummary() 
  {  
    $order = $this->getOrder();
    $paid = $order->getAttribute("Paid ID");
    $orderStatus = $order->getAttribute("Status");

    if($paid || $orderStatus != '') {
      $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "successful");
      $page = $GLOBALS["WT"]->setURIParameter($page, "tid", "");
      header("Location: $page");
      exit("");
    }
 
    $html = $order->render(Array("Show Change Links" => "yes"));

    $orderByAccount = WTConfig::get("Orders/Payment Options/Account") == "Yes";
    $orderByCreditCard = WTConfig::get("Orders/Payment Options/Credit Card") == "Yes";
    $orderByPayPal = WTConfig::get("Orders/Payment Options/PayPal") == "Yes";
    $orderByQuoteRequest = false;

//    if($orderByAccount && $orderByCreditCard) {
      $paymentMethod = $order->getAttribute("Payment Method");
      if($paymentMethod) {
        $accountMethodName = WTConfig::get("Orders/Payment Options/Account/Account Method Name");
        if($accountMethodName == "") {
          $accountMethodName = "Account";
        }
        $orderByAccount = $paymentMethod == $accountMethodName;//$paymentMethod == "Account" || $paymentMethod == "Process Offline";
        if(!$orderByAccount) {
          $accountMethods = array_map("trim", explode(",", $accountMethodName));
          $orderByAccount = in_array($paymentMethod, $accountMethods);
        }
        $orderByCreditCard = $paymentMethod == "Credit Card";
        $orderByPayPal = $paymentMethod == "PayPal";
        $orderByQuoteRequest = $paymentMethod == "Quote Request";
      }
//    }

    if($orderByAccount) {
      $html .= $this->renderOrderSubmit();
    }

    if($orderByCreditCard) {
      $html .= $this->renderCCPayment();
    }

    if($orderByPayPal) {
      $html .= $this->renderPayPalPayment();
    }

    if($orderByQuoteRequest) {
      $html .= $this->renderQuoteRequest();
    }



    return $html;
  }

  function renderLogin() 
  {
    if($GLOBALS["WT"]->getWTValue("wt.currentuser.ismember")) {
      $this->addCartToOrder();
      $uri = $GLOBALS["WT"]->getWTValue("wt.uri");
      $uri = substr($page, strlen($GLOBALS["WT"]->getSiteSetting("Site Base")));
      $uri = $GLOBALS["WT"]->setURIParameter($uri, "wtCmd", "checkoutstep");
      $uri = $GLOBALS["WT"]->setURIParameter($uri, "wtStep", "checkout");
      header("Location: $uri");
      exit("");
    }

    $loginTemplateNode = $GLOBALS["WT"]->getNode("/Templates/Cart Layouts/Login");
    if($loginTemplateNode) {
      return $loginTemplateNode->evaluate($templateData);
    } else {
      $loginTemplate = WTTemplate::load($GLOBALS["WTDIRECTORY"] . "templates/cart/login.wt");

      return WTTemplate::compileAndEvaluate($loginTemplate, $templateData);
    }

  
  }
  function renderBillingDetails()
  {
    $warnings = "";
    $order = $this->getOrder();


/*     $createdByGuid = $order->getAttribute("__createdByGuid");
    $contact = $GLOBALS["WT"]->getNode($createdByGuid);
    if($contact) {
      $username = $contact->getAttribute("Username");
      if($username) {
        $GLOBALS["WT"]->setUser($username);
      }
    }
*/
    $paid = $order->getAttribute("Paid ID");
    $orderStatus = $order->getAttribute("Status");
    if($paid || $orderStatus != "") {
      $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "successful");
      $page = $GLOBALS["WT"]->setURIParameter($page, "tid", "");
      header("Location: $page");
      exit("");
    }

    $billingForm = $GLOBALS["WT"]->getNode("/Forms/Order Billing Form");
    if(!$billingForm) {
      $billingForm = $GLOBALS["WT"]->getNode("/Forms/Order Address");
    }
    $billingAddress = Array();
    $billingAddressNode = $GLOBALS["WT"]->getNode($order->m_guid . "/Billing Address");
    if($billingAddressNode != NULL) {
      $billingAddress = $billingAddressNode->getAttributes();

      if($order->getAttribute("Billing Same As Shipping") == "Yes") {
        // check the postcode is ok
        $orderValue = $order->getTotal(false);
        $postcodeField = $billingForm->getFieldName("Postcode");
        if($postcodeField == 'Field') {
          $postcodeField = $billingForm->getFieldName("Company Postcode");
        }

        $postcode = $billingAddressNode->getAttribute($postcodeField);
        $country = "";
        $countryField = $billingForm->getFieldName("Country");
        if($countryField) {
          $country = $billingAddressNode->getAttribute($countryField);
        }


        $freightCarrierID = $order->getAttribute("Freight Carrier ID");
        $freight = $this->getFreight(Array("Order ID" => $order->m_guid, "country" => $country, "postcode" => $postcode, "order value" => $orderValue, "Freight Carrier ID" => $freightCarrierID));
        $canDeliver = WTFreight::getCanDeliver(Array("postcode" => $postcode, "order value" => $orderValue, "country" => $country, "weight" => $this->getTotalWeight(true), "quantity" => $this->getTotalQuantity() ));

        if($freight === false || $canDeliver === false) {
          if(!$canDeliver) {
            $warningNode = $GLOBALS["WT"]->getNode("/Config/Settings/Orders/Freight Non Delivery Message");
          } else {
            $warningNode = $GLOBALS["WT"]->getNode("/Config/Settings/Orders/Freight Error Message");
          }
          $value = "";
          if($warningNode != NULL) {
            $value = $warningNode->getAttribute("Value");
          }
          if($value == "") {
            $value = "We do not deliver to your area. Please check your postcode or contact us";
          }
          $warnings .= $value;
        }
      }
    }

    // do a query to work out how many freight carriers there are
    $q = Array();
    $q["Node Type"] = "Freight Carrier";
    $q["Path"] = "/Products/Freight/*";
    $q["Select"] = "COUNT(*)";
    $freightCarrierCount = $GLOBALS["WT"]->query($q, "singleValueCallback");

    $jsdefinition = $billingForm->renderJS();
    $jsdefinition = '{' . $jsdefinition . ",FieldBilling:'required'";
    if($freightCarrierCount > 0) {
      $jsdefinition .= ",FreightCarrier:'required'";
    }
    if($GLOBALS["WTVARSbillingrequiredfields"]) {
      $jsdefinition .= "," . $GLOBALS["WTVARSbillingrequiredfields"];
    }
    $jsdefinition .= '}';
    
    $templateData = Array();
    $templateData["Form Submit JS"] = 'return wtFormCheck(this, ' . $jsdefinition . ')';
    $templateData["Subscribe"] = $order->getAttribute("Subscribe ID");
    $templateData["Billing Same As Shipping"] = $order->getAttribute("Billing Same As Shipping");
    $templateData["Freight Carrier ID"] = $order->getAttribute("Freight Carrier ID");
    $templateData["Payment Method"] = $order->getAttribute("Payment Method");
    if($templateData["Payment Method"] == "") {
      $templateData["Payment Method"] = "Credit Card";
    }

    $templateData["Order Requires Delivery"] = $order->getAttribute("Order Requires Delivery");

    $templateData["Order Warning"] = $warnings;
    $templateData["Billing Form"] = $billingForm->render(Array("submit" => "", "form" => false, "required field message" => false), $billingAddress);
    $templateData["Form Conditions JS"] = $GLOBALS["WTFORMCONDITIONJS"];

    $templateData["orderguid"] = $order->m_guid;

    $billingTemplateNode = $GLOBALS["WT"]->getNode("/Templates/Cart Layouts/Billing");
    if($billingTemplateNode) {
      return $billingTemplateNode->evaluate($templateData);   
    } else {
      $billingTemplate = WTTemplate::load($GLOBALS["WTDIRECTORY"] . "templates/cart/billingdetails.wt");

      return WTTemplate::compileAndEvaluate($billingTemplate, $templateData);
    }
  }

  function renderDeliveryDetails()
  {
    $warnings = "";
    $order = $this->getOrder();
    $paid = $order->getAttribute("Paid ID");
    $orderStatus = $order->getAttribute("Status");

    if($paid || $orderStatus != "") {
      $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "successful");
      $page = $GLOBALS["WT"]->setURIParameter($page, "tid", "");
      header("Location: $page");
      exit("");
    }

    $deliveryForm = $GLOBALS["WT"]->getNode("/Forms/Order Delivery Form");
    if(!$deliveryForm) {
      $deliveryForm = $GLOBALS["WT"]->getNode("/Forms/Order Address");
    }    
    $deliveryAddress = Array();

    $deliveryAddressNode = $GLOBALS["WT"]->getNode($order->m_guid . "/Delivery Address");
    if($deliveryAddressNode != NULL) {
      $deliveryAddress = $deliveryAddressNode->getAttributes();

      $orderValue = $order->getTotal(false);
      $postcodeField = $deliveryForm->getFieldName("Postcode");
      if($postcodeField == 'Field') {
        $postcodeField = $deliveryForm->getFieldName("Company Postcode");
      }

      $postcode = $deliveryAddressNode->getAttribute($postcodeField);

      $country = "";
      $countryField = $deliveryForm->getFieldName("Country");
      if($countryField) {
        $country = $deliveryAddressNode->getAttribute($countryField);
      }

      $freightCarrierID = $order->getAttribute("Freight Carrier ID");

      $freight = $this->getFreight(Array("Order ID" => $order->m_guid, "country" => $country, "postcode" => $postcode, "order value" => $orderValue, "Freight Carrier ID" => $freightCarrierID));
      $canDeliver = WTFreight::getCanDeliver(Array("postcode" => $postcode, "order value" => $orderValue, "country" => $country, "weight" => $this->getTotalWeight(true), "quantity" => $this->getTotalQuantity() ));

      if($freight === false || $canDeliver === false) {
        if(!$canDeliver) {
          $warningNode = $GLOBALS["WT"]->getNode("/Config/Settings/Orders/Freight Non Delivery Message");
        } else {
          $warningNode = $GLOBALS["WT"]->getNode("/Config/Settings/Orders/Freight Error Message");
        }

        $value = "";
        if($warningNode != NULL) {
          $value = $warningNode->getAttribute("Value");
        }
        if($value == "") {
          $value = "We do not deliver to your area. Please check your postcode or contact us";
        }
        $warnings .= $value;
      }     
    }


    $hideEmail = WTConfig::get("Orders/Hide Email in Delivery Address");

   
    if($hideEmail != 'No') { 
      $jsdefinition = $deliveryForm->renderJS(Array("omit" => "Email Address"));
    } else {
      $jsdefinition = $deliveryForm->renderJS(Array());
    }
    $jsdefinition = '{' . $jsdefinition . '}';

    $templateData = Array();
    $templateData["orderguid"] = $order->m_guid;
    $templateData["Order Warning"] = $warnings;
    $templateData["Form Submit JS"] = 'return wtFormCheck(this, ' . $jsdefinition . ')';
    if($hideEmail != 'No') {
      $templateData["Delivery Form"] = $deliveryForm->render(Array("submit" => "", "form" => false, "omit" => "Email Address"), $deliveryAddress);
    } else {
      $templateData["Delivery Form"] = $deliveryForm->render(Array("submit" => "", "form" => false), $deliveryAddress);
    }

    $deliveryTemplateNode = $GLOBALS["WT"]->getNode("/Templates/Cart Layouts/Delivery");
    if($deliveryTemplateNode) {
      return $deliveryTemplateNode->evaluate($templateData);
    } else {
      $deliveryTemplate = WTTemplate::load($GLOBALS["WTDIRECTORY"] . "templates/cart/deliverydetails.wt");

      return WTTemplate::compileAndEvaluate($deliveryTemplate, $templateData);
    }

  }
/*
  function renderShipping() 
  {
    $order = $this->getOrder();

    $createdByGuid = $order->getAttribute("__createdByGuid");
//    print "created By $createdByGuid";
    $contact = $GLOBALS["WT"]->getNode($createdByGuid);
    if($contact) {
      $username = $contact->getAttribute("Username");
      if($username) {
        $GLOBALS["WT"]->setUser($username);
      }
    }
    $paid = $order->getAttribute("Paid ID");
    $orderStatus = $order->getAttribute("Status");
    $warnings = '';

    if($paid || $orderStatus != "") {
      $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "successful");
      header("Location: $page");
      exit("");
    }


    $addressForm = $GLOBALS["WT"]->getNode("/Forms/Order Shipping Form");
    if(!$addressForm) {
      $addressForm = $GLOBALS["WT"]->getNode("/Forms/Order Address");
    }

    $shippingInstructionsForm = $GLOBALS["WT"]->getNode("/Forms/Order Shipping Instructions");
   
    $html = '';
    $jsdefinition = "FieldEmail:'requiredemail'," . $addressForm->renderJS();
//    $jsdefinition .= ",FieldEmail:'requiredemail'";

    $jsdefinition .= ",FieldBilling:'required'";
    if($shippingInstructionsForm) {
      $shippingInstructionsFormJS = $shippingInstructionsForm->renderJS();
      if($shippingInstructionsFormJS) {
        $jsdefinition .= "," . $shippingInstructionsFormJS;
      }
    }
    $jsdefinition = '{' . $jsdefinition . '}';

    $templateData = Array();
    
    $templateData["Form Submit JS"] = 'return wtFormCheck(this, ' . $jsdefinition . ')';
    $templateData["Customer Email Address"] = $order->getAttribute("Customer Email Address");
    $templateData["Subscribe"] = $order->getAttribute("Subscribe ID");
    $templateData["Billing Same As Shipping"] = $order->getAttribute("Billing Same As Shipping");


    $values = Array();
    $shipping = $GLOBALS["WT"]->getNode($order->m_guid . "/Shipping Address");
    if($shipping != NULL) {
      $values = $shipping->getAttributes();
      $shippingForm = $GLOBALS["WT"]->getNode("/Forms/Order Shipping Form");
      if(!$shippingForm) {
        $shippingForm = $GLOBALS["WT"]->getNode("/Forms/Order Address");
      }
      $postcodeField = $shippingForm->getFieldName("Postcode");
      $postcode = $shipping->getAttribute($postcodeField);
//      $weight = $this->getTotalWeight();
//      $freight = WTFreight::getCharge(Array("postcode" => $postcode, "weight" => $weight));
      $orderValue = $order->getTotal(false);
      $freight = $this->getFreight(Array("postcode" => $postcode, "order value" => $orderValue));
      $canDeliver = WTFreight::getCanDeliver(Array("postcode" => $postcode, "order value" => $orderValue));

      if($freight === false || $canDeliver === false) {
        if(!$canDeliver) {
          $warningNode = $GLOBALS["WT"]->getNode("/Config/Settings/Orders/Freight Non Delivery Message");
        } else {
          $warningNode = $GLOBALS["WT"]->getNode("/Config/Settings/Orders/Freight Error Message");
        }
        if($warningNode != NULL) {
          $value = $warningNode->getAttribute("Value");
          if($value == "") {
            $value = "We do not deliver to your area. Please check your postcode or contact us";
          }
          $warnings .= $value;
          
//          $warnings .= $warningNode->getAttribute("Value");
        }
//        $warnings .= "We do not deliver to your area. Please check your postcode or contact us";
      }

    }

    
    $templateData["Order Warning"] = $warnings;
    $templateData["Shipping Form"] = $addressForm->render(Array("submit" => "", "form" => false), $values);


    if($shippingInstructionsForm) {
      $values = Array();
      $shippingInstructions = $GLOBALS["WT"]->getNode($order->m_guid . "/Shipping Instructions");
      if($shippingInstructions != NULL) {
        $values = $shippingInstructions->getAttributes();
      }
      $templateData["Shipping Instructions Form"] = $shippingInstructionsForm->render(Array("submit" => "", "form" => false), $values);
    }





    $shippingInstructionsForm = $GLOBALS["WT"]->getNode("/Forms/Order Shipping Instructions");
    if($shippingInstructionsForm) {

    }

    $templateData["orderguid"] = $order->m_guid;

    $shippingTemplateNode = $GLOBALS["WT"]->getNode("/Templates/Cart Layouts/Shipping");
    if($shippingTemplateNode) {
      return $shippingTemplateNode->evaluate($templateData);
   //   $shippingTemplate = $shippingTemplateNode->getAttribute("Source");
   
    } else {
      $shippingTemplate = WTTemplate::load($GLOBALS["WTDIRECTORY"] . "templates/cart/shipping.wt");
      return WTTemplate::compileAndEvaluate($shippingTemplate, $templateData);
    }

  }

  function renderBilling() {
    $order = $this->getOrder();

    $addressForm = $GLOBALS["WT"]->getNode("/Forms/Order Billing Form");
    if(!$addressForm) {
      $addressForm = $GLOBALS["WT"]->getNode("/Forms/Order Address");
    }
//    $addressForm = $GLOBALS["WT"]->getNode("/Forms/Order Address");
    $html = '';

    $jsdefinition = $addressForm->renderJS();
    $jsdefinition = '{' . $jsdefinition . '}';

    $templateData = Array();

    $billingTemplateNode = $GLOBALS["WT"]->getNode("/Templates/Cart Layouts/Billing");
    if($billingTemplateNode) {
      $billingTemplate = $billingTemplateNode->getAttribute("Source");
    } else {
      $billingTemplate = WTTemplate::load($GLOBALS["WTDIRECTORY"] . "templates/cart/billing.wt");
    }

    $templateData["Form Submit JS"] = 'return wtFormCheck(this, ' . $jsdefinition . ')';

    $values = Array();
    $billing = $GLOBALS["WT"]->getNode($order->m_guid . "/Billing Address");
    if($billing != NULL) {
      $values = $billing->getAttributes();
    }
    $templateData["Billing Form"] = $addressForm->render(Array("submit" => "", "form" => false), $values);
  
    return WTTemplate::compileAndEvaluate($billingTemplate, $templateData);  
  }
*/


  function renderPayPalPayment() {

    $order = $this->getOrder();
    $templateData = $order->getAttributes();
    $templateData["Order Total"] = $order->getTotal();

    $form = $GLOBALS["WT"]->getNode("/Forms/Order Billing Form");
    if(!$form) {
      $form = $GLOBALS["WT"]->getNode("/Forms/Order Address");
    }

    $billing = $GLOBALS["WT"]->getNode($order->m_guid . "/Billing Address");
    $templateData["First Name"] = $billing->getAttribute($form->getFieldName("First Name"));
    $templateData["Last Name"] = $billing->getAttribute($form->getFieldName("Last Name"));
    $templateData["Address Line 1"] = $billing->getAttribute($form->getFieldName("Address Line 1"));
    $templateData["Address Line 2"] = $billing->getAttribute($form->getFieldName("Address Line 2"));
    $templateData["Suburb"] = $billing->getAttribute($form->getFieldName("Suburb"));
    $templateData["Postcode"] = $billing->getAttribute($form->getFieldName("Postcode"));
    $templateData["State"] = $billing->getAttribute($form->getFieldName("State"));
    $templateData["Email Address"] = $billing->getAttribute($form->getFieldName("Email Address"));


    $paypalTemplateNode = $GLOBALS["WT"]->getNode("/Templates/Cart Layouts/PayPal Payment");
    if($paypalTemplateNode) {
      return $paypalTemplateNode->evaluate($templateData);
    } else {
      $paypalTemplate = WTTemplate::load($GLOBALS["WTDIRECTORY"] . "templates/cart/paypalPayment.wt");
    }
    return WTTemplate::compileAndEvaluate($paypalTemplate, $templateData);
  }

  function renderQuoteRequest() {
    $order = $this->getOrder();
    $tid = $GLOBALS["WT"]->getRequestValue("tid");

    $GLOBALS["WTVARSWTORDERID"] = $order->m_guid;

    $templateData = Array();
    if($tid != '') {
      $transaction = $GLOBALS["WT"]->getNode($tid);
      $templateData["Transaction Error"] = $transaction->getAttribute("Description");

    }

    $templateData["Order Total"] = $order->getTotal();


    $quoteRequestTemplateNode = $GLOBALS["WT"]->getNode("/Templates/Cart Layouts/Quote Request");
    if($quoteRequestTemplateNode) {
      return $quoteRequestTemplateNode->evaluate($templateData);
    } else {

      $quoteRequestTemplate = WTTemplate::load($GLOBALS["WTDIRECTORY"] . "templates/cart/quoteRequest.wt");
      return WTTemplate::compileAndEvaluate($quoteRequestTemplate, $templateData);
    }
  }

  function renderCCPayment() {
    $order = $this->getOrder();
    $tid = $GLOBALS["WT"]->getRequestValue("tid");

    $GLOBALS["WTVARSWTORDERID"] = $order->m_guid;

    $templateData = Array();
    if($tid != '') {
      $transaction = $GLOBALS["WT"]->getNode($tid);
      $templateData["Transaction Error"] = $transaction->getAttribute("Description");

    }

    $templateData["Order Total"] = $order->getTotal();

    $ccTemplateNode = $GLOBALS["WT"]->getNode("/Templates/Cart Layouts/CC Payment");
    if($ccTemplateNode) {
//      $ccTemplate = $ccTemplateNode->getAttribute("Source");
      return $ccTemplateNode->evaluate($templateData);
    } else {
      $ccTemplate = WTTemplate::load($GLOBALS["WTDIRECTORY"] . "templates/cart/ccPayment.wt");
      return WTTemplate::compileAndEvaluate($ccTemplate, $templateData);
    }

//    return WTTemplate::compileAndEvaluate($ccTemplate, $templateData);
  }

  function renderOrderSubmit() {
    $templateData = Array();
    $order = $this->getOrder();
    $orderTemplateNode = $GLOBALS["WT"]->getNode("/Templates/Cart Layouts/Order Submit");

    $templateData["Order Total"] = $order->getTotal();
    if($orderTemplateNode) {
      return $orderTemplateNode->evaluate($templateData);
    } else {
      $orderTemplate = WTTemplate::load($GLOBALS["WTDIRECTORY"] . "templates/cart/orderSubmit.wt");
      return WTTemplate::compileAndEvaluate($orderTemplate, $templateData);
    }
  }

  /**
   *  Create an order node from the cart contents
   *
   *  @return {int} The number of distinct items in the cart
   */
  function addCartToOrder() {
    $order = $this->getOrder();
    $orderStatus = $order->getAttribute("Status");
    if($order->getAttribute("Paid ID") == 1 || $orderStatus != "") {
      $order = $this->getOrder(true);
    }

    $currentUser = $GLOBALS["WT"]->getCurrentUser();
    $order->setCreatedBy($currentUser->m_guid);

    $order->setAttributes(Array("Session Data" => serialize($_SESSION)));

    $resultArray = Array();    
    $q = Array();
    $q["Node Type"] = "wtOrderItem";
    $q["Path"] = $order->m_guid . "/*";
    $q["Results Array"] = &$resultArray;
    $q["Select"] = "wtOrderItem.__guid";
    $GLOBALS["WT"]->query($q);
    foreach($resultArray as $result) {
      $node = $GLOBALS["WT"]->getNode($result["__guid"]);
      $node->deleteNode();
    }

    $subtotal = 0;
    $cart = WTSession::get($this->m_cartName);

    $orderRequiresDelivery = "No";

    foreach($cart as $key => $attributes) {
      $quantity = $attributes["quantity"];
      $productGuid = $attributes["productGuid"];      

      if($productGuid) {
        $product = $GLOBALS["WT"]->getNode($productGuid);
        $code = $product->getAttribute("Code");
        $name = $product->getAttribute("Name");
        $price = $product->getPrice($quantity, $quantity);

        if(array_key_exists("optionpricealteration", $attributes)) {
          $price += $attributes["optionpricealteration"];
        }


        if($product->getAttribute("Product Type") != "Image") {
          $orderRequiresDelivery = "Yes";
        }
      } else {
        $code = $attributes["Code"];
        $name = $attributes["Name"];
        $price = $attributes["Price"];
        $productGuid = 0;
      }

      if(array_key_exists("price", $attributes)) {
        $price = $attributes["price"];
      }

      if(array_key_exists("description", $attributes)) {
        $name .= '<br/>' . $attributes["description"];
      }
      $description = "";

      $subtotal += $price;

      $order->createChild("wtOrderItem", Array("Code" => $code, "Name" => $name, "Description" => $description, "Price" => $price, "Quantity" => $quantity, "Product ID" => $productGuid, "Options" => $key ));
    }

    $discount = $this->getDiscount();
    $order->setAttributes(Array("Discount" => $discount, "Order Requires Delivery" => $orderRequiresDelivery));


  }


  /**
   *  Return the discount for the cart
   *
   *  @method getDiscount
   *  @return {int} The discount in dollars and cents
   */
  function getDiscount() { 



    $discount = 0;

    if($GLOBALS["WTCARTDISCOUNTFUNCTION"]) {
      $args = Array();
      return call_user_func($GLOBALS["WTCARTDISCOUNTFUNCTION"], $args);
    }


    if(WTConfig::get("Orders/Discount") == "Yes") {

      $defaultDiscount = WTConfig::get("Orders/Discount/Default Discount Percent");

      $defaultDiscountNode = $GLOBALS["WT"]->getNode("/Config/Settings/Orders/Discount/Default Discount Percent");


      if($defaultDiscountNode) {

        $subtotal = $this->getTotal();

        $currentUser = $GLOBALS["WT"]->getCurrentUser();
        $userDiscount = $currentUser->getDiscount();
        if($userDiscount > $defaultDiscount) {
          $defaultDiscount = $userDiscount;
        }


        $discount = ($subtotal * $defaultDiscount) / 100;


      } else {
        $discountPercent = WTConfig::get("Orders/Discount/Discount Percent");
        $discountQuantity = WTConfig::get("Orders/Discount/Discount Quantity");

        $quantity = $this->getTotalQuantity();

        $subtotal = $this->getTotal();
       
        if($quantity >= $discountQuantity) {
          $discount = ($subtotal * $discountPercent) / 100;
        }
      }
    } else {
      $subtotal = $this->getTotal();
      $discount = 0;
      $currentUser = $GLOBALS["WT"]->getCurrentUser();
      $discountPercent = $currentUser->getDiscount();
      if($discountPercent > 0) {
        $discount = ($subtotal * $discountPercent) / 100;
      }
    }
    return $discount;
  }

  function renderSuccessful() {
    $html = '';

    $order = $this->getOrder();


    $subject = "";
    $message = "";
    $paymentMethod = $order->getAttribute("Payment Method");    
    $accountMethodName = WTConfig::get("Orders/Payment Options/Account/Account Method Name");
    if($accountMethodName == "") {
      $accountMethodName = "Account";
    }


    $accountMethods = array_map("trim", explode(",", $accountMethodName));


    if($paymentMethod != "" && ($paymentMethod == $accountMethodName || in_array($paymentMethod, $accountMethods) )) { //$paymentMethod == "Account" || $paymentMethod == "Process Offline") {
      $subject = WTOrder::getNotificationSubject("account order received");
      $message = WTOrder::getNotificationMessage("account order received");

      if($subject == "" && $message == "") {
        $message = WTConfig::get("Orders/Payment Options/Account/Account Payment Instructions");
      }



    } else if($paymentMethod == "Credit Card") {
      $subject = WTOrder::getNotificationSubject("credit card order successful");
      $message = WTOrder::getNotificationMessage("credit card order successful");

    } else if($paymentMethod == "Quote Request") {
      $subject = WTOrder::getNotificationSubject("quote request received");
      $message = WTOrder::getNotificationMessage("quote request received");
    }


    if($subject == "" && $message == "") {
      $message = WTConfig::get("Orders/Confirmation Message");
    }
    $data = $order->getAttributes();


    $data["Order Number"] = $order->getAttribute("Order Number");
    $data["Order Summary"] = $order->render();
    $form = $GLOBALS["WT"]->getNode("/Forms/Order Address");
    $billing = $GLOBALS["WT"]->getNode($order->m_guid . "/Billing Address");
    if($billing) {
      $firstNameField = $form->getFieldName("First Name");
      $data["First Name"] = $billing->getAttribute($firstNameField);
      $lastNameField = $form->getFieldName("Last Name");
      $data["Last Name"] = $billing->getAttribute($lastNameField);
    }

    foreach($data as $key => $value) {
      $message = str_replace("[$key]", $value, $message);
    }
    $html .= $message;

    return $html;
  
  }

/*
  function setOrder($guid, $key) {
    if(!is_numeric($guid)) {
      return false;
    }
    $key = mysql_escape_string($key);

    $q = Array();
    $q["Node Type"] = "wtOrder";
    $q["Criteria"] = "wtOrder.__guid = $guid AND `Key` = '$key'";
    $q["Select"] = "wtOrder.__guid";
    $orderGuid = $GLOBALS["WT"]->query($q, "singleValueCallback");
    if($orderGuid != 0) {
//      $_SESSION["WTORDER" . $GLOBALS["WTSITEID"]] = $orderGuid;
      WTSession::set("WTORDER" . $GLOBALS["WTSITEID"], $orderGuid);
      $order = $GLOBALS["WT"]->getNode($orderGuid); 
      if($order) {
        $sessionData = unserialize($order->getAttribute("Session Data"));
        $_SESSION[$this->m_cartName] = $sessionData[$this->m_cartName];
      }
      return true;
    }
    return false;
  }
*/

  /**
   *  Return the current order node object
   *
   *  @method getOrder
   *  @return {WTOrder} The current order node object
   */

  function getOrder($neworder = false) {
    $orderGuid = WTSession::get("WTORDER" . $GLOBALS["WTSITEID"]);

    if($orderGuid && !$neworder) {
      return $GLOBALS["WT"]->getNode($orderGuid);
    } else {
      $orders = $GLOBALS["WT"]->getNode("/Orders");
      $order = $orders->createChild("wtOrder", Array());
      $key = md5(uniqid(rand(), true));
      $order->setAttributes(Array("Order Number" => $order->m_guid, "Key" => $key));
      WTSession::set("WTORDER" . $GLOBALS["WTSITEID"], $order->m_guid);
//      $_SESSION["WTORDER" . $GLOBALS["WTSITEID"]] = $order->m_guid;

      $deliveryConfig = WTConfig::get("Orders/Orders Have Delivery");
      if($deliveryConfig) {
        if($deliveryConfig == "No") {
          $order->setAttributes(Array("Order Requires Delivery" => "No"));
        }
      }

      return $order;
    }
  }

  function gotoCheckout() 
  {
//    $order = $this->getOrder();
    $secureURL = WTConfig::get("Site Details/Site Secure URL");
    if($secureURL) {
      $page = $GLOBALS["WT"]->getWTValue("wt.uri");
      $page = substr($page, strlen($GLOBALS["WT"]->getSiteSetting("Site Base")));
      $page = $GLOBALS["WT"]->setURIParameter($page, "wtCmd", "checkoutstep");
      $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "checkout");
      $GLOBALS["WT"]->switchToSecure($page);
      exit("");
      
    } 
  }

};

?>