<?
/**
 * ship_fedex.php
 *
 * @package fedex automated shipping labels
 * @copyright Copyright 2007-2008 Numinix Technology http://www.numinix.com
 * @copyright Portions Copyright 2003-2006 Zen Cart Development Team
 * @copyright Portions Copyright 2003 osCommerce
 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
 * @version $Id: ship_fedex.php 29 2009-08-01 17:21:44Z numinix $
 * @author Numinix Technology
 */

// - makes a form for adding additional info about a shipment
// - sends a ship request to fedex
// - returns a shipping label & formats it for printing
// - cancels an existing ship request
// - builds a shipping manifest

  require('includes/application_top.php');
  
// debugging
// setting to 1 displays the array of all shipping
// and manifest data when a ship request is made

  if (MODULE_SHIPPING_FEDEX_DEBUG == 'true') {
    $debug = 1;
  } else {
    $debug = 0;
  }

  require(DIR_WS_FUNCTIONS . 'ship_fedex.php');

  $action = $_GET['action'];
  $order = $_GET['oID'];

// *** EDIT VARIABLES BELOW **
$lastshipment = MODULE_SHIPPING_FEDEX_SHIPMENT_TIME;            // Define last shipment time (ex: 17 would be 5pm on your server)
if (MODULE_SHIPPING_FEDEX_EMAIL_ON_SHIPPING == 'true') $send_email_on_shipping = 1; 
  else $send_email_on_shipping = 0;

// Modify the variable here and in admin/fedex_popup.php

if (MODULE_SHIPPING_FEDEX_THERMAL_PRINTING == 'label') $thermal_printing = 1;
  else $thermal_printing = 0;

////
// make a new ship request

  if($action=='ship') {
    


    if (!$order) {
      die (ERROR_NO_ORDER_NUMBER);
      }  
    
    foreach($_POST as $key => $value) {
      //if ($value != '') {
        $_SESSION[$key] = $value;
      //}
      //echo $key . ' ' . $_POST[$key] . '<br />';
    }
    
    if ($_GET['source'] != 'post1') {
      if ($_POST['package_num'] > 1) {
        //die();
        zen_redirect(zen_href_link(FILENAME_SHIP_FEDEX_REVERSED, 'cPath=' . $cPath . '&cID=' . $_GET['cID'] . '&oID=' . $order . '&action=post1'));
      }
    }      

    include(DIR_WS_INCLUDES . 'abbreviate.php'); // used to abbreviate state & country names
    require(DIR_WS_INCLUDES . 'fedexdc.php');
    
    
    // multi address modification
    if ($_POST['address_id'] != '' && (int)$_POST['address_id'] > 0) {
      // get alternate address
      $delivery_address_query = "SELECT company, name, address_1, address_2, city, state, zip, country, returns_orders_status_id 
                                 FROM " . TABLE_MULTI_ADDRESS . "
                                 WHERE address_id = " . (int)$_POST['address_id'] . "
                                 LIMIT 1;";
      $delivery_address = $db->Execute($delivery_address_query);
      $delivery_company = $delivery_address->fields['company'];
      $delivery_name = $delivery_address->fields['name'];
      $delivery_address_1 = $delivery_address->fields['address_1'];
      $delivery_address_2 = $delivery_address->fields['address_2'];
      if ($delivery_address_2 == '') $delivery_address_2 = "NONE";
      $delivery_city = $delivery_address->fields['city'];
      $delivery_state = $delivery_address->fields['state'];
      $delivery_zip = $delivery_address->fields['zip'];
      $delivery_country = abbreviate_country(zen_get_country_name($delivery_address->fields['country']));
      $returns_orders_status_id = $delivery_address->fields['returns_orders_status_id'];
    } else {
      // set some defaults
      $delivery_company = MODULE_SHIPPING_FEDEX_COMPANY_NAME;
      $delivery_name = MODULE_SHIPPING_FEDEX_CONTACT_NAME;
      $delivery_address_1 = MODULE_SHIPPING_FEDEX_ADDRESS_1;
      $delivery_address_2 = MODULE_SHIPPING_FEDEX_ADDRESS_2;
      $delivery_city = MODULE_SHIPPING_FEDEX_CITY;
      $delivery_state = MODULE_SHIPPING_FEDEX_STATE;
      $delivery_zip = MODULE_SHIPPING_FEDEX_POSTAL;
      $delivery_country = abbreviate_country(zen_get_country_name(STORE_COUNTRY));
      $returns_orders_status_id = MODULE_SHIPPING_FEDEX_ORDER_STATUS_RETURNED;
    }

    // array of characters we don't want in phone numbers
    $unwanted = array('(',')','-','.',' ','/');

    $transaction_code = 21; // 21 is a ship request
    
    // get all information from the order record
    $order_query = "select * from " . TABLE_ORDERS . " where orders_id = $order";

    $order_info = $db->Execute($order_query);
    
    // build recipient address
    if (isset($_POST['senders_name']) && zen_not_null($_POST['senders_name'])) $senders_name = substr($_POST['senders_name'], 0, 35); else $senders_name = name_length(name_case($order_info->fields['delivery_name']));
    if (isset($_POST['senders_company']) && zen_not_null($_POST['senders_company'])) $senders_company = substr($_POST['senders_company'], 0, 35); else $senders_company = substr($order_info->fields['delivery_company'], 0, 35);
    if (isset($_POST['senders_address_1']) && zen_not_null($_POST['senders_address_1'])) $senders_address_1 = substr($_POST['senders_address_1'], 0, 35); else $senders_address_1 = substr($order_info->fields['delivery_street_address'], 0, 35);
    if (isset($_POST['senders_address_2']) && zen_not_null($_POST['senders_address_2'])) $senders_address_2 = substr($_POST['senders_address_2'], 0, 35); else $senders_address_2 = substr($order_info->fields['delivery_suburb'], 0, 35);
    if (isset($_POST['senders_city']) && zen_not_null($_POST['senders_city'])) $senders_city = substr($_POST['senders_city'], 0, 35); else $senders_city = substr($order_info->fields['delivery_city'], 0, 35);    
    // abbreviate the senders state (function is in abbreviate.php)
    if (isset($_POST['senders_state']) && zen_not_null($_POST['senders_state'])) $senders_state = $_POST['senders_state']; else $senders_state = abbreviate_state($order_info->fields['delivery_state']);   
    // abbreviate the delivery country (function is in abbreviate.php)
    $senders_country = abbreviate_country($order_info->fields['delivery_country']);
    if (isset($_POST['senders_zip']) && zen_not_null($_POST['senders_zip'])) $senders_zip = str_replace(' ', '', $_POST['senders_zip']); else $senders_zip = str_replace(' ', '', $order_info->fields['delivery_postcode']);

    $senders_phone = trim(str_replace($unwanted, '', $_POST['telephone']));

    // abbreviate the delivery state (function is in abbreviate.php)
    $senders_state = abbreviate_state($order_info->fields['delivery_state']);

    // abbreviate the delivery country (function is in abbreviate.php)
    $senders_country = abbreviate_country($order_info->fields['delivery_country']);

    // get rid of dashes, parentheses and periods in customer's telephone number
    $delivery_phone = trim(str_replace($unwanted, '', MODULE_SHIPPING_FEDEX_PHONE));
    // remove "1" from start of phone number
    if (strlen($delivery_phone) > 10) {
      if (strpos($delivery_phone, "1") == 0) {
        $delivery_phone = substr($delivery_phone, 1, 10);
      }
    }
    // get sender's fedex info from configuration table
    if (MODULE_SHIPPING_FEDEX_SERVER == 'production') {
      $fedex_account = MODULE_SHIPPING_FEDEX_ACCOUNT;
    } else {
      $fedex_account = MODULE_SHIPPING_FEDEX_TEST_ACCOUNT;
    }    
    // modified to reverse address
    $fedex_vars = array (
      10=>$fedex_account, // 0
      498=>MODULE_SHIPPING_FEDEX_METER,   // 1
      75=>MODULE_SHIPPING_FEDEX_WEIGHT,  // 2
      4=>$senders_company, //3
      32=>$senders_name,
      5=>$senders_address_1,// 4
      6=>$senders_address_2,// 5
      7=>$senders_city,      // 6
      8=>$senders_state,    // 7
      9=>str_replace(' ', '', $senders_zip),    // 8
      183=>$senders_phone,  // 9
      68=>MODULE_SHIPPING_FEDEX_CURRENCY,                // 10
    );
    $fedex_keys = array_keys($fedex_vars);

    ////
    // create new FedExDC object
    $fed = new FedExDC($fedex_vars[0][10],$fedex_vars[1][498]);

// get the transaction value
//    $value_query = zen_db_query("select value from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $order . "' and class='ot_subtotal'");
//    $order_value = $db->Execute($value_query);
//    $order_value = round($order_value->fields['value'], 0);

//// some form variables

// format the form date (comes in as mm-dd-yyyy)
    $date_array = explode('-',$_POST['pickup_date']);
    $corrected_date = $date_array[2] . $date_array[0] . $date_array[1];

// determine whether the ship date is today or later
    if ($corrected_date == date(Ymd)) {
      $future = 'N'; // today
    }
    else {
      $future = 'Y';  // later date
    }
    if (MODULE_SHIPPING_FEDEX_EMAIL_ON_SHIPPING == 'true') $shipAlert = 'Y'; else $shipAlert = 'N';        
// start the array for fedex
    $shipData = array(
       0    => $transaction_code // transaction code
      ,2399 => $_POST['signature_type'] // signature type
      ,16   => $delivery_state // delivery state
      ,13   => $delivery_address_1 // delivery address
      ,14   => $delivery_address_2 // delivery address line 2
      ,1273 => $_POST['packaging_type'] // packaging type (01 is customer packaging)
      ,1274 => $_POST['service_type'] //
      ,18   => $delivery_phone // recipient's phone number
      ,15   => $delivery_city // delivery city
      ,23   => $_POST['bill_type'] // payment type (1 is bill to sender)
      ,117  => $senders_country // sender's country
      ,17   => str_replace(' ', '', $delivery_zip) // postal code it's going to
      ,50   => $delivery_country // country it's going to
      ,11   => $delivery_company // recipient's company name
      ,12   => $delivery_name // recipient's contact name
      ,1201 => $order_info->fields['customers_email_address'] // sender's email address
      ,1202 => STORE_OWNER_EMAIL_ADDRESS // recipient's email address
      ,1554 => $shipAlert // Shipper ShipAlert Flag 
      ,1557 => 'Y' //Recipient ShipAlert Flag
      ,1333 => $_POST['dropoff_type'] // drop off type (1 is regular pickup)
      ,1415 => number_format(round($_POST['declare_value'], 2), 2, '.', '') // total order value, forced to 2 decimal places
      ,1368 => 2 // label type (2 is standard)
      ,1369 => 1 // printer type (1 is laser)
      ,1370 => (($thermal_printing) ? 7 : 5) // label media (5 is plain paper, 7 is 4x6 image)
      ,3002 => $_POST['package_invoice'] // invoice number
      ,25   => $_POST['package_reference'] // reference number
      ,3001 => $_POST['package_po'] // purchase order number
      ,38   => $_POST['package_department'] // department name
      ,24   => $corrected_date  // ship date
      ,1119 => $future // future day shipment
      ,2975 => 'Y'  // keep your fedex number off the label     
      ,1266 => $_POST['saturday_delivery'] // Saturday delivery
      ,1200 => $_POST['hold_at_location'] // Hold At Fedex Location
      ,44   => $_POST['hal_address'] // Hold At Location address
      ,46   => $_POST['hal_city'] // Hold At Location city
      ,47   => $_POST['hal_state'] // Hold At Location state
      ,48   => $_POST['hal_postcode'] // Hold At Location postal code
      ,49   => $_POST['hal_phone'] // Hold At Location phone number
      ,57   => $_POST['dim_height'] // "your package" height dimension
      ,58   => $_POST['dim_width'] // "your package" width dimension
      ,59   => $_POST['dim_length'] // "your package length dimension
      ,3008 => $_POST['autopod'] // Automatic Proof of Delivery
      );

// if it's home delivery (90), add the "residential delivery flag" (440)
    if ($_POST['service_type'] == 90) {
      $shipData[440] = 'Y';
      }
    else {
      $shipData[440] = 'N';
      }

// if it's a Saturday delivery
    if ($_POST['service_type'] == 03 && $_POST['saturday_delivery'] == 1) {
      $shipData[1266] = 'Y';
      }
    if ($_POST['service_type'] == 01 && $_POST['saturday_delivery'] == 1) {
      $shipData[1266] = 'Y';
      }
    else {
      $shipData[1266] = 'N';
      }

// if it's a Hold At Fedex Location delivery
    if ($_POST['hold_at_location'] == 1) {
      $shipData[1200] = 'Y';
      }
    else {
      $shipData[1200] = 'N';
      }

// if AutoPOD, add AutoPOD flag
    if ($_POST['autopod'] == 1) {
      $shipData[3008] = 'Y';
      }
    else {
      $shipData[3008] = 'N';
      }

// if "your package" type is selected, add the dimensions flag
    if ($_POST['packaging_type'] == 01) {
      $shipData[57] = $_POST['dim_height'];
      $shipData[58] = $_POST['dim_width'];
      $shipData[59] = $_POST['dim_length'];
      }


// if it's an oversized shipment...
    if ($oversized) {
      $shipData[3124] = $_POST['oversized'];
      }

////
// if there's no meter number in the database, ask for a new one
if (MODULE_SHIPPING_FEDEX_SERVER == 'production') {
  $shipping_meter = $fedex_vars[498];
} else {
  $shipping_meter = '';
}
    if (!$shipping_meter) {
      $fed = new FedExDC($fedex_keys[10]);

// variables needed to subscribe
      $requestData = array (
        0 => 211, // 211 is the transaction code for a subscription request
        10 => $fedex_vars[10], // account number
        4003 => $fedex_vars[4], // contact name, using store name for now
        4008 => $fedex_vars[5], // street address
        4011 => $fedex_vars[7], // city
        4012 => $fedex_vars[8], // state
        4013 => $fedex_vars[9], // postal code
        4014 => abbreviate_country(zen_get_country_name(STORE_COUNTRY)), // country
        4015 => $fedex_vars[183] // phone number
        );

      $keyRequest = $fed->subscribe($requestData);
      // todo: add appropriate error checking for at least some of the possible errors
      if ($error = $fed->getError()) {
        echo '<pre>';
        print_r($requestData);
        echo '</pre>';
        echo '<pre>';
        print_r($keyRequest);
        echo '</pre>';
        die("ERROR: ". $error);
      } else {
        if (MODULE_SHIPPING_FEDEX_SERVER == 'production') {
          $db->Execute("update " . TABLE_CONFIGURATION . " set configuration_value = '" . $keyRequest[498] . "' where configuration_key = 'MODULE_SHIPPING_FEDEX_METER'");
        }
        $fedex_vars[498] = $keyRequest[498];
      }
    }
    // end meter request

    // put the form array together with the stuff from the database
    $shipData = $shipData+$fedex_vars;

    // determine shipment type (either ground or express)
    // (this is used in the call to fedexdc.php)
    if (($_POST['service_type'] == 92) or ($_POST['service_type'] == 90)) {
      $ship_type = 'ship_ground';
    } else {
      $ship_type = 'ship_express';
    }

    // request shipment(s) and post data to shipping manifest
    for ($i = 1; $_POST['package_num'] >= $i; $i++) {

      // data for shipping_manifest
      $manifest_data = array (
      //delivery_id => '',
      orders_id => $order,
      delivery_name => name_case($delivery_name),
      delivery_company => $delivery_company,
      delivery_address_1 => $delivery_address_1,
      delivery_address_2 => $delivery_address_2,
      delivery_city => $delivery_city,
      delivery_state => $delivery_state,
      delivery_postcode => $delivery_zip,
      delivery_phone => $delivery_phone,
      package_weight => $_POST['package_weight'],
      package_value => $_POST['declare_value'],
      oversized => $_POST['oversized'],
      pickup_date => $corrected_date,
      saturday_delivery => $_POST['saturday_delivery'],
      hold_at_location => $_POST['hold_at_location'],
      hal_address => $_POST['hal_address'],
      hal_city => $_POST['hal_city'],
      hal_state => $_POST['hal_state'],
      hal_postcode => $_POST['hal_postcode'],
      hal_phone => $_POST['hal_phone'],
      dim_height => $_POST['dim_height'],
      dim_width => $_POST['dim_width'],
      dim_length => $_POST['dim_length'],
      shipping_type => $_POST['service_type'],
      residential => $shipData[440],
      autopod => $_POST['autopod'],
      cod => '0',
      );

      // get the package weight/total weight and format it to one decimal place
      $total_weight = round($_POST['package_weight'], 1);
      $total_weight = sprintf("%01.1f", $total_weight);

      // deal with multiple packages
      
      if ($_POST['package_num'] > 1 ) {
        $shipData[116] = $_POST['package_num'];
        $shipData[1117] = $i;
        $manifest_data['multiple'] = $i;

        if ($i == 1) {
          if ($debug) {
            $shipData[1400] = $total_weight;
            $package_weight = $_POST['package_weight' . $i];
            $package_weight = sprintf("%01.1f", $package_weight);
            $shipData[1401] = $package_weight;
            $shipData[1415] = round($_POST['declare_value' . $i])  . '.00';
            echo SHIPMENT_REQUEST_DATA . $i . ':<br /><pre>';
            print_r($shipData);
            echo '</pre>';
            $manifest_data['tracking_num'] = 'master_trackNum';
            echo MANIFEST_DATA . $i . ':<br /><pre>';
            print_r($manifest_data);
            echo '</pre>';
            }
          else {
            $shipData[1400] = $total_weight;
            $package_weight = round($_POST['package_weight' . $i],1);
            $package_weight = sprintf("%01.1f", $package_weight);
            $shipData[1401] = $package_weight;
            $shipData[1415] = round($_POST['declare_value' . $i]) . '.00';
            $master_trackNum = fedex_ship_request($shipData,$ship_type,$order);
            $manifest_data['tracking_num'] = $master_trackNum;
            }
          }
        else {
          if ($debug) {
            $shipData[1123] = 'master_trackNum';
            $package_weight = $_POST['package_weight' . $i];
            $package_weight = sprintf("%01.1f", $package_weight);
            $shipData[1401] = $package_weight;
            $shipData[1415] = round($_POST['declare_value' . $i]) . '.00';
            echo SHIPMENT_REQUEST_DATA . $i . ':<br /><pre>';
            print_r($shipData);
            echo '</pre>';
            $manifest_data['tracking_num'] = 'trackNum';
            echo MANIFEST_DATA . $i . ':<br /><pre>';
            print_r($manifest_data);
            echo '</pre>';
            }
          else {
            $shipData[1123] = $master_trackNum;
            $package_weight = round($_POST['package_weight' . $i],1);
            $package_weight = sprintf("%01.1f", $package_weight);
            $shipData[1401] = $package_weight;
            $shipData[1415] = round($_POST['declare_value' . $i], 0) . '.00';
            $trackNum = fedex_ship_request($shipData,$ship_type,$order);
            $manifest_data['tracking_num'] = $trackNum;
            }
          }
        }
// for single package shipments
      elseif ($_POST['package_num'] == 1) {
        if ($debug) {
          $shipData[1401] = $total_weight;
          echo SHIPMENT_REQUEST_DATA . $i . ':<br /><pre>';
          print_r($shipData);
          echo '</pre>';
          $manifest_data['tracking_num'] = 'master_trackNum';
          echo MANIFEST_DATA . $i . ':<br /><pre>';
          print_r($manifest_data);
          echo '</pre>';
          }
        else {
          $shipData[1401] = $total_weight;
          $master_trackNum = fedex_ship_request($shipData,$ship_type,$order);
          $manifest_data['tracking_num'] = $master_trackNum;
          }
        }
// post data to shipping manifest
        if ($debug==0) {
          zen_db_perform(TABLE_SHIPPING_MANIFEST, $manifest_data);
        //print_r($manifest_data);
        //echo '<br />' . TABLE_SHIPPING_MANIFEST;
        //die();
        }
      }

    if ($debug) {
      die(RUNNING_IN_DEBUG);
      }

////
// update the order record

// if there's a master tracking number, keep it with the order
      if ($master_trackNum) {
        $trackNum = $master_trackNum;
        }

// store the tracking number
      $db->Execute("update " . TABLE_ORDERS . " set fedex_tracking_return='" . $trackNum . "' where orders_id = " . $order . "");

// add comment to order history
      $fedex_comments = ORDER_HISTORY_DELIVERED . $trackNum;

// set the order status
      $update_status = array ('orders_status' => (int)$returns_orders_status_id);
      zen_db_perform(TABLE_ORDERS, $update_status, 'update', "orders_id = '" . $order . "'");

      if ($send_email_on_shipping) {
        $customer_notified = '1';
      }
      else {
        $customer_notified = '0';
      }

      $db->Execute("insert into " . TABLE_ORDERS_STATUS_HISTORY . " (orders_id, orders_status_id, date_added, customer_notified, comments) values ('" . $order . "', '" . (int)$returns_orders_status_id . "', now(), '" . $customer_notified . "', '" . $fedex_comments  . "')");

// send email automatically on shipping
      if ($send_email_on_shipping) {
            $check_status_query = "select customers_name as customers_name, customers_email_address as customers_email_address, orders_status as orders_status, date_purchased as date_purchased from " . TABLE_ORDERS . " where orders_id = '" . (int)$order . "'";
            $check_status = $db->Execute($check_status_query);

           if (zen_not_null($trackNum)) {
          $email_notify_tracking = sprintf(EMAIL_TEXT_TRACKING_NUMBER) . "\n" . URL_TO_TRACK1 . nl2br(zen_output_string_protected($trackNum)) . "\n\n";
        };

              $html_msg['EMAIL_MESSAGE_HTML'] = $email_txt = MODULE_SHIPPING_FEDEX_COMPANY_NAME . "<br />" . EMAIL_SEPARATOR . "<br />" . EMAIL_TEXT_ORDER_NUMBER . ' ' . $order . "<br /><br />" . EMAIL_TEXT_INVOICE_URL . ' ' . zen_catalog_href_link(FILENAME_CATALOG_ACCOUNT_HISTORY_INFO, 'order_id=' . $order, 'SSL') . "<br />" . EMAIL_TEXT_DATE_ORDERED . ' ' . zen_date_long($check_status->fields['date_purchased']) . "<br /><br />" . "<br />" . $email_notify_tracking . "<br /><br />" . sprintf(EMAIL_TEXT_STATUS_UPDATE, 'Shipped');
        zen_mail($check_status->fields['customers_name'], $check_status->fields['customers_email_address'], EMAIL_TEXT_SUBJECT, $email_txt, MODULE_SHIPPING_FEDEX_CONTACT_NAME, MODULE_SHIPPING_FEDEX_CONTACT_NAME_EMAIL_ADDRESS, $html_msg, 'order_update');
      }

// ... and display the new label without manifest entry for express shipments
      $ship_type_query = "select shipping_type as shipping_type from " . TABLE_SHIPPING_MANIFEST . " where orders_id = '" . $order . "'";
      $ship_type = $db->Execute($ship_type_query);
      if ($ship_type->fields['shipping_type'] < 89) {
        $delete_manifest_query = $db->Execute("delete from " . TABLE_SHIPPING_MANIFEST . " where orders_id = '" . $order . "'");
      }
      
      // unset sessions
      unset($_SESSION['fedex_gateway']);
      unset($_SESSION['package_num']);
      unset($_SESSION['oversized']);
      unset($_SESSION['saturday_delivery']);
      unset($_SESSION['signature_type']);
      unset($_SESSION['hold_at_location']);
      unset($_SESSION['hal_address']);
      unset($_SESSION['hal_city']);
      unset($_SESSION['hal_state']);
      unset($_SESSION['hal_postcode']);
      unset($_SESSION['hal_phone']);
      unset($_SESSION['dim_height']);
      unset($_SESSION['dim_width']);
      unset($_SESSION['dim_length']);
      unset($_SESSION['residential']);
      unset($_SESSION['packaging_type']);
      unset($_SESSION['service_type']);
      unset($_SESSION['payment_type']);
      unset($_SESSION['package_weight']);
      unset($_SESSION['bill_type']);
      unset($_SESSION['dropoff_type']);
      unset($_SESSION['pickup_date']);
      unset($_SESSION['package_invoice']);
      unset($_SESSION['package_reference']);
      unset($_SESSION['package_po']);
      unset($_SESSION['package_department']);
      unset($_SESSION['autopod']);
      unset($_SESSION['item_weights']);
      unset($_SESSION['telephone']); 
      unset($_SESSION['package_num']);
      unset($_SESSION['rate_request']);
      
      zen_redirect(zen_href_link('fedex_popup.php?num=' . $trackNum . '&oID=' . $order . '&multiple=' . $shipData[1117]));
  }

// end ship request

// if "action" is anything other than "ship," we can write out a regular admin page

  else {

////
// cancel a scheduled shipment

    if($action=='cancel') {

      if (!$order) {
        echo ERROR_NO_ORDER_SPECIFIED;
        }
      elseif ($order) {

        require(DIR_WS_INCLUDES . 'fedexdc.php');
        $transaction_code = "023";
        
    if (MODULE_SHIPPING_FEDEX_SERVER == 'production') {
      $fedex_account = MODULE_SHIPPING_FEDEX_ACCOUNT;
    } else {
      $fedex_account = MODULE_SHIPPING_FEDEX_TEST_ACCOUNT;
    }
// get required config variables
      $fedex_vars = array (
      10=>$fedex_account,
      498=>MODULE_SHIPPING_FEDEX_METER
      );

// determine if we're using test or production gateway
      $fedex_gateway = MODULE_SHIPPING_FEDEX_SERVER;
      $fedex_keys = array_keys($fedex_vars);

// create new FedExDC object
      $fed = new FedExDC($fedex_vars[10],$fedex_vars[498]);

// get the tracking number from the order record
      $fedex_tracking_query = "select fedex_tracking_return as fedex_tracking_return from " . TABLE_ORDERS . " where orders_id = '" . $order . "'";
      $r = $db->Execute($fedex_tracking_query);
      $fedex_tracking_return = $r->fields['fedex_tracking_return'];

// get the shipment type from the shipping manifest
      $ship_type_query = "select shipping_type as shipping_type from " . TABLE_SHIPPING_MANIFEST . " where orders_id = '" . $order . "'";
      $ship_type = $db->Execute($ship_type_query);
      if (($ship_type->fields['shipping_type'] == 90) or ($ship_type->fields['shipping_type'] == 92)) {
        $ship_type = 'FDXG';
        }
      else {
        $ship_type = 'FDXE';
        }

// simple array with transaction code, tracking number, carrier code
      $cancelData = array (
        0 => $transaction_code,
        1 => ORDER_NUMBER . $order, // order number, optional
        29 => $fedex_tracking_return,
        3025 => $ship_type
        );

      $cancelData = $fedex_keys+$cancelData;

// remove shipment data from the shipping manifest
      $delete_manifest_query = $db->Execute("delete from " . TABLE_SHIPPING_MANIFEST . " where orders_id = '" . $order . "'");
      if ($delete_manifest_query) {
        }
      elseif (!$delete_manifest_query) {
        echo COULD_NOT_DELETE_ENTRIES;
        }

// cancel the shipment
      $cancelRet = $fed->cancel_ground($cancelData);

// todo: add appropriate error checking for at least some of the possible errors
      if ($error = $fed->getError()) {
        die(ERROR . $error);
        }

// delete the tracking number from the order record
      $delete_trackNum = array('fedex_tracking_return' => '');

      zen_db_perform(TABLE_ORDERS, $delete_trackNum, 'update', "orders_id = '" . $order . "'");

// ...mark the order record "cancelled"...
      $update_status = array ('orders_status' => MODULE_SHIPPING_FEDEX_ORDER_STATUS_CANCELLED);
      zen_db_perform(TABLE_ORDERS, $update_status, 'update', "orders_id = '" . $order . "'");

// ...add a comment to the order history to show what we've done...
      $fedex_comments = ORDER_HISTORY_CANCELLED . $trackNum;

      $db->Execute("insert into " . TABLE_ORDERS_STATUS_HISTORY . " (orders_id, orders_status_id, date_added, customer_notified, comments) values ('" . $order . "', '" . MODULE_SHIPPING_FEDEX_ORDER_STATUS_CANCELLED . "', now(), '0', '" . $fedex_comments  . "')");

// ...delete the record from the manifest...
      $db->Execute("delete from " . TABLE_SHIPPING_MANIFEST . " where orders_id = '" . $order . "'");

// ...and refresh the orders page
      zen_redirect(zen_href_link(FILENAME_ORDERS, '?oID=' . $order));
      }
    }

////
// make the form for additional shipment information

  elseif($action=='new') {
    // unset sessions
    unset($_SESSION['fedex_gateway']);
    unset($_SESSION['package_num']);
    unset($_SESSION['oversized']);
    unset($_SESSION['saturday_delivery']);
    unset($_SESSION['signature_type']);
    unset($_SESSION['hold_at_location']);
    unset($_SESSION['hal_address']);
    unset($_SESSION['hal_city']);
    unset($_SESSION['hal_state']);
    unset($_SESSION['hal_postcode']);
    unset($_SESSION['hal_phone']);
    unset($_SESSION['dim_height']);
    unset($_SESSION['dim_width']);
    unset($_SESSION['dim_length']);
    unset($_SESSION['residential']);
    unset($_SESSION['packaging_type']);
    unset($_SESSION['service_type']);
    unset($_SESSION['payment_type']);
    unset($_SESSION['package_weight']);
    unset($_SESSION['bill_type']);
    unset($_SESSION['dropoff_type']);
    unset($_SESSION['pickup_date']);
    unset($_SESSION['package_invoice']);
    unset($_SESSION['package_reference']);
    unset($_SESSION['package_po']);
    unset($_SESSION['package_department']);
    unset($_SESSION['autopod']);
    unset($_SESSION['item_weights']);
    unset($_SESSION['package_num']);
    unset($_SESSION['telephone']);
    unset($_SESSION['rate_request']);
      
    $order = $_GET['oID'];

// determine if we're using test or production gateway
    $fedex_gateway = MODULE_SHIPPING_FEDEX_SERVER;

// Moved up so we can now detect company or not
// get orders information
    $order_query = "select * from " . TABLE_ORDERS . " where orders_id = $order";
    $order_info = $db->Execute($order_query);

    // abbreviate the delivery country (function is in abbreviate.php)
    include(DIR_WS_INCLUDES . 'abbreviate.php'); // used to abbreviate state & country names
    $delivery_country = abbreviate_country(zen_get_country_name(STORE_COUNTRY));


// arrays for shipping options; include as many or as few as you like
    $packaging_type = array();
    $packaging_type[] = array('id' => '01', 'text' => 'Your Packaging');
    $packaging_type[] = array('id' => '02', 'text' => 'FedEx Pak');
    $packaging_type[] = array('id' => '03', 'text' => 'FedEx Box');
    $packaging_type[] = array('id' => '04', 'text' => 'FedEx Tube');
    $packaging_type[] = array('id' => '06', 'text' => 'FedEx Envelope');

    foreach ($packaging_type as $packaging_type_array) {
      if ($packaging_type_array['text'] == MODULE_SHIPPING_FEDEX_PACKAGE_TYPE_DEFAULT) {
        $packaging_type_default = $packaging_type_array['id'];
        break;
      }
    }
    
    $service_type = array();
    if (MODULE_SHIPPING_FEDEX_GROUND_SERVICE_STATUS == 'true') $service_type[] = array('id' => '92', 'text' => 'FedEx Ground Service');
    if (MODULE_SHIPPING_FEDEX_HOME_DELIVERY_STATUS == 'true') $service_type[] = array('id' => '90', 'text' => 'FedEx Home Delivery');
    if (MODULE_SHIPPING_FEDEX_PRIORITY_OVERNIGHT_STATUS == 'true') $service_type[] = array('id' => '01', 'text' => 'FedEx Priority Overnight');
    if (MODULE_SHIPPING_FEDEX_2DAY_STATUS == 'true') $service_type[] = array('id' => '03', 'text' => 'FedEx 2day');
    if (MODULE_SHIPPING_FEDEX_STANDARD_OVERNIGHT_STATUS == 'true') $service_type[] = array('id' => '05', 'text' => 'FedEx Standard Overnight');
    if (MODULE_SHIPPING_FEDEX_FIRST_OVERNIGHT_STATUS == 'true') $service_type[] = array('id' => '06', 'text' => 'FedEx First Overnight');
    if (MODULE_SHIPPING_FEDEX_EXPRESS_SAVER_STATUS == 'true') $service_type[] = array('id' => '20', 'text' => 'FedEx Express Saver');
//    $service_type[] = array('id' => '70', 'text' => 'FedEx 1day Freight');
//    $service_type[] = array('id' => '80', 'text' => 'FedEx 2day Freight');
//    $service_type[] = array('id' => '83', 'text' => 'FedEx 3dayFreight');

    $bill_type = array();
    $bill_type[] = array('id' => '1', 'text' => 'Bill sender (Prepaid)');
    $bill_type[] = array('id' => '2', 'text' => 'Bill recipient');
    $bill_type[] = array('id' => '3', 'text' => 'Bill third party');
    $bill_type[] = array('id' => '4', 'text' => 'Bill credit card');
    $bill_type[] = array('id' => '5', 'text' => 'Bill recipient for FedEx Ground');

    $dropoff_type = array();
    $dropoff_type[] = array('id' => 1, 'text' => 'Regular pickup');
    $dropoff_type[] = array('id' => 2, 'text' => 'Request courier');
    $dropoff_type[] = array('id' => 3, 'text' => 'Drop box');
    $dropoff_type[] = array('id' => 4, 'text' => 'Drop at BSC');
    $dropoff_type[] = array('id' => 5, 'text' => 'Drop at station');
    
    foreach ($dropoff_type as $dropoff_type_array) {
      if ($dropoff_type_array['text'] == MODULE_SHIPPING_FEDEX_DROPOFF_DEFAULT) {
        $dropoff_default = $dropoff_type_array['id'];
        break;
      }
    }

    $oversized = array();
    $oversized[] = array('id' => 0, 'text' => '');
    $oversized[] = array('id' => 1, 'text' => 1);
    $oversized[] = array('id' => 2, 'text' => 2);
    $oversized[] = array('id' => 3, 'text' => 3);

    // array for Saturday delivery
    $saturday_delivery = array();
    $saturday_delivery[] = array('id' => 0, 'text' => 'N');
    $saturday_delivery[] = array('id' => 1, 'text' => 'Y');

    // array for Hold At Fedex Location
    $hold_at_location = array();
    $hold_at_location[] = array('id' => 0, 'text' => 'N');
    $hold_at_location[] = array('id' => 1, 'text' => 'Y');

    // arrays for signature services
    $signature_type = array();
    $signature_type[] = array('id' => '0', 'text' => 'None Required');
    $signature_type[] = array('id' => '2', 'text' => 'Anyone can sign (res only)');
    $signature_type[] = array('id' => '3', 'text' => 'Signature Required');
    $signature_type[] = array('id' => '4', 'text' => 'Adult Signature');

    // arrays for AutoPOD
    $autopod = array();
    $autopod[] = array('id' => 0, 'text' => 'N');
    $autopod[] = array('id' => 1, 'text' => 'Y');

// get & format tomorrow's date for default pickup date
    $dayofweek = strftime("%A", mktime());

    // get the current timestamp into an array
    $timestamp = time();
    $date_time_array = getdate($timestamp);

    $datehours = $date_time_array['hours'];

    if ($dayofweek == Saturday) {
      $default_pickup_date = date('m-d-Y',strtotime('+2 day'));
    } else if ($dayofweek == Sunday) {
      $default_pickup_date = date('m-d-Y',strtotime('+1 day'));

    // Seeing if order after last pickup time, if so set order for tommorrow by default
    } else if ($datehours > $lastshipment) {
      $default_pickup_date = date('m-d-Y',strtotime('+1 day'));
    } else {
    $default_pickup_date = date('m-d-Y',strtotime('today'));
    }

// get the shipping method
    $shipping_query = "select title as title from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $order . "' and class='ot_shipping'";
    $shipping_method = $db->Execute($shipping_query);
    $shipping_method = trim($shipping_method->fields['title'], ':');

    $shipping_method_keywords = array('90' => 'Home Delivery',
                      '92' => 'Ground Service',
                      '01' => 'Priority',
                      '03' => '2Day',
                      '05' => 'Standard Overnight',
                      '06' => 'First Overnight',
                      '20' => 'Express Saver');

    //if (MODULE_SHIPPING_FEDEX_COMPANY_NAME) {
    $shipping_type='92'; // default to Fedex Ground for shipments to company
    
    while (list($shipping_index, $shipping_keyword) = each($shipping_method_keywords)){
      if (false !== strpos($shipping_method, $shipping_keyword)){
        $shipping_type=$shipping_index;
        break 1;
      }
    }

// get the order qty and item weights
    $order_qty_query = "select * from " . TABLE_ORDERS_PRODUCTS . " where orders_id = '" . $order . "'";
    $order_qtys = $db->Execute($order_qty_query);
    $order_qty = 0;
    $order_weight = 0;
    $order_item_html = '';
    $item_weights = array();
    //if (mysql_num_rows($order_qty_query)) { // NUMINIX
      while (!$order_qtys->EOF){
        $order_item_html = $order_item_html . '          <tr>' . "\n" .
        '            <td class="smallText" align="left">' . $order_qtys->fields['products_quantity'] . ' * ' .
        $order_qtys->fields['products_name'] . '</td>' . "\n" .
        '            <td class="smallText" align="left">';
        $order_qty = $order_qty + $order_qtys->fields['products_quantity'];
        $products_id = $order_qtys->fields['products_id'];
        $products_weight_query = "select * from " . TABLE_PRODUCTS . " where products_id = '" . $products_id . "'";
        $products_weights = $db->Execute($products_weight_query);
        if ($products_weights->RecordCount() > 0) {
          $order_weight = $order_weight + ($order_qtys->fields['products_quantity'] * ($products_weights->fields['products_weight']));
          $item_weights[] = $products_weights->fields['products_weight'];
        }
        $order_qtys->MoveNext();
      }

      // Find out which weighs more tare or percentage shipping rate and display that rate

      $order_weight_tar = $order_weight + SHIPPING_BOX_WEIGHT;
      $order_weight_percent = ($order_weight * (SHIPPING_BOX_PADDING / 100 + 1));

      if ($order_weight_percent < $order_weight_tar) {
      $order_weight = $order_weight_tar;
      } else {
      $order_weight = $order_weight_percent;
      }

      $order_weight = round($order_weight,1);
      $order_weight = sprintf("%01.1f", $order_weight);
      
      // create dropdown for address selection
      if (defined('TABLE_MULTI_ADDRESS')) {
        $address_id = (int)$_GET['address_id'];
        $address_query = $db->Execute("SELECT * FROM " . TABLE_MULTI_ADDRESS . " ORDER BY address_id;");
        $count = 0;
        $address_array[$count]['id'] = 0;
        $address_array[$count]['text'] = 'Please select';
        while (!$address_query->EOF) {
          if ($address_query->fields['address_id'] >= 0) {
            $count++;
            $address_array[$count]['id'] = $address_query->fields['address_id'];
            if ($address_query->fields['company'] != '') $address_array[$count]['text'] = $address_query->fields['company']; 
            else $address_array[$count]['text'] = $address_query->fields['name'];
            $address_query->MoveNext();
          }
        }
        // get selected address
        if ($address_id > 0) {
          $selected_address_query = $db->Execute("SELECT * FROM " . TABLE_MULTI_ADDRESS . " WHERE address_id = " . $address_id . " LIMIT 1;");
          $selected_address = '';
          if ($selected_address_query->fields['company']) $selected_address .= $selected_address_query->fields['company'] . "<br />";
          if ($selected_address_query->fields['name']) $selected_address .= $selected_address_query->fields['name'] . "<br />";
          $selected_address .= $selected_address_query->fields['address_1'] . "<br />";
          if ($selected_address_query->fields['address_2']) $selected_address .= $selected_address_query->fields['address_2'] . "<br />";
          $selected_address .= $selected_address_query->fields['city'] . ", " . $selected_address_query->fields['state'] . " " . $selected_address_query->fields['zip'] . "<br />";
          $selected_address .= zen_get_country_name($selected_address_query->fields['country']);
        }
      }
      $unwanted = array('(',')','-','.',' ','/');
      $senders_name = substr(name_case($order_info->fields['customers_name']), 0, 35);
      $senders_company = substr($order_info->fields['delivery_company'], 0, 35);
      $senders_address_1 = substr($order_info->fields['delivery_street_address'], 0, 35);
      $senders_address_2 = substr($order_info->fields['delivery_suburb'], 0, 35);
      $senders_city = $order_info->fields['delivery_city'];
      //include_once(DIR_WS_INCLUDES . 'abbreviate.php'); // used to abbreviate state & country names
      $senders_state = abbreviate_state($order_info->fields['delivery_state']);
      $senders_zip = $order_info->fields['delivery_postcode'];
      $senders_phone = trim(str_replace($unwanted, '', $order_info->fields['customers_telephone']));
   }

?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<link rel="stylesheet" type="text/css" href="includes/cssjsmenuhover.css" media="all" id="hoverJS">
<link rel="stylesheet" type="text/css" href="includes/fedex.css">
<script type="text/javascript" src="includes/javascript/jquery_1.3.2.min.js"></script>
<script type="text/javascript" src="includes/javascript/multi_address.js"></script>
<script type="text/javascript" src="includes/javascript/jscript_fedex.js"></script>
<script type="text/javascript" src="includes/javascript/jscript_jquery_alerts.js"></script>    
<script language="javascript" src="includes/menu.js"></script> 
<script language="javascript" src="includes/general.js"></script>
<script language="javascript">
function validate() {
  var weight = new Number(ship_fedex.package_weight.value);
  var declare_value = new Number(ship_fedex.declare_value.value);
  if (weight=='') {
    alert('<?php echo ENTER_PACKAGE_WEIGHT; ?>');
    event.returnValue=false;
    }
  package_num=ship_fedex.package_num.value;
  if (package_num=='') {
    alert('<?php echo ENTER_NUMBER_PACKAGES; ?>');
    event.returnValue=false;
    }
  if (package_num > 1) {
    package_total_weight = 0;
    package_total_value = 0;
    for (i=1; i<=package_num; i++) {
      package_total_weight += parseFloat(document.getElementsByName('package_weight'+i)[0].value);
      package_total_value += parseFloat(document.getElementsByName('declare_value'+i)[0].value);
    }
    weight = weight.toFixed(2);
    package_total_weight = package_total_weight.toFixed(2);
    if (weight < package_total_weight) {
      alert('<?php echo 'Total weight cannot be less than the sum of all package weights'; ?>');
      event.returnValue=false;
    }
    declare_value = declare_value.toFixed(0);
    package_total_value = package_total_value.toFixed(0);
    if (declare_value < package_total_value) {
      alert('<?php echo 'Total declared value cannot be less than the sum of all package weights'; ?>');
      event.returnValue=false;
    }      
  }
}
</script>
<script type="text/javascript">
  <!--
  function init()
  {
    cssjsmenu('navbar');
    if (document.getElementById)
    {
      var kill = document.getElementById('hoverJS');
      kill.disabled = true;
    }
  if (typeof _editor_url == "string") HTMLArea.replace('message_html');
  }
  // -->
</script>

</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF" onLoad="init()">
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->

<!-- body //-->
<table border="0" width="100%" cellspacing="2" cellpadding="2">
  <tr>
    <td width="<?php echo BOX_WIDTH; ?>" valign="top"><table border="0" width="<?php echo BOX_WIDTH; ?>" cellspacing="1" cellpadding="1" class="columnLeft">
    </table></td>
<!-- body_text //-->
    <td width="100%" valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2">
      <tr>
              <td width="100%"><table border="0" width="100%" cellspacing="0" cellpadding="0">
<?
  // if it's a new shipment, write out the form for more data
  if ($action=='new') {
    $package_num = 1;
    
    //echo $package_num;
    //die(); 
?>
          <tr>
            <td class="pageHeading"><?php
            echo HEADING_TITLE;
            if ($order) {
              echo ', ' . ORDER_NUMBER . $order;
              }
            elseif (!$order) {
              echo ERROR_NO_ORDER_SPECIFIED;
              }
            ?></td>
            <td class="pageHeading" align="right"><?php echo zen_draw_separator('pixel_trans.gif', 1, HEADING_IMAGE_HEIGHT); ?></td>
            <td class="pageHeading" align="right"><?php echo '<a href="' . zen_href_link(FILENAME_ORDERS, 'oID=' . $order) . '">' . zen_image_button('button_back.gif', IMAGE_BACK) . '</a>'; ?></td>
          </tr>

          <tr>
          <td colspan="3" class="main" align="left">
          <table border=0 cellpadding=0 cellspacing=0 width="700">
            <tr>
              <td class="main" align="left" valign="top">
                <strong>Sold To:</strong><br />
                <address id="sender">
                <?php echo $order_info->fields['delivery_company'] . '<br />'; ?>
                <?php echo name_length($order_info->fields['customers_name']) . '<br />'; ?>
                <?php echo $order_info->fields['customers_street_address'] . '<br />'; ?>
                <?php if ($order_info->fields['customers_suburb'] != '') echo $order_info->fields['customers_suburb'] . '<br />'; ?> 
                <?php echo $order_info->fields['customers_city'] . '<br />'; ?>
                <?php echo $order_info->fields['customers_state'] . '<br />'; ?>
                <?php echo $order_info->fields['customers_postcode'] . '<br />'; ?>
                </address>
              </td>
              <td class="main" align="left" valign="top">
                <strong>Shipping To:</strong><br />
                <address id="recipient">
                <?php 
                  if ($selected_address != '') {
                    echo $selected_address;
                  } else {
                ?>
                <?php   echo MODULE_SHIPPING_FEDEX_COMPANY_NAME; ?><br />
                <?php   echo name_length(MODULE_SHIPPING_FEDEX_CONTACT_NAME); ?><br />
                <?php   echo MODULE_SHIPPING_FEDEX_ADDRESS_1; ?><br />
                <?php   echo MODULE_SHIPPING_FEDEX_ADDRESS_2; ?><br />
                <?php   echo MODULE_SHIPPING_FEDEX_CITY; ?><br />
                <?php   echo MODULE_SHIPPING_FEDEX_STATE; ?><br />
                <?php   echo MODULE_SHIPPING_FEDEX_POSTAL; ?>
                <?php } ?>
                </address>
              </td>
              <?php if (defined('TABLE_MULTI_ADDRESS')) { ?>
              <td class="main" align=left" valign="top">
                <label for="change_address_reversed"><strong>Change Recipient Address:</strong></label><br />
                <?php echo zen_draw_pull_down_menu('change_address_reversed', $address_array, $address_id, '', false); ?>
              </td>
              <?php } ?>
            </tr>
          </table>
          </td>
          </tr>
          <tr>
      <td colspan="3" class="main" align="left"><strong>Shipping Method:</strong><br /><?php echo $shipping_method ?><br />&nbsp;</td>
      </tr>
            <?php echo $order_item_html;?>

          </table></td>
            </tr>
        <tr>
              <td>
            <?php
              // if quantity = 1, skip to shipping directly
        //if ($package_num <= 1){
              echo zen_draw_form('ship_fedex', FILENAME_SHIP_FEDEX_REVERSED, 'cPath=' . $cPath . '&cID=' . $_GET['cID'] . '&oID=' . $order . '&action=ship', 'post', 'enctype="multipart/form-data"  onsubmit="validate();"');
          //}
          // otherwise, go to a 2nd screen to key in individual weights
          //elseif ($package_num > 1) {
            //echo zen_draw_form('ship_fedex', FILENAME_SHIP_FEDEX, 'cPath=' . $cPath . '&cID=' . $_GET['cID'] . '&oID=' . $order . '&action=post1', 'post', 'enctype="multipart/form-data"  onsubmit="validate();"');
          //}
        ?>
          <input type="hidden" name="order_item_html" value='<?php echo urlencode(serialize($order_item_html)); ?>' />
          <input type="hidden" name="item_weights" value='<?php echo urlencode(serialize($item_weights)); ?>' />
          <input type="hidden" name="fedex_gateway" value="<? echo $fedex_gateway; ?>" />
          <input type="hidden" name="address_id" value="<?php echo $address_id; ?>" />
          <table width="70%" border="0" cellspacing="0" cellpadding="2">
            <tr>
              <td colspan="3"><?php echo zen_draw_separator('pixel_trans.gif', '1', '15'); ?></td>
            </tr>
                  <tr>
              <td class="main" align="right"><strong><u>Required Fields</u></strong></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td class="main" align="right">Sender's Name:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('senders_name',$senders_name,'size="32"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Sender's Company:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('senders_company',$senders_company,'size="32"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Sender's Address Line 1:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('senders_address_1',$senders_address_1,'size="32"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Sender's Address Line 2:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('senders_address_2',$senders_address_2,'size="32"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Sender's City:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('senders_city',$senders_city,'size="32"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Sender's State:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('senders_state',$senders_state,'size="32"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Sender's Postal Code:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('senders_zip',$senders_zip,'size="32"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Number of Packages:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('package_num',$package_num,'size="2"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Oversized?</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_pull_down_menu('oversized',$oversized); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Sender's Telephone:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('telephone',$senders_phone,'size="15"'); ?> (10 digits, no dashes)</td>
            </tr>
            <tr>
              <td class="main" align="right">Packaging Type ("other" for ground shipments):</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_pull_down_menu('packaging_type',$packaging_type, $packaging_type_default); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Type of Service:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_pull_down_menu('service_type',$service_type, $shipping_type); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Payment Type:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_pull_down_menu('bill_type',$bill_type); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Dropoff Type:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_pull_down_menu('dropoff_type', $dropoff_type, $dropoff_default); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Pickup date (yyyymmdd):</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('pickup_date',$default_pickup_date,'size="9"'); ?></td>
            </tr>
            <?php
            // get the transaction value
                $value_query = "select value as value from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $order . "' and class='ot_subtotal'";
                $order_value = $db->Execute($value_query);
                $order_value = round($order_value->fields['value'], 0);
                require(DIR_WS_CLASSES . 'currencies.php'); 
                $currencies = new currencies();
            ?>
            <tr>
              <td class="main" align="right">Declared Value ($):</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('declare_value', '', 'size="2"'); ?> (Actual Value: <?php echo $currencies->format($order_value); ?>)</td>
              </tr>
            <tr>
            <?php
            $declare_value = round($declare_value, 0);

              if ($package_num > 1) {
                echo '<td class="main" align="right">' . TOTAL_WEIGHT . '</td>';
                }
              else {
                echo '<td class="main" align="right">' . PACKAGE_WEIGHT . '</td>';
                }
            ?>
                <td class="main">&nbsp;</td>
                    <td class="main"><?php echo zen_draw_input_field('package_weight',(string)$order_weight,'size="2"'); ?></td>
                    <td></td>
                  </tr>

            <tr>
                    <td class="main">&nbsp;</td>
                    <td></td>
                    <td></td>
                  </tr>
            <tr>
              <td class="main" align="right"><strong><u>Optional Fields</u></strong></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td class="main" align="right">Your Package Dimensions:</td>
              <td class="main">&nbsp;</td>
              <td class="main">&nbsp;Length:&nbsp;<?php echo zen_draw_input_field('dim_length','','size="5" maxlength="30"'); ?>&nbsp;Width:&nbsp;<?php echo zen_draw_input_field('dim_width','','size="5" maxlength="30"'); ?>&nbsp;Height:&nbsp;<?php echo zen_draw_input_field('dim_height','','size="5" maxlength="30"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right" valign="top">Saturday Delivery?</td>
              <td class="main">&nbsp;</td>
              <td class="main">

                        <?php echo zen_draw_pull_down_menu('saturday_delivery',$saturday_delivery); ?>&nbsp;&nbsp;<div class="smallText">
                        <font color="#d02727">Only Priority or 2Day Shipping Service Allowed For Saturday Delivery</font></div>
                    </td>
            </tr>
            <tr>
              <td class="main" align="right">Invoice #:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('package_invoice',$order,'size="33" maxlength="30"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Reference #:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('package_reference',$order,'size="33" maxlength="30"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Purchase Order #:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('package_po','','size="33" maxlength="30"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Department Name:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('package_department','','size="10" maxlength="10"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Signature Options:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_pull_down_menu('signature_type',$signature_type); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Hold At Fedex Location (HAL):</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_pull_down_menu('hold_at_location',$hold_at_location); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">HAL Address:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('hal_address','','size="33"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">HAL City:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('hal_city','','size="33"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">HAL State:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('hal_state','','size="33"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">HAL Postal Code:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('hal_postcode','','size="33"'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">HAL Phone #:</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('hal_phone','','size="33"'); ?></td>
            </tr>

            <tr>
              <td colspan="3"><?php echo zen_draw_separator('pixel_trans.gif', '1', '15'); ?></td>
            </tr>
            <tr>
              <td class="main" align="right"><strong><u>Fedex Ground Fields</u></strong></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td class="main" align="right">Automatic Proof of Delivery?</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_pull_down_menu('autopod',$autopod); ?></td>
            </tr>
            <tr>
              <td class="main" align="right">Rate request only?</td>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_checkbox_field('rate_request','1',false); ?></td>
            </tr>

            <tr>
              <td>&nbsp;</td>
              <td>&nbsp;</td>
              <td><?php echo zen_image_submit('button_submit.gif', IMAGE_SUBMIT); ?></td>
            </tr>
          </table>
    </form>
<?
    }

  // new form accepts total weight and individual weights
  // if there are multiple packages
  elseif ($action=='post1') {
    //$package_num = $_POST['package_num'];
    $order_item_html = $_SESSION['order_item_html'] = unserialize(urldecode($_POST['order_item_html']));
    $item_weights = $_SESSION['item_weights'] = unserialize(urldecode($_POST['item_weights']));
    $package_num = $_POST['package_num'] = $_SESSION['package_num'];
    //die();
?>


          <tr>
            <td class="pageHeading"><?php
            echo HEADING_TITLE;
            if ($order) {
              echo ', ' . ORDER_NUMBER . $order;
              }
            elseif (!$order) {
              echo ERROR_NO_ORDER_SPECIFIED;
              }
            ?></td>
            <td class="pageHeading" align="right"><?php echo zen_draw_separator('pixel_trans.gif', 1, HEADING_IMAGE_HEIGHT); ?></td>
            <td class="pageHeading" align="right"><?php echo '<a href="' . zen_href_link(FILENAME_ORDERS, 'oID=' . $order) . '">' . zen_image_button('button_back.gif', IMAGE_BACK) . '</a>'; ?></td>
            <?php echo $order_item_html;?>
          </tr>
        </table></td>
      </tr>
      <tr>
        <td>
          <? echo zen_draw_form('ship_fedex', FILENAME_SHIP_FEDEX_REVERSED, 'cPath=' . $cPath . '&cID=' . $_GET['cID'] . '&oID=' . $order . '&action=ship&source=post1', 'post', 'enctype="multipart/form-data"  onsubmit="validate();"'); ?>
          <input type="hidden" name="fedex_gateway" value="<? echo $_SESSION['fedex_gateway']; ?>"/>
          <input type="hidden" name="package_num" value = "<?php echo $_SESSION['package_num']; ?>"/>
          <input type="hidden" name="oversized" value="<?php echo $_SESSION['oversized']; ?>"/>
          <input type="hidden" name="saturday_delivery" value="<?php echo $_SESSION['saturday_delivery']; ?>"/>
          <input type="hidden" name="signature_type" value="<?php echo $_SESSION['signature_type']; ?>" />
          <input type="hidden" name="hold_at_location" value="<?php echo $_SESSION['hold_at_location']; ?>"/>
          <input type="hidden" name="hal_address" value="<?php echo $_SESSION['hal_address']; ?>"/>
          <input type="hidden" name="hal_city" value="<?php echo $_SESSION['hal_city']; ?>"/>
          <input type="hidden" name="hal_state" value="<?php echo $_SESSION['hal_state']; ?>"/>
          <input type="hidden" name="hal_postcode" value="<?php echo $_SESSION['hal_postcode']; ?>"/>
          <input type="hidden" name="hal_phone" value="<?php echo $_SESSION['hal_phone']; ?>"/>
          <input type="hidden" name="dim_height" value="<?php echo $_SESSION['dim_height']; ?>"/>
          <input type="hidden" name="dim_width" value="<?php echo $_SESSION['dim_width']; ?>"/>
          <input type="hidden" name="dim_length" value="<?php echo $_SESSION['dim_length']; ?>"/>
          <input type="hidden" name="residential" value="<?php echo $_SESSION['residential']; ?>"/>
          <input type="hidden" name="packaging_type" value="<?php echo $_SESSION['packaging_type']; ?>"/>
          <input type="hidden" name="service_type" value="<?php echo $_SESSION['service_type']; ?>"/>
          <input type="hidden" name="payment_type" value="<?php echo $_SESSION['payment_type']; ?>"/>
          <input type="hidden" name="bill_type" value="<?php echo $_SESSION['bill_type']; ?>"/>
          <input type="hidden" name="dropoff_type" value="<?php echo $_SESSION['dropoff_type']; ?>"/>
          <input type="hidden" name="pickup_date" value="<?php echo $_SESSION['pickup_date']; ?>"/>
          <input type="hidden" name="package_invoice" value="<?php echo $_SESSION['package_invoice']; ?>"/>
          <input type="hidden" name="package_reference" value="<?php echo $_SESSION['package_reference']; ?>"/>
          <input type="hidden" name="package_po" value="<?php echo $_SESSION['package_po']; ?>"/>
          <input type="hidden" name="package_department" value="<?php echo $_SESSION['package_department']; ?>"/>
          <input type="hidden" name="autopod" value="<?php echo $_SESSION['autopod']; ?>"/>
          <input type="hidden" name="telephone" value="<?php echo $_SESSION['telephone']; ?>" />
          <table width="70%" border="0" cellspacing="0" cellpadding="2">
            <tr>
              <td colspan="3"><?php echo zen_draw_separator('pixel_trans.gif', '1', '15'); ?></td>
            </tr>
            <!-- begin display for multiple packages -->
            <!-- begin package weight -->
            <tr>
              <td class="main" align="right">
<?php
            if ($package_num > 1) {
              echo TOTAL_WEIGHT . '</td>';
              }
            else {
              echo PACKAGE_WEIGHT . '</td>';
              }
?>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('package_weight','','size="2"'); ?></td>
            </tr>

<?php
            if ($package_num > 1) {
              echo '<tr>';
              for ($i = 1; $i <= $package_num; $i++) {
                echo '<td class="main" align="right">Package #' . $i . ' Weight:</td>';
                echo '<td class="main">&nbsp;</td>';
                $item_weight_rounded = sprintf("%01.1f", $item_weights);
                echo '<td class="main">' . zen_draw_input_field('package_weight' . $i, $item_weight_rounded, 'size="2"') . '</td>';
                $div = $i/3;
                if (is_int($div) && ($i != $package_num)) {
                  echo '</tr><tr>';
                  }
                }
              echo '</tr>';
            }
?>
            <!-- end package weight -->
            <!-- begin declared value -->
            <tr>
              <td class="main" align="right">
<?php
            echo TEXT_TOTAL_VALUE;
?>
              <td class="main">&nbsp;</td>
              <td class="main"><?php echo zen_draw_input_field('declare_value','','size="2"'); ?></td>
            </tr>

<?php
            if ($package_num > 1) {
              echo '<tr>';
              for ($i = 1; $i <= $package_num; $i++) {
                echo '<td class="main" align="right">Package #' . $i . ' Value:</td>';
                echo '<td class="main">&nbsp;</td>';
                //$item_weight_rounded = sprintf("%01.1f", $item_weights);
                echo '<td class="main">' . zen_draw_input_field('declare_value' . $i, '', 'size="2"') . '</td>';
                $div = $i/3;
                if (is_int($div) && ($i != $package_num)) {
                  echo '</tr><tr>';
                  }
                }
              echo '</tr>';
            }
?>
            <!-- end declared value -->
            <tr>
              <td>&nbsp;</td>
              <td>&nbsp;</td>
              <td><?php echo zen_image_submit('button_submit.gif', IMAGE_SUBMIT); ?></td>
            <tr>
            <!-- end display for multiple packages -->
          </table>
          </form>
<?php
      }
?>
          </td>
      </tr>
        </table></td>
      </tr>
    </table></td>
<!-- body_text_eof //-->
  </tr>
</table>
<!-- body_eof //-->

<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
<br />
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php');
}
?>