protected function editOrderSaveAction()
		{
			if (empty($_POST['quoteSession'])) {
				exit;
			}

			$quoteSession = $_POST['quoteSession'];

			/** @var ISC_QUOTE */
			$quote = getClass('ISC_ADMIN_ORDERS')->getQuoteSession($quoteSession);
			if(!$quote) {
				$this->sendEditOrderNoQuoteResponse('saveError');
			}

			try {
				$quote->setCustomerMessage(Interspire_Request::post('customerMessage'));
				$quote->setStaffNotes(Interspire_Request::post('staffNotes'));

				$entity = new ISC_ENTITY_ORDER;

				$currency = GetDefaultCurrency();
				$order = array(
					'ordcurrencyid' => $currency['currencyid'],
					'ordcurrencyexchangerate' => $currency['currencyexchangerate'],
					'ordipaddress' => getIp(),
					'extraInfo' => array(),
					'quote' => $quote,
				);

				$createAccount = false;

				// process customer details to see if an account should be made
				if (Interspire_Request::post('orderFor') == 'new') {
					// this really needs to be split off into another method because it's done both at the front end checkout, in save billing, and in here! -ge
					$password = '';
					$confirmedPassword = '';
					$email = '';
					$accountFormFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_ACCOUNT, true);
					$accountCustomFields = array();
					foreach($accountFormFields as $formFieldId => $formField) {
						$formFieldPrivateId = $formField->record['formfieldprivateid'];

						if (!$formFieldPrivateId) {
							$accountCustomFields[$formFieldId] = $formField->getValue();
						} else if($formFieldPrivateId == 'EmailAddress') {
							$email = $formField->getValue();
						} else if($formFieldPrivateId == 'Password') {
							$password = $formField->getValue();
						} else if($formFieldPrivateId == 'ConfirmPassword') {
							$confirmedPassword = $formField->getValue();
						}
					}

					// shouldn't reach this point with a valid email without all the details already being validated after step 1 > next, so go ahead and assign it to the order
					if ($email) {
						$createAccount = array(
							'addresses' => array(),
							'password' => $password,
							'customFormFields' => $accountCustomFields,
						);

						foreach ($quote->getAllAddresses() as /** @var ISC_QUOTE_ADDRESS */$address) {
							if (!$address->getSaveAddress()) {
								continue;
							}

							$customerAddress = $address->getAsArray();
							$customFields = $address->getCustomFields();
							if (!empty($customFields)) {
								$customerAddress['customFormFields'] = $customFields;

								// Shipping fields need to be mapped back to billing so they can be stored
								if ($address->getType() == ISC_QUOTE_ADDRESS::TYPE_SHIPPING) {
									$newCustomFields = array();
									$map = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, array_keys($customFields));
									foreach($map as $oldId => $newId) {
										$newCustomFields[$newId] = $customFields[$oldId];
									}
									$customerAddress['customFormFields'] = $newCustomFields;
								}
							}

							$createAccount['addresses'][] = $customerAddress;
						}
					}
				}

				if ($quote->getOrderId()) {
					$editing = true;
					$adding = false;

					$orderId = $quote->getOrderId();

					$existingOrder = $entity->get($orderId);
					if ($existingOrder['deleted']) {
						// don't allow saving changes for a deleted order
						$errors[] = GetLang('EditDeletedOrderError');
					} else {
						$order['orderid'] = $orderId;
						if (!$entity->edit($order)) {
							$errors[] = $entity->getError();
						}
					}
				} else {
					$editing = false;
					$adding = true;

					$order['orderpaymentmodule'] = '';

					$orderId = $entity->add($order);

					if ($orderId) {
						$quote->setOrderId($orderId);
					} else {
						$errors[] = $entity->getError();
					}
				}

				if (!empty($errors)) {
					$this->sendEditOrderResponse(array(
						'errors' => $errors,
						'stateTransition' => 'saveError',
					));
				}

				// retrieve the created/edited order record
				$order = GetOrder($orderId);

				if ($createAccount) {
					// this function doesn't return anything for error testing
					createOrderCustomerAccount($order, $createAccount);
				}

				// Process a payment
				$paymentMethod = Interspire_Request::post('paymentMethod');

				$providerSuccess = false;

				// Retrieve the payment method details
				$paymentFields = Interspire_Request::post('paymentField');
				if (!empty($paymentFields[$paymentMethod])) {
					$paymentFields = $paymentFields[$paymentMethod];
				}
				else {
					$paymentFields = array();
				}

				if ($quote->getGrandTotalWithStoreCredit() > 0 && ($adding || empty($order['ordpaymentstatus']) || empty($order['orderpaymentmodule'])) && !empty($paymentMethod)) {
					$gatewayAmount = $quote->getGrandTotalWithStoreCredit();

					$provider = null;

					// was a custom payment specified?
					if ($paymentMethod == 'custom') {
						$paymentMethodName = $paymentFields['custom_name'];
						$providerSuccess = true;
					}
					// actual payment module
					else {
						GetModuleById('checkout', $provider, $paymentMethod);
						if(is_object($provider)) {
							$paymentMethodName = $provider->GetDisplayName();

							if (method_exists($provider, 'ProcessManualPayment')) {
								// set the order token as required by various payment methods
								ISC_SetCookie('SHOP_ORDER_TOKEN', $order['ordtoken'], time() + (3600*24), true);
								// make the token immediately available
								$_COOKIE['SHOP_ORDER_TOKEN'] = $order['ordtoken'];

								// process the payment
								$result = $provider->ProcessManualPayment($order, $paymentFields);
								if ($result['result']) {
									$providerSuccess = true;
									$gatewayAmount = $result['amount'];

									FlashMessage(GetLang('OrderPaymentSuccess', array('amount' => FormatPrice($gatewayAmount), 'orderId' => $orderId, 'provider' => $paymentMethodName)), MSG_SUCCESS);
								}
								else {
									$errors[] = GetLang('OrderPaymentFail', array('orderId' => $orderId, 'provider' => $paymentMethodName, 'reason' => $result['message']));
								}
							}
							else {
								// all manual/offline methods will always be successfull
								$providerSuccess = true;
							}
						}
						else {
							// failed to get a payment module
						}
					}
				// if the grand total after minus the coupon,etc is 0 and it's adding order also the payment method is custom.
				} else if ($quote->getGrandTotalWithStoreCredit() == 0 && ($adding || empty($order['ordpaymentstatus']) || empty($order['orderpaymentmodule'])) && $paymentMethod == 'custom') {
					$paymentMethodName = $paymentFields['custom_name'];
					$providerSuccess = true;
				}

				// was payment successfull?
				if ($providerSuccess) {
					// record payment info for the order
					$updatedOrder = array(
						'orderpaymentmethod' 	=> $paymentMethodName,
						'orderpaymentmodule'	=> $paymentMethod,
					);

					$this->db->UpdateQuery("orders", $updatedOrder, "orderid = " . $orderId);

					// set appropriate status for the order
					if ($quote->isDigital()) {
						$newStatus = ORDER_STATUS_COMPLETED;
					}
					else {
						$newStatus = ORDER_STATUS_AWAITING_FULFILLMENT;
					}
					UpdateOrderStatus($orderId, $newStatus, false);

					// email invoice
					if (Interspire_Request::post('emailInvoiceToCustomer')) {
						EmailInvoiceToCustomer($orderId);
					}
				}

				if (!empty($errors)) {
					$response = array(
						'errors' => $errors,
						'stateTransition' => 'saveError',
					);
				}
				else {
					if ($editing) {
						FlashMessage(GetLang('OrderUpdated', array('orderId' => $orderId)), MSG_SUCCESS);
					} else {
						FlashMessage(GetLang('OrderCreated', array('orderId' => $orderId)), MSG_SUCCESS);
					}

					$response = array(
						'stateTransition' => 'saveOk',
					);

					// remove quote object from session after successful save and successful payment
					getClass('ISC_ADMIN_ORDERS')->deleteQuoteSession($quoteSession);
				}

				if ($adding) {
					$response['updateOrderId'] = $orderId;
				}

				$this->sendEditOrderResponse($response);
			} catch (ISC_QUOTE_EXCEPTION $exception) {
				$this->sendEditOrderResponse(array(
					'stateTransition' => 'saveError',
					'errors' => array(
						$exception->getMessage(),
					),
				));
			}
		}
 /**
  * Actually save a new order or an updated existing order in the database
  * after it's been validated.
  *
  * @param array An array of details about the order to save.
  * @param int The ID of the existing order if we're updating an order.
  * @return boolean True if successful, false if not.
  */
 private function CommitOrder($data, $orderId = 0)
 {
     $GLOBALS['ISC_CLASS_DB']->StartTransaction();
     /**
      * We need to find our billing/shipping details from the form fields first as it is
      * also used in creating the customer
      */
     $billingDetails = array();
     $shippingDetails = array();
     $billingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_BILLING, true);
     $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
     $fields = $billingFields + $shippingFields;
     $addressMap = array('FirstName' => 'firstname', 'LastName' => 'lastname', 'CompanyName' => 'company', 'AddressLine1' => 'address1', 'AddressLine2' => 'address2', 'City' => 'city', 'State' => 'state', 'Zip' => 'zip', 'State' => 'state', 'Country' => 'country', 'Phone' => 'phone');
     foreach (array_keys($fields) as $fieldId) {
         $privateName = $fields[$fieldId]->record['formfieldprivateid'];
         if ($privateName == '' || !array_key_exists($privateName, $addressMap)) {
             continue;
         }
         if ($fields[$fieldId]->record['formfieldformid'] == FORMFIELDS_FORM_BILLING) {
             $detailsVar =& $billingDetails;
         } else {
             $detailsVar =& $shippingDetails;
         }
         /**
          * Find the country
          */
         if (isc_strtolower($privateName) == 'country') {
             $detailsVar['shipcountry'] = $fields[$fieldId]->getValue();
             $detailsVar['shipcountryid'] = GetCountryByName($fields[$fieldId]->getValue());
             if (!isId($detailsVar['shipcountryid'])) {
                 $detailsVar['shipcountryid'] = 0;
             }
             /**
              * Else find the state
              */
         } else {
             if (isc_strtolower($privateName) == 'state') {
                 $detailsVar['shipstate'] = $fields[$fieldId]->getValue();
                 $stateInfo = GetStateInfoByName($detailsVar['shipstate']);
                 if ($stateInfo && isId($stateInfo['stateid'])) {
                     $detailsVar['shipstateid'] = $stateInfo['stateid'];
                 } else {
                     $detailsVar['shipstateid'] = 0;
                 }
                 /**
                  * Else the rest
                  */
             } else {
                 $detailsVar['ship' . $addressMap[$privateName]] = $fields[$fieldId]->getValue();
             }
         }
     }
     // If we're creating an account for this customer, create it now
     if ($data['ordcustid'] == 0 && $data['customerType'] == 'new') {
         $customerData = array('email' => $data['custconemail'], 'password' => $data['custpassword'], 'firstname' => $billingDetails['shipfirstname'], 'lastname' => $billingDetails['shiplastname'], 'company' => $billingDetails['shipcompany'], 'phone' => $billingDetails['shipphone'], 'token' => GenerateCustomerToken(), 'customergroupid' => $data['custgroupid']);
         $GLOBALS['CusFirstname'] = $billingDetails['shipfirstname'];
         # Baskaran
         /* Added the store credit as seperate as it may be disabled while add/edit order - vikas  */
         if (isset($data['custstorecredit'])) {
             $customerData['storecredit'] = DefaultPriceFormat($data['custstorecredit']);
         }
         /**
          * Save the customer custom fields
          */
         if (gzte11(ISC_MEDIUMPRINT)) {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ACCOUNT);
             if (isId($formSessionId)) {
                 $customerData['custformsessionid'] = $formSessionId;
             }
         }
         $entity = new ISC_ENTITY_CUSTOMER();
         $data['ordcustid'] = $entity->add($customerData);
         if (!$data['ordcustid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     }
     //2010-11-08 Ronnie add When calculating the ship infomation corresponding to no
     $GLOBALS['BCK_shipcountryid'] = $detailsVar['shipcountry'];
     $GLOBALS['BCK_shipstateid'] = $detailsVar['shipstate'];
     if ($GLOBALS['BCK_shipstateid'] == '') {
         $GLOBALS['BCK_shipcountryid'] = $billingDetails['shipcountry'];
         $GLOBALS['BCK_shipstateid'] = $billingDetails['shipstate'];
     }
     foreach ($this->GetCartApi()->GetProductsInCart() as $rowId => $product) {
         if (!isset($product['exists_order_coupon']) && isset($product['discount'])) {
             // Now workout the discount amount
             if ($product['coupontype'] == 0) {
                 // It's a dollar discount
                 $newPrice = $product['product_price'] - $product['discount'];
             } else {
                 // It's a percentage discount
                 $discount = $product['product_price'] / 100 * $product['discount'];
                 if ($discount == $product['product_price']) {
                     $newPrice = 0;
                 } else {
                     $newPrice = $product['product_price'] - $discount;
                 }
             }
             if ($newPrice < 0) {
                 $newPrice = 0;
             }
             $this->GetCartApi()->SetItemValue($rowId, 'discount_price', $newPrice);
         } elseif (isset($product['exists_order_coupon']) && isset($product['discount'])) {
             $this->GetCartApi()->SetItemValue($rowId, 'discount_price', $product['product_price']);
             $newPrice = 0;
             if ($product['coupontype'] == 0) {
                 // It's a dollar discount
                 $newPrice = $product['product_price'] + $product['discount'];
             } else {
                 // It's a percentage discount
                 $newPrice = $product['product_price'] / (1 - $product['discount'] / 100);
             }
             $this->GetCartApi()->SetItemValue($rowId, 'product_price', $newPrice);
         }
     }
     $orderSummary = $this->CalculateOrderSummary();
     //ronnie
     //$orderSummary['taxCost'];
     $defaultCurrency = GetDefaultCurrency();
     $email = '';
     if (isset($data['custconemail']) && $data['customerType'] == 'new') {
         $email = $data['custconemail'];
     } else {
         if (isset($data['anonymousemail']) && $data['customerType'] == 'anonymous') {
             $email = $data['anonymousemail'];
         }
     }
     /**********************************************************
     				Code added by Mayank Jaitly for getting the logged user
     				for adding his/her id as order owner.
     			************************************************************/
     $loggeduser = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetUser();
     //////////  End of alteration
     $custid = $data['ordcustid'];
     $ordstatus = '';
     $query = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]customers c, [|PREFIX|]customer_groups cg WHERE c.customerid = '{$custid}' AND cg.customergroupid = c.custgroupid AND cg.groupname = 'Walk In' ");
     if ($GLOBALS['ISC_CLASS_DB']->CountResult($query) > 0) {
         $ordstatus = '10';
     } else {
         $ordstatus = $data['ordstatus'];
     }
     $billemail = $email;
     $shipemail = $email;
     if ($data['customerType'] == 'anonymous') {
         if (isset($data['anonymousemail']) && !empty($data['anonymousemail'])) {
             $billemail = $email;
             $shipemail = $email;
         } else {
             $billemail = $_POST['ordbillemail'];
             $shipemail = $_POST['ordshipemail'];
         }
     }
     $newOrder = array('paymentmethod' => $data['orderpaymentmodule'], 'customerid' => $data['ordcustid'], 'billingaddress' => $billingDetails, 'ordbillemail' => $billemail, 'ordshipemail' => $shipemail, 'ordbillphone' => $billingDetails['shipphone'], 'geoipcountry' => $billingDetails['shipcountry'], 'geoipcountrycode' => GetCountryISO2ByName($billingDetails['shipcountry']), 'vendorid' => $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId(), 'giftcertificates' => $this->GetCartApi()->GetGiftCertificates(), 'shippingcost' => $orderSummary['shippingCost'], 'handlingcost' => $orderSummary['handlingCost'], 'pending_token' => GenerateOrderToken(), 'itemtotal' => $orderSummary['subtotal'], 'taxcost' => $orderSummary['taxCost'], 'taxrate' => $orderSummary['taxRate'], 'taxname' => $orderSummary['taxName'], 'giftcertificateamount' => $orderSummary['giftCertificateTotal'], 'companygiftcertificateamount' => $orderSummary['companyGiftCertificateTotal'], 'gatewayamount' => $orderSummary['adjustedTotalCost'], 'totalincludestax' => $orderSummary['taxIncluded'], 'shippingprovider' => $orderSummary['shippingMethod'], 'shippingmodule' => $orderSummary['shippingModule'], 'totalcost' => $orderSummary['total'], 'ordstatus' => 0, 'isdigitalorder' => (int) $this->GetCartApi()->AllProductsInCartAreIntangible(), 'currencyid' => $defaultCurrency['currencyid'], 'currencyexchangerate' => 0, 'ordercomments' => @$data['ordcustmessage'], 'ordnotes' => @$data['ordnotes'], 'products' => $this->GetCartApi()->GetProductsInCart(), 'ordtrackingno' => $data['ordtrackingno'], 'orderowner' => $loggeduser['pk_userid']);
     if (isset($data['ordbillsaveAddress'])) {
         $newOrder['billingaddress']['saveAddress'] = 1;
         if (gzte11(ISC_MEDIUMPRINT)) {
             $newOrder['billingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_BILLING);
         }
     }
     if ($newOrder['paymentmethod'] == 'manual') {
         $newOrder['paymentmethodname'] = GetLang('ManualPayment');
     } else {
         if ($newOrder['paymentmethod'] == 'giftcertificate') {
             $newOrder['giftcertificateamount'] = $orderSummary['total'];
         } else {
             if ($newOrder['paymentmethod'] == 'storecredit') {
                 $newOrder['storecreditamount'] = $orderSummary['total'];
             } else {
                 if ($newOrder['paymentmethod'] == 'custom') {
                     $newOrder['paymentmethodname'] = $data['paymentField']['custom']['name'];
                 } else {
                     if ($newOrder['paymentmethod'] == 'paypal_admin') {
                         // added new condition for paypal payment option - vikas
                         $newOrder['paymentmethodname'] = GetLang('PaypalPayment');
                     } else {
                         if ($newOrder['paymentmethod'] == 'googlecheckout_admin') {
                             $newOrder['paymentmethodname'] = GetLang('GooglePayment');
                         } else {
                             if ($newOrder['paymentmethod'] == 'creditcard') {
                                 $newOrder['paymentmethodname'] = GetLang('CreditCardPayment');
                             } else {
                                 if ($newOrder['paymentmethod'] == 'cash') {
                                     $newOrder['paymentmethodname'] = GetLang('CashPayment');
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if (!$this->GetCartApi()->AllProductsInCartAreIntangible()) {
         if (isset($data['shippingUseBilling']) && $data['shippingUseBilling'] == 1) {
             $newOrder['shippingaddress'] = $newOrder['billingaddress'];
         } else {
             $newOrder['shippingaddress'] = $shippingDetails;
             if (isset($data['ordshipsaveAddress']) && gzte11(ISC_MEDIUMPRINT)) {
                 /**
                  * This is a bit tricky. We need to convert these shipping fields to use the billing
                  * field IDs when saving in the shipping_addresses table as they all use the billing
                  * fields on the frontend
                  */
                 $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
                 $shippingKeys = array_keys($shippingFields);
                 $shippingMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, $shippingKeys);
                 $shippingSessData = array();
                 foreach ($shippingMap as $fieldId => $newBillingId) {
                     if ($shippingFields[$fieldId]->record['formfieldprivateid'] !== '') {
                         continue;
                     }
                     $shippingSessData[$newBillingId] = $shippingFields[$fieldId]->getValue();
                 }
                 $newOrder['shippingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($shippingSessData);
             }
         }
         if (isset($data['ordshipsaveAddress'])) {
             $newOrder['shippingaddress']['saveAddress'] = 1;
         }
     }
     if ($orderId > 0) {
         $existingOrder = GetOrder($orderId);
         $newOrder['vendorid'] = $existingOrder['ordvendorid'];
         $newOrder['extraInfo'] = @unserialize($existingOrder['extrainfo']);
         //Alandy_2011-14-20 debug credit amount error! recalculate the gatewayamount,fetch the gatewayamount from profer order is wrong!
         //$newOrder['gatewayamount'] = $existingOrder['ordgatewayamount'];
         $newOrder['storecreditamount'] = $existingOrder['ordstorecreditamount'];
         $newOrder['currencyid'] = $existingOrder['ordcurrencyid'];
         $newOrder['currencyexchangerate'] = $existingOrder['ordcurrencyexchangerate'];
         $newOrder['orderid'] = $orderId;
         $newOrder['orddate'] = $existingOrder['orddate'];
         $newOrder['ordipaddress'] = $existingOrder['ordipaddress'];
     }
     /**
      * Save the billing/shipping custom fields for the order
      */
     if (gzte11(ISC_MEDIUMPRINT)) {
         if (isId($orderId) && isset($existingOrder['ordformsessionid']) && isId($existingOrder['ordformsessionid'])) {
             $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING), true, $existingOrder['ordformsessionid']);
         } else {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING));
             if (isId($formSessionId)) {
                 $newOrder['ordformsessionid'] = $formSessionId;
             }
         }
     }
     // dada.wang 20120406 save cgc change
     $cgces = $this->GetCartApi()->Get('COMPANYGIFTCERTIFICATES');
     if (is_array($cgces) && !empty($cgces)) {
         $newOrder['companygiftcertificates'] = $cgces;
     }
     $entity = new ISC_ENTITY_ORDER();
     if (isset($existingOrder)) {
         $newOrder['adminflag'] = 1;
         //dada.wang 2012-04-10 if has gc or cgc was remove then use this function to remove it
         $this->RemoveGCAndCGC($newOrder);
         if (!$entity->edit($newOrder)) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     } else {
         $newOrder['adminflag'] = 1;
         $data['orderid'] = $entity->add($newOrder);
         if (!$data['orderid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
         $newOrder['orderid'] = $data['orderid'];
     }
     // If one or more gift certificates were used we need to apply them to this order
     if ($newOrder['giftcertificateamount'] > 0 && isset($newOrder['giftcertificates']) && !empty($newOrder['giftcertificates'])) {
         $usedCertificates = array();
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->ApplyGiftCertificatesToOrder($newOrder['orderid'], $newOrder['totalcost'], $newOrder['giftcertificates'], $usedCertificates);
     }
     // Add by NI_20100827_Jack
     // If one or more gift certificates were used we need to apply them to this order
     if ($newOrder['companygiftcertificateamount'] > 0 && isset($newOrder['companygiftcertificates']) && !empty($newOrder['companygiftcertificates'])) {
         $usedCertificates = array();
         $GLOBALS['ISC_CLASS_COMPANY_GIFT_CERTIFICATES'] = GetClass('ISC_COMPANYGIFTCERTIFICATES');
         $GLOBALS['ISC_CLASS_COMPANY_GIFT_CERTIFICATES']->ApplyCompanyGiftCertificatesToOrder($newOrder['orderid'], $newOrder['totalcost'], $newOrder['companygiftcertificates'], $usedCertificates);
     }
     $GLOBALS['ISC_CLASS_DB']->CommitTransaction();
     // Did the payment method have any info it needs to save? Save it
     $provider = null;
     GetModuleById('checkout', $provider, $data['orderpaymentmodule']);
     if (is_object($provider) && method_exists($provider, 'SaveManualPaymentFields')) {
         $fields = $data['paymentField'][$data['orderpaymentmodule']];
         $provider->SaveManualPaymentFields(GetOrder($data['orderid'], false, false), $fields);
     }
     if ($data['ordstatus'] != $newOrder['ordstatus']) {
         UpdateOrderStatus($data['orderid'], $data['ordstatus'], false);
     }
     // If we're emailing the customer about their order, send it now
     if (isset($data['emailinvoice']) && $data['emailinvoice'] == 1) {
         EmailInvoiceToCustomer($data['orderid']);
     }
     unset($_SESSION['ORDER_MANAGER'][$data['orderSession']]);
     /*************************************************************
     					Alterations done by Mayank Jaitly on 28 June 2010
     			**************************************************************/
     /*	
     // commented the below code as this is not needed.
     	$customerYMMdata=array(
     						   	'year' => $data['searchyear'],
     							'make' => $data['searchmake'],
     							'model' => MakeURLNormal($data['searchmodel']),
     							'bed_size' =>$data['bedsize'],
     							'cab_size' =>$data['cabsize']
     							
     						   );
     							   
     	$clarion_entity = new ISC_ADMIN_CLARION();
     	$ymmID=$clarion_entity->fnSaveUserYMM($customerYMMdata,$data['ordcustid'],$_REQUEST['customerType'],$data['orderid']);
     */
     /***********************	End of Alteration		*********/
     /***************************************************************
     				Code Added by Mayank Jaitly on 29 June 2010
     			****************************************************************/
     // commented the below code as this is not needed.
     //	$clarion_entity->fnUpdateOrderYMM($data['orderid'],$ymmID);
     /********************* End of code   **************************/
     return $data['orderid'];
 }
 /**
  * Actually save a new order or an updated existing order in the database
  * after it's been validated.
  *
  * @param array An array of details about the order to save.
  * @param int The ID of the existing order if we're updating an order.
  * @return boolean True if successful, false if not.
  */
 private function CommitOrder($data, $orderId = 0)
 {
     $GLOBALS['ISC_CLASS_DB']->StartTransaction();
     /**
      * We need to find our billing/shipping details from the form fields first as it is
      * also used in creating the customer
      */
     $billingDetails = array();
     $shippingDetails = array();
     $billingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_BILLING, true);
     $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
     $fields = $billingFields + $shippingFields;
     $addressMap = array('FirstName' => 'firstname', 'LastName' => 'lastname', 'CompanyName' => 'company', 'AddressLine1' => 'address1', 'AddressLine2' => 'address2', 'City' => 'city', 'State' => 'state', 'Zip' => 'zip', 'State' => 'state', 'Country' => 'country', 'Phone' => 'phone');
     foreach (array_keys($fields) as $fieldId) {
         $privateName = $fields[$fieldId]->record['formfieldprivateid'];
         if ($privateName == '' || !array_key_exists($privateName, $addressMap)) {
             continue;
         }
         if ($fields[$fieldId]->record['formfieldformid'] == FORMFIELDS_FORM_BILLING) {
             $detailsVar =& $billingDetails;
         } else {
             $detailsVar =& $shippingDetails;
         }
         /**
          * Find the country
          */
         if (isc_strtolower($privateName) == 'country') {
             $detailsVar['shipcountry'] = $fields[$fieldId]->getValue();
             $detailsVar['shipcountryid'] = GetCountryByName($fields[$fieldId]->getValue());
             if (!isId($detailsVar['shipcountryid'])) {
                 $detailsVar['shipcountryid'] = 0;
             }
             /**
              * Else find the state
              */
         } else {
             if (isc_strtolower($privateName) == 'state') {
                 $detailsVar['shipstate'] = $fields[$fieldId]->getValue();
                 $stateInfo = GetStateInfoByName($detailsVar['shipstate']);
                 if ($stateInfo && isId($stateInfo['stateid'])) {
                     $detailsVar['shipstateid'] = $stateInfo['stateid'];
                 } else {
                     $detailsVar['shipstateid'] = 0;
                 }
                 /**
                  * Else the rest
                  */
             } else {
                 $detailsVar['ship' . $addressMap[$privateName]] = $fields[$fieldId]->getValue();
             }
         }
     }
     // If we're creating an account for this customer, create it now
     if ($data['ordcustid'] == 0 && $data['customerType'] == 'new') {
         $customerData = array('email' => $data['custconemail'], 'password' => $data['custpassword'], 'firstname' => $billingDetails['shipfirstname'], 'lastname' => $billingDetails['shiplastname'], 'company' => $billingDetails['shipcompany'], 'phone' => $billingDetails['shipphone'], 'token' => GenerateCustomerToken(), 'customergroupid' => $data['custgroupid'], 'storecredit' => DefaultPriceFormat($data['custstorecredit']));
         /**
          * Save the customer custom fields
          */
         if (gzte11(ISC_MEDIUMPRINT)) {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ACCOUNT);
             if (isId($formSessionId)) {
                 $customerData['custformsessionid'] = $formSessionId;
             }
         }
         $entity = new ISC_ENTITY_CUSTOMER();
         $data['ordcustid'] = $entity->add($customerData);
         if (!$data['ordcustid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     }
     $orderSummary = $this->CalculateOrderSummary();
     $defaultCurrency = GetDefaultCurrency();
     $email = '';
     if (isset($data['custconemail']) && $data['customerType'] == 'new') {
         $email = $data['custconemail'];
     } else {
         if (isset($data['anonymousemail']) && $data['customerType'] == 'anonymous') {
             $email = $data['anonymousemail'];
         }
     }
     $newOrder = array('paymentmethod' => $data['orderpaymentmodule'], 'customerid' => $data['ordcustid'], 'billingaddress' => $billingDetails, 'ordbillemail' => $email, 'ordbillphone' => $billingDetails['shipphone'], 'geoipcountry' => $billingDetails['shipcountry'], 'geoipcountrycode' => GetCountryISO2ByName($billingDetails['shipcountry']), 'vendorid' => $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId(), 'giftcertificates' => $this->GetCartApi()->GetGiftCertificates(), 'shippingcost' => $orderSummary['shippingCost'], 'handlingcost' => $orderSummary['handlingCost'], 'pending_token' => GenerateOrderToken(), 'itemtotal' => $orderSummary['subtotal'], 'taxcost' => $orderSummary['taxCost'], 'taxrate' => $orderSummary['taxRate'], 'taxname' => $orderSummary['taxName'], 'giftcertificateamount' => $orderSummary['giftCertificateTotal'], 'gatewayamount' => $orderSummary['adjustedTotalCost'], 'totalincludestax' => $orderSummary['taxIncluded'], 'shippingprovider' => $orderSummary['shippingMethod'], 'shippingmodule' => $orderSummary['shippingModule'], 'totalcost' => $orderSummary['total'], 'ordstatus' => 0, 'isdigitalorder' => (int) $this->GetCartApi()->AllProductsInCartAreIntangible(), 'currencyid' => $defaultCurrency['currencyid'], 'currencyexchangerate' => 0, 'ordercomments' => @$data['ordcustmessage'], 'ordnotes' => @$data['ordnotes'], 'products' => $this->GetCartApi()->GetProductsInCart(), 'ordtrackingno' => $data['ordtrackingno']);
     if (isset($data['ordbillsaveAddress'])) {
         $newOrder['billingaddress']['saveAddress'] = 1;
         if (gzte11(ISC_MEDIUMPRINT)) {
             $newOrder['billingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_BILLING);
         }
     }
     if ($newOrder['paymentmethod'] == 'manual') {
         $newOrder['paymentmethodname'] = GetLang('ManualPayment');
     } else {
         if ($newOrder['paymentmethod'] == 'giftcertificate') {
             $newOrder['giftcertificateamount'] = $orderSummary['total'];
         } else {
             if ($newOrder['paymentmethod'] == 'storecredit') {
                 $newOrder['storecreditamount'] = $orderSummary['total'];
             } else {
                 if ($newOrder['paymentmethod'] == 'custom') {
                     $newOrder['paymentmethodname'] = $data['paymentField']['custom']['name'];
                 }
             }
         }
     }
     if (!$this->GetCartApi()->AllProductsInCartAreIntangible()) {
         if (isset($data['shippingUseBilling']) && $data['shippingUseBilling'] == 1) {
             $newOrder['shippingaddress'] = $newOrder['billingaddress'];
         } else {
             $newOrder['shippingaddress'] = $shippingDetails;
             if (isset($data['ordshipsaveAddress']) && gzte11(ISC_MEDIUMPRINT)) {
                 /**
                  * This is a bit tricky. We need to convert these shipping fields to use the billing
                  * field IDs when saving in the shipping_addresses table as they all use the billing
                  * fields on the frontend
                  */
                 $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
                 $shippingKeys = array_keys($shippingFields);
                 $shippingMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, $shippingKeys);
                 $shippingSessData = array();
                 foreach ($shippingMap as $fieldId => $newBillingId) {
                     if ($shippingFields[$fieldId]->record['formfieldprivateid'] !== '') {
                         continue;
                     }
                     $shippingSessData[$newBillingId] = $shippingFields[$fieldId]->getValue();
                 }
                 $newOrder['shippingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($shippingSessData);
             }
         }
         if (isset($data['ordshipsaveAddress'])) {
             $newOrder['shippingaddress']['saveAddress'] = 1;
         }
     }
     if ($orderId > 0) {
         $existingOrder = GetOrder($orderId);
         $newOrder['vendorid'] = $existingOrder['ordvendorid'];
         $newOrder['extraInfo'] = @unserialize($existingOrder['extrainfo']);
         $newOrder['gatewayamount'] = $existingOrder['ordgatewayamount'];
         $newOrder['storecreditamount'] = $existingOrder['ordstorecreditamount'];
         $newOrder['currencyid'] = $existingOrder['ordcurrencyid'];
         $newOrder['currencyexchangerate'] = $existingOrder['ordcurrencyexchangerate'];
         $newOrder['orderid'] = $orderId;
         $newOrder['orddate'] = $existingOrder['orddate'];
         $newOrder['ordipaddress'] = $existingOrder['ordipaddress'];
     }
     /**
      * Save the billing/shipping custom fields for the order
      */
     if (gzte11(ISC_MEDIUMPRINT)) {
         if (isId($orderId) && isset($existingOrder['ordformsessionid']) && isId($existingOrder['ordformsessionid'])) {
             $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING), true, $existingOrder['ordformsessionid']);
         } else {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING));
             if (isId($formSessionId)) {
                 $newOrder['ordformsessionid'] = $formSessionId;
             }
         }
     }
     $entity = new ISC_ENTITY_ORDER();
     if (isset($existingOrder)) {
         if (!$entity->edit($newOrder)) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     } else {
         $data['orderid'] = $entity->add($newOrder);
         if (!$data['orderid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     }
     // If one or more gift certificates were used we need to apply them to this order
     if ($newOrder['giftcertificateamount'] > 0 && isset($newOrder['giftcertificates']) && !empty($newOrder['giftcertificates'])) {
         $usedCertificates = array();
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->ApplyGiftCertificatesToOrder($newOrder['orderid'], $newOrder['totalcost'], $newOrder['giftcertificates'], $usedCertificates);
     }
     $GLOBALS['ISC_CLASS_DB']->CommitTransaction();
     // Did the payment method have any info it needs to save? Save it
     $provider = null;
     GetModuleById('checkout', $provider, $data['orderpaymentmodule']);
     if (is_object($provider) && method_exists($provider, 'SaveManualPaymentFields')) {
         $fields = $data['paymentField'][$data['orderpaymentmodule']];
         $provider->SaveManualPaymentFields(GetOrder($data['orderid'], false, false), $fields);
     }
     if ($data['ordstatus'] != $newOrder['ordstatus']) {
         UpdateOrderStatus($data['orderid'], $data['ordstatus'], false);
     }
     // If we're emailing the customer about their order, send it now
     if (isset($data['emailinvoice']) && $data['emailinvoice'] == 1) {
         EmailInvoiceToCustomer($data['orderid']);
     }
     unset($_SESSION['ORDER_MANAGER'][$data['orderSession']]);
     return $data['orderid'];
 }