Skip to content

Instantly share code, notes, and snippets.

@madismanni
Last active June 18, 2018 17:39

Revisions

  1. madismanni revised this gist Jul 12, 2017. 2 changed files with 66 additions and 0 deletions.
    65 changes: 65 additions & 0 deletions Checkout.php
    Original file line number Diff line number Diff line change
    @@ -336,8 +336,73 @@ public function getAvailableRates($rates)
    return $return;
    }

    // >>> SUPEE-9767

    /**
    * Add secret key to url config path
    */
    const XML_CSRF_USE_FLAG_CONFIG_PATH = 'system/csrf/use_form_key';

    /**
    * Validate Form Key
    *
    * @return bool
    */
    function __validateFormKey()
    {
    if (!($formKey = $this->getRequest()->getParam('form_key', null))
    || $formKey != Mage::getSingleton('core/session')->getFormKey()) {
    return false;
    }
    return true;
    }

    /**
    * Validate Form Key
    *
    * @return bool
    */
    protected function _validateFormKey()
    {
    $validated = true;
    if ($this->_isFormKeyEnabled()) {
    $validated = $this->__validateFormKey();
    }
    return $validated;
    }

    /**
    * Check if form key validation is enabled.
    *
    * @return bool
    */
    protected function _isFormKeyEnabled()
    {
    return Mage::getStoreConfigFlag(self::XML_CSRF_USE_FLAG_CONFIG_PATH);
    }

    /**
    * Check if form_key validation enabled on checkout process
    *
    * @return bool
    */
    protected function isFormkeyValidationOnCheckoutEnabled()
    {
    return Mage::getStoreConfigFlag('admin/security/validate_formkey_checkout');
    }
    // <<< SUPEE-9767


    public function _handlePostData()
    {

    // >>> SUPEE-9767
    if ($this->isFormkeyValidationOnCheckoutEnabled() && !$this->_validateFormKey()) {
    return;
    }
    // <<< SUPEE-9767


    $this->formErrors = array(
    'billing_errors' => array(),
    'shipping_errors' => array(),
    1 change: 1 addition & 0 deletions checkout.phtml
    Original file line number Diff line number Diff line change
    @@ -23,6 +23,7 @@ $helper = Mage::helper('onestepcheckout/checkout');

    <form id="onestepcheckout-form" method="post" action="<?php echo $this->getUrl('onestepcheckout', array('_secure'=>true)); ?>">
    <fieldset class="group-select" style="margin: 0;">
    <?php echo $this->getBlockHtml('formkey') ?>

    <?php if($this->settings['checkout_title']): ?>
    <h1 class="onestepcheckout-title"><?php echo $this->settings['checkout_title']; ?></h1>
  2. madismanni created this gist Jul 12, 2017.
    1,140 changes: 1,140 additions & 0 deletions Checkout.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,1140 @@
    <?php
    /**
    {{COPYRIGHT_NOTICE}}
    */

    class Idev_OneStepCheckout_Block_Checkout extends Mage_Checkout_Block_Onepage_Abstract
    {

    public $formErrors;
    public $settings;
    public $log = array();
    public $_rates = 0;
    public $subscribes = false;


    const SESSION_ADDRESS_CHECK_NAME = 'onestepcheckout_address_check_name';

    protected function _loadConfig()
    {
    $this->settings = Mage::helper('onestepcheckout/checkout')->loadConfig();
    }

    public function _getDefaultShippingMethod()
    {
    if($this->settings['default_shipping_method'] != '') {
    return $this->settings['default_shipping_method'];
    }
    else {
    $check_single = $this->_checkSingleShippingMethod();
    if($check_single) {
    return $check_single;
    }
    }
    }

    protected function _checkSingleShippingMethod()
    {
    $rates = $this->getOnepage()->getQuote()->getShippingAddress()->getShippingRatesCollection();
    $rateCodes = array();

    foreach($rates as $rate) {
    if(!in_array($rate->getCode(), $rateCodes)) {
    $rateCodes[] = $rate->getCode();
    }
    }

    if(count($rateCodes) == 1) {
    return $rateCodes[0];
    }

    return false;
    }

    protected function _isLoggedInWithAddresses()
    {
    $helper = $this->helper('customer');
    if($helper->isLoggedIn() && $helper->customerHasAddresses() ) {
    return true;
    }

    return false;
    }

    protected function _isLoggedIn()
    {
    $helper = $this->helper('customer');
    if($helper->isLoggedIn() ) {
    return true;
    }

    return false;

    }

    public function _construct()
    {
    parent::_construct();

    $this->getQuote()->setIsMultiShipping(false);

    $this->email = false;
    $this->customer_after_place_order = false;
    $this->_loadConfig();

    if($this->_isLoggedIn()) {
    $helper = Mage::helper('customer');
    $customer = $helper->getCustomer();
    $this->email = $customer->getEmail();
    }

    //we need to refactor this , not a neat way to make all in constructor
    if($this->getSubTemplate()){
    return true;
    }

    try {
    $this->_handlePostData();
    } catch(Exception $e) {
    $redirect = $this->getUrl('checkout/cart');
    $response = Mage::app()->getResponse();
    Mage::app()->getFrontController()->setNoRender(true);
    return $response->setRedirect($redirect);
    }
    }

    public function getEstimateRates()
    {
    if (empty($this->_rates)) {
    $groups = $this->getQuote()->getShippingAddress()->getGroupedAllShippingRates();
    $this->_rates = $groups;
    }

    return $this->_rates;
    }

    public function getAddressesHtmlSelect($type)
    {
    if ($this->isCustomerLoggedIn()) {
    $options = array();
    foreach ($this->getCustomer()->getAddresses() as $address) {
    $options[] = array(
    'value'=>$address->getId(),
    'label'=>$address->format('oneline')
    );
    }

    $addressId = '';
    if (empty($addressId)) {
    if ($type=='billing') {
    $address = $this->getCustomer()->getDefaultBillingAddress();
    } else {
    $address = $this->getCustomer()->getDefaultShippingAddress();
    }

    if ($address) {
    $addressId = $address->getId();
    }
    }

    if ($type=='billing') {
    $address = $this->getQuote()->getBillingAddress();
    } else {
    $address = $this->getQuote()->getShippingAddress();
    }

    if ($address) {
    $addressIde = $address->getCustomerAddressId();
    if($addressIde){
    $addressId = $addressIde;
    }
    }

    $select = $this->getLayout()->createBlock('core/html_select')
    ->setName($type.'_address_id')
    ->setId($type.'-address-select')
    ->setClass('address-select')
    ->setExtraParams('onchange="'.$type.'.newAddress(!this.value)"')
    ->setValue($addressId)
    ->setOptions($options);

    $select->addOption('', Mage::helper('checkout')->__('New Address'));

    $isPost = $this->getRequest()->getPost();
    $isPost = (!empty($isPost));
    $selectedValue = $this->getRequest()->getPost('billing_address_id', false);


    if($this->getNewAddressSelectValueOnError($type)){
    $select->setValue('');
    }

    return $select->getHtml();
    }

    return '';
    }

    public function getNewAddressSelectValueOnError($type)
    {

    if ($type=='billing') {
    $selectedValue = $this->getRequest()->getPost('billing_address_id', false);
    } else {
    $selectedValue = $this->getRequest()->getPost('shipping_address_id', false);
    }

    $isPost = $this->getRequest()->getPost();
    $isPost = (!empty($isPost));

    if($isPost && $selectedValue == ''){
    return true;
    }

    return false;
    }

    public function hasAjaxSaveBillingField($name)
    {
    $fields = explode(',', $this->settings['ajax_save_billing_fields']);

    if(in_array($name, $fields)) {
    return true;
    }

    return false;
    }

    public function sameAsBilling()
    {
    $return = true;
    $billing_data = $this->getRequest()->getPost('billing', array());
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
    if(empty($billing_data['use_for_shipping'])) {
    $return = false;
    } else {
    $return = true;
    }
    }

    $address = $this->getQuote()->getShippingAddress();

    if(!$this->getQuote()->getShippingAddress()->getSameAsBilling()) {
    $return = false;
    } else {
    $return = true;
    }

    return $return;
    }

    public function differentShippingAvailable()
    {
    if($this->isVirtual()) {
    return false;
    }

    if($this->settings['enable_different_shipping']) {
    return true;
    }

    return false;
    }

    public function isVirtual()
    {
    return $this->getOnepage()->getQuote()->isVirtual();
    }

    public function hasFormErrors()
    {
    if($this->hasShippingErrors() || $this->hasBillingErrors() || $this->hasMethodErrors() || $this->hasShipmentErrors()) {
    return true;
    }

    return false;
    }

    public function hasMethodErrors()
    {
    if(isset($this->formErrors['shipping_method']) && $this->formErrors['shipping_method']) {
    return true;
    }

    if(isset($this->formErrors['payment_method']) && $this->formErrors['payment_method']) {
    return true;
    }

    if(isset($this->formErrors['payment_method_error'])) {
    return true;
    }

    if(isset($this->formErrors['terms_error'])) {
    return true;
    }

    if(isset($this->formErrors['agreements_error'])) {
    return true;
    }

    return false;
    }

    public function hasShippingErrors()
    {
    if(isset($this->formErrors['shipping_errors'])) {
    if(count($this->formErrors['shipping_errors']) == 0) {
    return false;
    }

    return true;
    }
    else {
    return true;
    }
    }

    public function hasBillingErrors()
    {
    if(!empty($this->formErrors)) {
    if(isset($this->formErrors['billing_errors'])) {
    if(empty($this->formErrors['billing_errors'])) {
    return false;
    }

    return true;
    }
    else {
    return true;
    }
    }

    return false;
    }

    public function hasShipmentErrors()
    {
    if(!empty($this->formErrors['shipping_method'])){
    return true;
    }

    return false;
    }

    public function getAvailableRates($rates)
    {
    $return = array();
    if(!empty($rates)){
    foreach ($rates as $_code => $_rates){
    foreach ($_rates as $rate){
    $return['codes'][] = $rate->getCode();
    $return['rates'][$rate->getCode()] = $rate;
    }
    }
    }

    return $return;
    }

    public function _handlePostData()
    {
    $this->formErrors = array(
    'billing_errors' => array(),
    'shipping_errors' => array(),
    );

    $post = $this->getRequest()->getPost();

    if(!$post) {
    return;
    }

    // Save billing information

    $checkoutHelper = Mage::helper('onestepcheckout/checkout');

    $payment_data = $this->getRequest()->getPost('payment');

    $billing_data = $this->getRequest()->getPost('billing', array());
    $shipping_data = $this->getRequest()->getPost('shipping', array());

    $billing_data = $checkoutHelper->load_exclude_data($billing_data);
    $shipping_data = $checkoutHelper->load_exclude_data($shipping_data);
    $getCreateAccount = $this->getRequest()->getPost('create_account', false);

    //ensure that address fields order is preserved after changing field order
    if (! empty($billing_data ['street']) && is_array($billing_data ['street'])) {
    ksort($billing_data ['street']);
    }

    if (! empty($shipping_data ['street']) && is_array($shipping_data ['street'])) {
    ksort($shipping_data ['street']);
    }

    if(!empty($billing_data)){
    $this->getQuote()->getBillingAddress()->addData($billing_data)->implodeStreetAddress();
    }

    if($this->differentShippingAvailable()) {
    $this->getQuote()->getShippingAddress()->setCountryId($shipping_data['country_id'])->setCollectShippingRates(true);
    }

    //handle comments and feedback
    $enableComments = Mage::getStoreConfig('onestepcheckout/exclude_fields/enable_comments');
    $enableCommentsDefault = Mage::getStoreConfig('onestepcheckout/exclude_fields/enable_comments_default');
    $orderComment = $this->getRequest()->getPost('onestepcheckout_comments');
    $orderComment = trim($orderComment);
    if($enableComments && !$enableCommentsDefault) {
    if ($orderComment != ""){
    $this->getQuote()->setOnestepcheckoutCustomercomment(Mage::helper('core')->escapeHtml($orderComment));
    }
    }

    $enableFeedback = Mage::getStoreConfig('onestepcheckout/feedback/enable_feedback');
    if($enableFeedback){
    $feedbackValues = unserialize(Mage::getStoreConfig('onestepcheckout/feedback/feedback_values'));
    $feedbackValue = $this->getRequest()->getPost('onestepcheckout-feedback');
    $feedbackValueFreetext = $this->getRequest()->getPost('onestepcheckout-feedback-freetext');
    if(!empty($feedbackValue)){
    if($feedbackValue!='freetext'){
    $feedbackValue = $feedbackValues[$feedbackValue]['value'];
    } else {
    $feedbackValue = $feedbackValueFreetext;
    }

    $this->getQuote()->setOnestepcheckoutCustomerfeedback(Mage::helper('core')->escapeHtml($feedbackValue));
    }
    }

    //handle comments and feedback end

    if(isset($billing_data['email'])) {
    $this->email = $billing_data['email'];
    }

    if(!$this->_isLoggedIn()){
    $registration_mode = $this->settings['registration_mode'];
    if($registration_mode == 'auto_generate_account') {
    // Modify billing data to contain password also
    $password = Mage::helper('onestepcheckout/checkout')->generatePassword();
    $billing_data['customer_password'] = $password;
    $billing_data['confirm_password'] = $password;
    $this->getQuote()->getCustomer()->setData('password', $password);
    $this->getQuote()->setData('password_hash', Mage::getModel('customer/customer')->encryptPassword($password));
    }

    if($registration_mode == 'require_registration' || $registration_mode == 'allow_guest') {
    if(!empty($billing_data['customer_password']) && !empty($billing_data['confirm_password']) && ($billing_data['customer_password'] == $billing_data['confirm_password'])){
    $password = $billing_data['customer_password'];
    $this->getQuote()->setCheckoutMethod('register');
    $this->getQuote()->setCustomerId(null);
    $this->getQuote()->getCustomer()->setData('password', $password);
    $this->getQuote()->setData('password_hash', Mage::getModel('customer/customer')->encryptPassword($password));
    }
    }
    }

    if($this->_isLoggedIn() || $registration_mode == 'require_registration' || $registration_mode == 'auto_generate_account' || (!empty($billing_data['customer_password']) && !empty($billing_data['confirm_password']))){
    //handle this as Magento handles subscriptions for registered users (no confirmation ever)
    $subscribe_newsletter = $this->getRequest()->getPost('subscribe_newsletter');
    if(!empty($subscribe_newsletter)){
    $this->subscribes = true;
    }
    }

    $billingAddressId = $this->getRequest()->getPost('billing_address_id');
    $customerAddressId = (!empty($billingAddressId)) ? $billingAddressId : false ;

    $shippingAddressId = $this->getRequest()->getPost('shipping_address_id', false);

    if($this->_isLoggedIn()){
    $this->getQuote()->getBillingAddress()->setSaveInAddressBook(empty($billing_data['save_in_address_book']) ? 0 : 1);
    $this->getQuote()->getShippingAddress()->setSaveInAddressBook(empty($shipping_data['save_in_address_book']) ? 0 : 1);
    }

    if($this->differentShippingAvailable()) {
    if(!isset($billing_data['use_for_shipping']) || $billing_data['use_for_shipping'] != '1') {
    //$shipping_result = $this->getOnepage()->saveShipping($shipping_data, $shippingAddressId);
    $shipping_result = Mage::helper('onestepcheckout/checkout')->saveShipping($shipping_data, $shippingAddressId);

    if(isset($shipping_result['error'])) {
    $this->formErrors['shipping_error'] = true;
    $this->formErrors['shipping_errors'] = $checkoutHelper->_getAddressError($shipping_result, $shipping_data, 'shipping');
    }
    }
    else {
    //$shipping_result = $this->getOnepage()->saveShipping($billing_data, $shippingAddressId);
    $shipping_result = Mage::helper('onestepcheckout/checkout')->saveShipping($billing_data, $customerAddressId);
    }
    }

    $result = $this->getOnepage()->saveBilling($billing_data, $customerAddressId);

    $customerSession = Mage::getSingleton('customer/session');

    if (!empty($billing_data['dob']) && !$customerSession->isLoggedIn()) {
    $dob = Mage::app()->getLocale()->date($billing_data['dob'], null, null, false)->toString('yyyy-MM-dd');
    $this->getQuote()->setCustomerDob($dob);
    $this->getQuote()->setDob($dob);
    $this->getQuote()->getBillingAddress()->setDob($dob);
    }

    if($customerSession->isLoggedIn() && !empty($billing_data['dob'])){
    $dob = Mage::app()->getLocale()->date($billing_data['dob'], null, null, false)->toString('yyyy-MM-dd');
    $customerSession->getCustomer()
    ->setId($customerSession->getId())
    ->setWebsiteId($customerSession->getCustomer()->getWebsiteId())
    ->setEmail($customerSession->getCustomer()->getEmail())
    ->setDob($dob)
    ->save();
    }

    // set customer tax/vat number for further usage
    $taxid = '';
    if(!empty($billing_data['taxvat'])){
    $taxid = $billing_data['taxvat'];
    } else if(!empty($billing_data['vat_id'])){
    $taxid = $billing_data['vat_id'];
    }

    if (!empty($taxid)) {
    $this->getQuote()->setCustomerTaxvat($taxid);
    $this->getQuote()->setTaxvat($taxid);
    $this->getQuote()->getBillingAddress()->setTaxvat($taxid);
    $this->getQuote()->getBillingAddress()->setTaxId($taxid);
    $this->getQuote()->getBillingAddress()->setVatId($taxid);
    }

    if($customerSession->isLoggedIn() && !empty($billing_data['taxvat'])){
    $customerSession->getCustomer()
    ->setTaxId($billing_data['taxvat'])
    ->setTaxvat($billing_data['taxvat'])
    ->setVatId($billing_data['taxvat'])
    ->save();
    }

    if(!empty($billing_data['customer_password']) && !empty($billing_data['confirm_password'])) {
    // Trick to allow saving of
    $this->getOnepage()->saveCheckoutMethod('register');
    $this->getQuote()->setCustomerId(null);
    $this->getQuote()->getCustomer()
    ->setId(null)
    ->setCustomerGroupId(Mage::helper('customer')->getDefaultCustomerGroupId($this->getQuote()->getStore()));
    $customerData = '';
    $tmpBilling = $billing_data;

    if(!empty($tmpBilling['street']) && is_array($tmpBilling['street'])){
    $tmpBilling ['street'] = '';
    }

    $tmpBData = array();
    foreach($this->getQuote()->getBillingAddress()->implodeStreetAddress()->getData() as $k=>$v){
    if(!empty($v) && !is_array($v)){
    $tmpBData[$k]=$v;
    }
    }

    $customerData= array_intersect($tmpBilling, $tmpBData);

    if(!empty($customerData)){
    $this->getQuote()->getCustomer()->addData($customerData);
    foreach($customerData as $key => $value){
    $this->getQuote()->setData('customer_'.$key, $value);
    }
    }
    }

    if(isset($result['error'])) {
    $this->formErrors['billing_error'] = true;
    $this->formErrors['billing_errors'] = $checkoutHelper->_getAddressError($result, $billing_data);
    $this->log[] = 'Error saving billing details: ' . implode(', ', $this->formErrors['billing_errors']);
    }

    // Validate stuff that saveBilling doesn't handle
    if (! $this->_isLoggedIn()) {
    $validator = new Zend_Validate_EmailAddress();
    if (! $billing_data['email'] || $billing_data['email'] == '' || ! $validator->isValid($billing_data['email'])) {
    if (is_array($this->formErrors['billing_errors'])) {
    $this->formErrors['billing_errors'][] = 'email';
    } else {
    $this->formErrors['billing_errors'] = array(
    'email'
    );
    }

    $this->formErrors['billing_error'] = true;
    } else {
    $allow_guest_create_account_validation = false;

    if ($this->settings['registration_mode'] == 'allow_guest') {
    if (isset($getCreateAccount) && $getCreateAccount == '1') {
    $allow_guest_create_account_validation = true;
    }
    }

    if ($this->settings['registration_mode'] == 'require_registration' || $this->settings['registration_mode'] == 'auto_generate_account' || $allow_guest_create_account_validation) {
    if ($this->_customerEmailExists(
    $billing_data['email'], Mage::app()->getWebsite()
    ->getId()
    )) {
    $allow_without_password = $this->settings['registration_order_without_password'];

    if (! $allow_without_password) {
    if (is_array($this->formErrors['billing_errors'])) {
    $this->formErrors['billing_errors'][] = 'email';
    $this->formErrors['billing_errors'][] = 'email_registered';
    } else {
    $this->formErrors['billing_errors'] = array(
    'email',
    'email_registered'
    );
    }
    } else {
    }
    } else {
    $password_errors = array();

    if (! isset($billing_data['customer_password']) || $billing_data['customer_password'] == '') {
    $password_errors[] = 'password';
    }

    if (! isset($billing_data['confirm_password']) || $billing_data['confirm_password'] == '') {
    $password_errors[] = 'confirm_password';
    } else {
    if ($billing_data['confirm_password'] !== $billing_data['customer_password']) {
    $password_errors[] = 'password';
    $password_errors[] = 'confirm_password';
    }
    }

    if (!empty($password_errors)) {
    if (is_array($this->formErrors['billing_errors'])) {
    foreach ($password_errors as $error) {
    $this->formErrors['billing_errors'][] = $error;
    }
    } else {
    $this->formErrors['billing_errors'] = $password_errors;
    }
    }
    }
    }
    }
    }

    if($this->settings['enable_terms']) {
    if(!isset($post['accept_terms']) || $post['accept_terms'] != '1') {
    $this->formErrors['terms_error'] = true;
    }
    }

    if ($this->settings['enable_default_terms'] && $requiredAgreements = Mage::helper('checkout')->getRequiredAgreementIds()) {
    $postedAgreements = array_keys($this->getRequest()->getPost('agreement', array()));
    if ($diff = array_diff($requiredAgreements, $postedAgreements)) {
    //$this->formErrors['terms_error'] = $this->__('Please agree to all the terms and conditions before placing the order.');
    $this->formErrors['agreements_error'] = true;
    }
    }

    // Save shipping method
    $shipping_method = $this->getRequest()->getPost('shipping_method', '');

    if(!$this->isVirtual()){
    //additional checks if the rate is indeed available for chosen shippin address
    $availableRates = $this->getAvailableRates($this->getOnepage()->getQuote()->getShippingAddress()->getGroupedAllShippingRates());
    if(empty($shipping_method) || (!empty($availableRates['codes']) && !in_array($shipping_method, $availableRates['codes']))){
    $this->formErrors['shipping_method'] = true;
    } else if (!$this->getOnepage()->getQuote()->getShippingAddress()->getShippingDescription()) {
    if(!empty($availableRates['rates'][$shipping_method])){
    $rate = $availableRates['rates'][$shipping_method];
    $shippingDescription = $rate->getCarrierTitle() . ' - ' . $rate->getMethodTitle();
    $this->getOnepage()->getQuote()->getShippingAddress()->setShippingDescription(trim($shippingDescription, ' -'));
    }
    }
    }

    if(!$this->isVirtual() ) {
    //$result = $this->getOnepage()->saveShippingMethod($shipping_method);
    $result = Mage::helper('onestepcheckout/checkout')->saveShippingMethod($shipping_method);
    if(isset($result['error'])) {
    $this->formErrors['shipping_method'] = true;
    }
    else {
    Mage::dispatchEvent('checkout_controller_onepage_save_shipping_method', array('request'=>$this->getRequest(), 'quote'=>$this->getOnepage()->getQuote()));
    }
    }

    // Save payment method
    $payment = $this->getRequest()->getPost('payment', array());
    $paymentRedirect = false;

    $payment = $this->filterPaymentData($payment);
    $result = array();
    try {
    if(!empty($payment['method']) && $payment['method'] == 'free' && $this->getOnepage()->getQuote()->getGrandTotal() <= 0){
    $instance = Mage::helper('payment')->getMethodInstance('free');
    if ($instance->isAvailable($this->getOnepage()->getQuote())) {
    $instance->setInfoInstance($this->getOnepage()->getQuote()->getPayment());
    $this->getOnepage()->getQuote()->getPayment()->setMethodInstance($instance);
    }
    }

    $result = Mage::helper('onestepcheckout/checkout')->savePayment($payment);
    $paymentRedirect = $this->getOnepage()->getQuote()->getPayment()->getCheckoutRedirectUrl();

    if(defined('Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_BUTTON') && !empty($payment['method']) && $payment['method'] == 'paypal_express' && $this->getOnepage()->getQuote()->getGrandTotal() > 0){
    $urlModel = Mage::getModel('core/url');
    $paymentRedirect = $urlModel->sessionUrlVar($paymentRedirect).'?'.Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_BUTTON.'=0';
    }

    }
    catch (Mage_Payment_Exception $e) {
    if ($e->getFields()) {
    $result['fields'] = $e->getFields();
    }

    $result['error'] = $e->getMessage();
    }
    catch (Exception $e) {
    $result['error'] = $e->getMessage();
    }

    if (isset($result['error'])) {
    if ($result['error'] == 'Can not retrieve payment method instance') {
    $this->formErrors['payment_method'] = true;
    } else {
    $this->formErrors['payment_method_error'] = $result['error'];
    }
    }

    if (! $this->hasFormErrors()) {
    if ($this->settings['enable_newsletter']) {
    // Handle newsletter
    $subscribe_newsletter = $this->getRequest()->getPost('subscribe_newsletter');
    $registration_mode = $this->settings['registration_mode'];
    if (! empty($subscribe_newsletter) && ($registration_mode != 'require_registration' && $registration_mode != 'auto_generate_account') && ! $this->getRequest()->getPost('create_account')) {
    $model = Mage::getModel('newsletter/subscriber');
    $model->loadByEmail($this->email);
    if (! $model->isSubscribed()) {
    $subscribeobj = $model->subscribe($this->email);
    if (is_object($subscribeobj)) {
    $subscribeobj->save();
    }
    }
    }
    }

    if ($paymentRedirect && $paymentRedirect != '') {
    $response = Mage::app()->getResponse();
    // as pointed out by Oriol Augé , no need to render further after redirect
    Mage::app()->getFrontController()->setNoRender(true);
    return $response->setRedirect($paymentRedirect);
    }

    if ($this->_isLoggedIn()) {
    // User is logged in
    // Place order as registered customer

    $this->_saveOrder();
    $this->log[] = 'Saving order as a logged in customer';
    } else {
    if ($this->_isEmailRegistered()) {
    $registration_mode = $this->settings['registration_mode'];
    $allow_without_password = $this->settings['registration_order_without_password'];

    if ($registration_mode == 'require_registration' ||
    $registration_mode == 'auto_generate_account' ||
    $registration_mode == 'registration_success') {
    if ($allow_without_password) {
    // Place order on the emails account without the password
    $this->setCustomerAfterPlace($this->_getCustomer());
    $this->getOnepage()->saveCheckoutMethod('guest');
    $this->_saveOrder();
    } else {
    // This should not happen, because validation should handle it
    $redirect = $this->getUrl('checkout/cart');
    $response = Mage::app()->getResponse();
    Mage::app()->getFrontController()->setNoRender(true);
    return $response->setRedirect($redirect);
    }
    } elseif ($registration_mode == 'allow_guest') {
    $this->setCustomerAfterPlace($this->_getCustomer());
    $this->getOnepage()->saveCheckoutMethod('guest');
    $this->_saveOrder();
    } else {
    $this->getOnepage()->saveCheckoutMethod('guest');
    $this->_saveOrder();
    }

    // Place order as customer with same e-mail address
    $this->log[] = 'Save order on existing account with email address';
    } else {
    if ($this->settings['registration_mode'] == 'require_registration') {
    // Save as register
    $this->log[] = 'Save order as REGISTER';
    $this->getOnepage()->saveCheckoutMethod('register');
    $this->getQuote()->setCustomerId(null);
    $this->_saveOrder();
    } elseif ($this->settings['registration_mode'] == 'allow_guest') {
    if (isset($getCreateAccount) && $getCreateAccount == '1') {
    $this->getOnepage()->saveCheckoutMethod('register');
    $this->getQuote()->setCustomerId(null);
    $this->_saveOrder();
    } else {
    $this->getOnepage()->saveCheckoutMethod('guest');

    //guest checkout is disabled for persistent cart , reset the customer data here as customer data is emulated
    $persistentHelper = Mage::helper('onestepcheckout')->getPersistentHelper();
    if(is_object($persistentHelper)){
    if($persistentHelper->isPersistent()){
    $this->getQuote()->getCustomer()
    ->setId(null)
    ->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
    $this->getQuote()
    ->setCustomerId(null)
    ->setCustomerEmail(null)
    ->setCustomerFirstname(null)
    ->setCustomerMiddlename(null)
    ->setCustomerLastname(null)
    ->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID)
    ->setIsPersistent(false);
    }
    }

    $this->_saveOrder();
    }
    } else {
    $registration_mode = $this->settings['registration_mode'];

    if ($registration_mode == 'auto_generate_account') {
    $this->getOnepage()->saveCheckoutMethod('register');
    $this->getQuote()->setCustomerId(null);
    $this->_saveOrder();
    } else {
    $this->getOnepage()->saveCheckoutMethod('guest');
    $this->_saveOrder();
    }
    }
    }
    }
    }
    }

    protected function setCustomerAfterPlace($customer)
    {
    $this->customer_after_place_order = $customer;
    }

    protected function afterPlaceOrder()
    {
    $customer = $this->customer_after_place_order;

    if($customer || $this->subscribes){
    $order_id = $this->getOnepage()->getLastOrderId();
    $order = Mage::getModel('sales/order')->loadByIncrementId($order_id);
    }

    if($customer) {
    $order
    ->setCustomerId($customer->getId())
    ->setCustomerIsGuest(false)
    ->setCustomerGroupId($customer->getGroupId())
    ->setCustomerEmail($customer->getEmail())
    ->setCustomerFirstname($customer->getFirstname())
    ->setCustomerLastname($customer->getLastname())
    ->setCustomerMiddlename($customer->getMiddlename())
    ->setCustomerPrefix($customer->getPrefix())
    ->setCustomerSuffix($customer->getSuffix())
    ->setCustomerTaxvat($customer->getTaxvat())
    ->setCustomerGender($customer->getGender())
    ->save();
    }

    if($this->subscribes){
    $customerEmail = $order->getCustomerEmail();
    $model = Mage::getModel('newsletter/subscriber');
    $subscribeobj = $model->subscribe($customerEmail);
    if(is_object($subscribeobj)){
    $subscribeobj->save();
    }
    }
    }

    protected function _customerEmailExists($email, $websiteId = null)
    {
    $customer = Mage::getModel('customer/customer');
    if ($websiteId) {
    $customer->setWebsiteId($websiteId);
    }

    $customer->loadByEmail($email);
    if ($customer->getId()) {
    return $customer;
    }

    return false;
    }

    protected function _getCustomer()
    {
    $model = Mage::getModel('customer/customer');
    $model->setWebsiteId(Mage::app()->getStore()->getWebsiteId())->loadByEmail($this->email);

    if($model->getId() == NULL) {
    return false;
    }

    return $model;
    }

    protected function _isEmailRegistered()
    {
    $model = Mage::getModel('customer/customer');
    $model->setWebsiteId(Mage::app()->getStore()->getWebsiteId())->loadByEmail($this->email);

    if($model->getId() == NULL) {
    return false;
    }

    return true;
    }

    public function validateMinimumAmount()
    {
    return $this->getQuote()->validateMinimumAmount();
    }

    public function canCheckout()
    {
    if($this->getQuote()->getItemsSummaryQty() == 0) {
    return false;
    }

    return true;
    }



    protected function _saveOrder()
    {
    // osc checkout helper
    $oscch = Mage::helper('onestepcheckout/checkout');

    // Hack to fix weird Magento payment behaviour
    $payment = $this->getRequest()->getPost('payment', false);
    if($payment) {
    $payment = $this->filterPaymentData($payment);
    $this->getOnepage()->getQuote()->getPayment()->importData($payment);

    $ccSaveAllowedMethods = array('ccsave');
    $method = $this->getOnepage()->getQuote()->getPayment()->getMethodInstance();

    if(in_array($method->getCode(), $ccSaveAllowedMethods)){
    $info = $method->getInfoInstance();
    $info->setCcNumberEnc($info->encrypt($info->getCcNumber()));
    }
    }

    try {
    if(!$this->getOnepage()->getQuote()->isVirtual() && !$this->getOnepage()->getQuote()->getShippingAddress()->getShippingDescription()){
    Mage::throwException(Mage::helper('checkout')->__('Please choose a shipping method'));
    }

    if(!Mage::helper('customer')->isLoggedIn()){
    // checkout.php, _saveOrder() 1
    if ($oscch->isYesSwitch_CollectTotal_CheckoutPhp_SaveOrder1()) {
    $this->getOnepage()->getQuote()->setTotalsCollectedFlag(false)->collectTotals();
    }
    }

    $order = $this->getOnepage()->saveOrder();
    }

    catch(Exception $e) {
    //need to activate
    $this->getOnepage()->getQuote()->setIsActive(true);

    //need to recalculate
    // checkout.php, _saveOrder() 2
    if ($oscch->isYesSwitch_CollectTotal_CheckoutPhp_SaveOrder2()) {
    $this->getOnepage()->getQuote()->getShippingAddress()->setCollectShippingRates(true)->collectTotals();
    }

    $error = $e->getMessage();
    $this->formErrors['unknown_source_error'] = $error;
    Mage::logException($e);
    Mage::helper('checkout')->sendPaymentFailedEmail($this->getOnepage()->getQuote(), $error);
    return;
    //die('Error: ' . $e->getMessage());
    }

    $this->afterPlaceOrder();

    $redirectUrl = $this->getOnepage()->getCheckout()->getRedirectUrl();

    if($redirectUrl) {
    $redirect = $redirectUrl;
    } else {
    $this->getOnepage()->getQuote()->setIsActive(false);
    $this->getOnepage()->getQuote()->save();
    $redirect = $this->getUrl('checkout/onepage/success');
    //$this->_redirect('checkout/onepage/success', array('_secure'=>true));
    }

    $response = Mage::app()->getResponse();
    Mage::app()->getFrontController()->setNoRender(true);
    return $response->setRedirect($redirect);
    }

    /**
    * A fix for common one big form problem
    * we rename the fields in template and iterate over subarrays
    * to see if there's any values and set them to main scope
    * while try to preserve _data keys
    *
    * @param mixed $payment
    * @return mixed
    */
    protected function filterPaymentData($payment)
    {
    if($payment){
    foreach($payment as $key => $value){
    if(!strstr($key, '_data') && is_array($value) && !empty($value)){
    foreach($value as $subkey => $realValue){
    if(!empty($realValue)){
    $payment[$subkey]=$realValue;
    }
    }
    }
    }

    foreach ($payment as $key => $value){
    if(!strstr($key, '_data') && is_array($value)){
    unset($payment[$key]);
    }
    }
    }

    return $payment;
    }

    public function getOnepage()
    {
    return Mage::getSingleton('checkout/type_onepage');
    }

    public function isUseBillingAddressForShipping()
    {
    if (($this->getQuote()->getIsVirtual())
    || !$this->getQuote()->getShippingAddress()->getSameAsBilling()) {
    return false;
    }

    return true;
    }

    public function getCountries()
    {
    return Mage::getResourceModel('directory/country_collection')->loadByStore();
    }

    public function canShip()
    {
    return !$this->getQuote()->isVirtual();
    }

    public function getCountryHtmlSelect($type)
    {
    if($type == 'billing') {
    $address = $this->getQuote()->getBillingAddress();
    /*
    $address = $this->getQuote()->getCustomer()->getPrimaryBillingAddress();
    if (!$this->isCustomerLoggedIn() || $address == null)
    $address = $this->getQuote()->getBillingAddress();
    */
    }
    else {
    $address = $this->getQuote()->getShippingAddress();

    /*
    $address = $this->getQuote()->getCustomer()->getPrimaryShippingAddress();
    if (!$this->isCustomerLoggedIn() || $address == null)
    $address = $this->getQuote()->getShippingAddress();
    */
    }

    $countryId = $address->getCountryId();
    if (is_null($countryId)) {
    $countryId = Mage::getStoreConfig('general/country/default');
    }

    $select = $this->getLayout()->createBlock('core/html_select')
    ->setName($type.'[country_id]')
    ->setId($type.':country_id')
    ->setTitle(Mage::helper('checkout')->__('Country'))
    ->setClass('validate-select')
    ->setValue($countryId)
    ->setOptions($this->getCountryOptions());
    if ($type === 'shipping') {
    $select->setExtraParams('onchange="shipping.setSameAsBilling(false);"');
    }

    return $select->getHtml();
    }

    /**
    * check if e-mail address is subscribed to newsletter
    *
    * @param $email string
    * @return boolean
    */
    public function isSubscribed ($email = null)
    {
    $isSubscribed = false;

    if (! empty($email)) {
    try {
    $result = Mage::getModel('newsletter/subscriber')->loadByEmail(
    $email
    );
    if (is_object($result) && $result->getSubscriberStatus() == 1) {
    $isSubscribed = true;
    }
    } catch (Exception $e) {
    }
    }

    return $isSubscribed;
    }

    // echoes billing and shipping input fields
    function echoAddressFields($htmlArray = array())
    {
    // ordering of fields and "new line after" flags
    $sortOrdering = $this->settings ['sortordering_fields'];

    // compose new array of html fields, ordering and "new line" information
    $composedArray = array ();

    foreach ($htmlArray as $fieldKey => $inputElementHtml ) {
    $positionNr = $sortOrdering [$fieldKey];
    $isNewlineAfter = $sortOrdering [$fieldKey . "_newline_after"];

    // composed array contains arrays of (positionNr, $fieldKey, $inputElementHtml, isNewlineAfter)
    $arrayElem = array (
    "positionNr" => $positionNr,
    "fieldKey" => $fieldKey,
    "inputElementHtml" => $inputElementHtml,
    "isNewlineAfter" => $isNewlineAfter
    );

    $key = $positionNr;
    $composedArray [$key] = $arrayElem;
    }

    // do the sorting by key, i.e. positionNr
    ksort($composedArray);

    return $composedArray;
    } //echoAddressFields

    }
    1,321 changes: 1,321 additions & 0 deletions checkout.phtml
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,1321 @@
    <?php
    /**
    {{COPYRIGHT_NOTICE}}
    */

    $step_counter = 1;
    $helper = Mage::helper('onestepcheckout/checkout');

    ?>
    <?php if(!$this->canCheckout() || !$this->validateMinimumAmount()): ?>
    <?php if($this->settings['checkout_title']): ?>
    <h1 class="onestepcheckout-title"><?php echo $this->settings['checkout_title']; ?></h1>
    <?php endif; ?>

    <?php if($this->canCheckout() && !$this->validateMinimumAmount()): ?>
    <p><?php echo Mage::getStoreConfig('sales/minimum_order/description'); ?></p>
    <p><a href="<?php echo $this->getUrl(''); ?>"><?php echo $this->__('Back to homepage'); ?></a></p>
    <?php else: ?>
    <p><?php echo $this->__('You need to have products in your cart to checkout, and your cart is empty.'); ?></p>
    <p><a href="<?php echo $this->getUrl(''); ?>"><?php echo $this->__('Back to homepage'); ?></a></p>
    <?php endif; ?>
    <?php else: ?>

    <form id="onestepcheckout-form" method="post" action="<?php echo $this->getUrl('onestepcheckout', array('_secure'=>true)); ?>">
    <fieldset class="group-select" style="margin: 0;">

    <?php if($this->settings['checkout_title']): ?>
    <h1 class="onestepcheckout-title"><?php echo $this->settings['checkout_title']; ?></h1>
    <?php endif; ?>

    <?php if($this->settings['checkout_description']): ?>
    <p class="onestepcheckout-description"><?php echo $this->settings['checkout_description']; ?></p>
    <?php endif; ?>

    <?php if(!$this->isCustomerLoggedIn() && $helper->showLoginLink()): ?>
    <p class="onestepcheckout-login-link">
    <a id="onestepcheckout-login-link" href="javascript:;"><?php echo $this->__('Already registered? Click here to login.'); ?></a>
    </p>
    <?php endif; ?>

    <?php if(isset($this->formErrors['unknown_source_error'])): ?>
    <div class="onestepcheckout-error">
    <?php echo $this->formErrors['unknown_source_error']; ?>
    </div>
    <?php endif; ?>
    <div class="onestepcheckout-threecolumns checkoutcontainer onestepcheckout-skin-<?php echo $this->settings['skin']; ?> <?php if(Mage::helper('onestepcheckout')->isEnterprise()): ?>onestepcheckout-enterprise<?php endif; ?>">
    <div class="onestepcheckout-column-left">
    <div class="onestepcheckout-column-padright">
    <div id="billing_address">
    <script type="text/javascript">
    var billing = new Billing();

    </script>
    <ul>
    <li>
    <p class="onestepcheckout-numbers onestepcheckout-numbers-<?php echo $step_counter++; ?>"><span class="numbers-<?php echo $step_counter-1; ?>"></span><?php echo $this->__('Billing address'); ?></p>
    <?php if(isset($this->formErrors['billing_error']) && !empty($this->formErrors['billing_errors'])): ?>
    <div class="onestepcheckout-error">
    <?php echo $this->__('Please check red fields below and try again.'); ?>
    </div>
    <?php endif; ?>
    </li>
    <?php if ($this->customerHasAddresses()): ?>
    <li>
    <label class="addresslabel" for="billing-address-select"><?php echo $this->__('Select a billing address from your address book or enter a new address.') ?></label>
    <div class="input-box">
    <?php echo $this->getAddressesHtmlSelect('billing') ?>
    </div>
    </li>
    <?php endif; ?>
    <li>
    <div>
    <ul id="billing_address_list" <?php echo (($this->customerHasAddresses() && !$this->getNewAddressSelectValueOnError('billing')) ? 'style = "display:none"' : false ); ?>>
    <?php echo $this->getChildHtml('billing_address');?>
    <?php $addressAttributes = $this->getChild('customer_form_billing_address_user_defined_attributes');?>
    <?php if ($addressAttributes): ?>
    <?php $addressAttributes->setEntity($this->getQuote()->getBillingAddress())->setEntityType('customer_address');?>
    <?php $addressAttributes->setFieldIdFormat('billing:%1$s')->setFieldNameFormat('billing[%1$s]');?>
    <?php echo $addressAttributes->setExcludeFileAttributes(true)->setShowContainer(false)->toHtml()?>
    <?php endif;?>
    <?php $customerAttributes = $this->getChild('customer_form_customer_user_defined_attributes');?>
    <?php if ($customerAttributes): ?>
    <?php $customerAttributes->setEntityModelClass('customer/customer')->setFieldIdFormat('billing:%1$s');?>
    <?php $customerAttributes->setFieldNameFormat('billing[%1$s]')->setShowContainer(false);?>
    <?php echo $customerAttributes->setExcludeFileAttributes(true)->toHtml()?>
    <?php endif;?>
    </ul>
    </div>
    </li>
    <li>
    <?php
    $billing_data = $this->getRequest()->getPost('billing', array());
    $uncheck = (!empty($billing_data) && empty($billing_data['use_for_shipping']));?>
    <?php if($this->differentShippingAvailable()): ?>
    <div class="input-box input-different-shipping">
    <input type="checkbox" name="billing[use_for_shipping]" id="billing:use_for_shipping_yes" value="1" <?php echo (($this->sameAsBilling() && !$uncheck) ? 'checked="checked" ':'')?>/><label for="billing:use_for_shipping_yes"><?php echo $this->__('Ship to the same address')?></label>
    </div>
    <?php else: ?>
    <input type="hidden" name="billing[use_for_shipping]" id="billing:use_for_shipping_yes" value="1" />
    <?php endif; ?>
    </li>
    </ul>
    </div>
    <?php if($this->differentShippingAvailable()): ?>
    <div id="shipping_address" <?php echo (($this->sameAsBilling() && !$uncheck) ? 'style="display: none"': false);?>>
    <script type="text/javascript">
    var shipping = new Shipping();
    </script>
    <ul>
    <li class="shipping-address-title">
    <?php echo $this->__('Shipping address'); ?>
    </li>
    <?php if ($this->customerHasAddresses()): ?>
    <li class="form-alt">
    <label class="addresslabel" for="shipping-address-select"><?php echo $this->__('Select a shipping address from your address book or enter a new address.') ?></label>
    <div class="input-box"><?php echo $this->getAddressesHtmlSelect('shipping') ?></div>
    </li>
    <?php endif ?>
    <li id="shipping_address_list" <?php if($this->customerHasAddresses() && !$this->getNewAddressSelectValueOnError('shipping')) { echo ' style="display: none;" '; } ?>>
    <div id="">
    <ul>
    <?php echo $this->getChildHtml('shipping_address');?>
    <?php $addressAttributes = $this->getChild('customer_form_shipping_address_user_defined_attributes');?>
    <?php if ($addressAttributes): ?>
    <?php $addressAttributes->setEntity($this->getQuote()->getShippingAddress())->setEntityType('customer_address');?>
    <?php $addressAttributes->setFieldIdFormat('shipping:%1$s')->setFieldNameFormat('shipping[%1$s]');?>
    <?php echo $addressAttributes->setExcludeFileAttributes(true)->setShowContainer(false)->toHtml()?>
    <?php endif;?>
    </ul>
    <input type="hidden" name="shipping[address_id]" value="<?php echo $this->getQuote()->getShippingAddress()->getId() ?>" id="shipping:address_id" />
    <!-- END LIST OF SHIPPIING FIELDS -->
    </div>
    </li>
    </ul>
    </div>
    <?php endif; ?>
    </div>
    </div>

    <div class="onestepcheckout-column-middle">
    <div class="onestepcheckout-column-padright">
    <?php if(!$this->isVirtual()): ?>
    <?php if(Mage::getStoreConfig('onestepcheckout/general/hide_shipping_method')):?>
    <?php if(isset($this->formErrors['shipping_method']) && $this->formErrors['shipping_method']): ?>
    <div class="onestepcheckout-error onestepcheckout-shipment-method-error">
    <?php echo $this->__('Please choose a shipping method.'); ?>
    </div>
    <?php endif; ?>
    <?php echo $this->getChildHtml('choose-shipping-method'); ?>
    <?php else:?>
    <div class="onestepcheckout-shipping-method">
    <p class="onestepcheckout-numbers onestepcheckout-numbers-<?php echo $step_counter++; ?>"><span class="numbers-<?php echo $step_counter-1; ?>"></span><?php echo $this->__('Shipping method'); ?></p>

    <?php if(isset($this->formErrors['shipping_method']) && $this->formErrors['shipping_method']): ?>
    <div class="onestepcheckout-error onestepcheckout-shipment-method-error">
    <?php echo $this->__('Please choose a shipping method.'); ?>
    </div>
    <?php endif; ?>

    <div class="onestepcheckout-shipping-method-block">
    <?php echo $this->getChildHtml('choose-shipping-method'); ?>
    </div>
    </div>
    <?php endif; ?>
    <?php endif; ?>

    <?php if(Mage::getStoreConfig('onestepcheckout/general/hide_payment_method')):?>
    <?php if(!empty($this->formErrors['payment_method'])): ?>
    <div class="onestepcheckout-error onestepcheckout-payment-method-error">
    <?php echo $this->__('Please choose a payment method.'); ?>
    </div>
    <?php endif; ?>
    <?php if(!empty($this->formErrors['payment_method_error'])): ?>
    <div class="onestepcheckout-error onestepcheckout-payment-method-error">
    <?php echo $this->__('Please enter valid details below.'); ?>
    </div>
    <?php endif; ?>
    <?php echo $this->getChildHtml('choose-payment-method'); ?>
    <?php else: ?>
    <p class="onestepcheckout-numbers onestepcheckout-numbers-<?php echo $step_counter++; ?>"><span class="numbers-<?php echo $step_counter-1; ?>"></span><?php echo $this->__('Payment method'); ?></p>
    <?php if(isset($this->formErrors['payment_method']) && $this->formErrors['payment_method']): ?>
    <div class="onestepcheckout-error onestepcheckout-payment-method-error">
    <?php echo $this->__('Please choose a payment method.'); ?>
    </div>
    <?php else: ?>
    <?php if(isset($this->formErrors['payment_method_error'])): ?>
    <div class="onestepcheckout-error onestepcheckout-payment-method-error">
    <?php echo $this->__('Please enter valid details below.'); ?>
    </div>
    <?php endif; ?>
    <?php endif; ?>
    <div class="tool-tip oscmodal" data-remodal-id="payment-tooltip-modal" id="payment-tool-tip">
    <img src="<?php echo $this->getSkinUrl('images/cvv.gif') ?>" alt="<?php echo $this->__('Card Verification Number Visual Reference') ?>" />
    <button data-remodal-action="close" class="remodal-close"></button>
    </div>
    <script>
    window.paymentToolTip = jQuery('#payment-tool-tip').remodal({'hashTracking': false});
    </script>
    <?php echo $this->getChildHtml('choose-payment-method'); ?>
    <?php endif; ?>
    </div>
    </div>

    <div class="onestepcheckout-column-right">
    <div class="onestepcheckout-column-padleft">
    <p class="onestepcheckout-numbers onestepcheckout-numbers-4"><span class="numbers-4"></span><?php echo $this->__('Review your order'); ?></p>

    <div class="onestepcheckout-summary">
    <?php echo $this->getChildHtml('summary'); ?>
    </div>

    <?php if($this->settings['enable_discount']): ?>
    <div class="onestepcheckout-coupons" id="onestepcheckout-coupons">
    <div id="coupon-notice" style="display: none;"></div>
    <?php $_couponcode = $this->getQuote()->getCouponCode(); ?>
    <div class="input-box input-coupon">
    <label for="id_couponcode"><?php echo $this->__('Coupon code:'); ?></label><br/>
    <input class="input-text" type="text" name="onestepcheckout-couponcode" id="id_couponcode" value="<?php echo Mage::helper('core')->escapeHtml($_couponcode); ?>" />
    </div>
    <div class="button-box">
    <button id="onestepcheckout-coupon-add" class="form-button-alt button" type="button"><span><span><?php echo $this->__('Apply Coupon'); ?></span></span></button>
    <button id="onestepcheckout-coupon-remove" class="form-button-alt button2" type="button" style="<?php if($_couponcode == '') { echo 'display: none;'; } ?>"><span><span><?php echo $this->__('Cancel Coupon'); ?></span></span></button>
    </div>
    <script>
    Event.observe(window, 'load', function() {
    $('onestepcheckout-coupon-add').observe('click', function(e) {

    var coupon = $('id_couponcode').getValue();
    var couponNotice = $('coupon-notice');

    couponNotice.hide();
    couponNotice.up('div').removeClassName('failureo');
    couponNotice.up('div').removeClassName('successo');
    if(coupon == '') {
    alert('<?php echo $this->__('Please enter a valid coupon code.'); ?>');
    return;
    }

    var url = '<?php echo $this->getUrl('onestepcheckout/ajax/add_coupon', array('_secure'=>true)); ?>';
    var parameters = {code: coupon};
    var shipping_methods = $$('dl.shipment-methods').first();
    var payment_methods = $$('div.payment-methods').first();
    var summary = $$('div.onestepcheckout-summary').first();

    if(shipping_methods){
    shipping_methods.update('<div class="loading-ajax">&nbsp;</div>');
    }

    if(payment_methods){
    payment_methods.update('<div class="loading-ajax">&nbsp;</div>');
    }

    summary.update('<div class="loading-ajax">&nbsp;</div>');

    new Ajax.Request(url, {
    method: 'post',
    parameters: parameters,
    onSuccess: function(transport) {
    if(transport.status == 200) {

    var response = transport.responseText.evalJSON();

    var url = '<?php echo $this->getUrl('onestepcheckout/ajax/set_methods_separate', array('_secure'=>true)); ?>';
    var update_payments = <?php echo $this->settings['enable_update_payment_on_shipping'] ? 'true' : 'false'; ?>;

    if(shipping_methods){
    shipping_methods.hide();
    shipping_methods.update(response.shipping_method);
    shipping_methods.show();
    $$('dl.shipment-methods input').invoke('observe', 'click', get_separate_save_methods_function(url, update_payments));
    $$('dl.shipment-methods input').invoke('observe', 'click', function() {
    $$('div.onestepcheckout-shipment-method-error').each(function(item) {
    new Effect.Fade(item);
    });
    });
    }

    if(payment_methods){
    payment_methods.hide();
    payment_methods.replace(response.payment_method);
    payment_methods.show();

    paymentContainer = $('container_payment_method_' + payment.currentMethod);
    paymentForm = $('payment_form_' + payment.currentMethod);

    if(paymentContainer != null){
    paymentContainer.show();
    }
    if(paymentForm != null){
    paymentForm.show();
    }
    $$('div.payment-methods input[name="payment\[method\]"]').invoke('observe', 'click', get_separate_save_methods_function(url));
    $$('div.payment-methods input[name="payment\[method\]"]').invoke('observe', 'click', function() {
    $$('div.onestepcheckout-payment-method-error').each(function(item) {
    new Effect.Fade(item);
    });
    });
    }

    summary.hide();
    summary.update(response.summary);
    summary.show();

    if(response.success) {

    couponNotice.update(response.message);
    couponNotice.removeClassName('error-msg');
    couponNotice.addClassName('success-msg');
    $('onestepcheckout-coupons').addClassName('successo');
    couponNotice.show();
    /* Show remove button */
    $('onestepcheckout-coupon-remove').show();
    }
    else {

    couponNotice.update(response.message);
    couponNotice.removeClassName('success-msg');
    couponNotice.addClassName('error-msg');
    $('onestepcheckout-coupons').addClassName('failureo');
    couponNotice.show();
    /* Hide remove button */
    $('onestepcheckout-coupon-remove').hide();
    }
    }
    },
    onFailure: function(transport) {
    window.location.replace('<?php echo $this->getUrl('checkout/cart/', array('_secure'=>true)); ?>');
    }
    });
    });

    $('onestepcheckout-coupon-remove').observe('click', function(e) {

    var coupon = $('id_couponcode').getValue();
    var couponNotice = $('coupon-notice');

    couponNotice.hide();

    var url = '<?php echo $this->getUrl('onestepcheckout/ajax/add_coupon', array('_secure'=>true)); ?>';
    var parameters = {code: coupon, remove: '1'};
    var shipping_methods = $$('dl.shipment-methods').first();
    var payment_methods = $$('div.payment-methods').first();
    var summary = $$('div.onestepcheckout-summary').first();

    if(shipping_methods){
    shipping_methods.update('<div class="loading-ajax">&nbsp;</div>');
    }

    if(payment_methods){
    payment_methods.update('<div class="loading-ajax">&nbsp;</div>');
    }
    summary.update('<div class="loading-ajax">&nbsp;</div>');

    new Ajax.Request(url, {
    method: 'post',
    parameters: parameters,
    onSuccess: function(transport) {
    if(transport.status == 200) {
    var response = transport.responseText.evalJSON();

    if(response.success){
    $('id_couponcode').setValue('')
    $('onestepcheckout-coupon-remove').hide();
    }

    var url = '<?php echo $this->getUrl('onestepcheckout/ajax/set_methods_separate', array('_secure'=>true)); ?>';
    var update_payments = <?php echo $this->settings['enable_update_payment_on_shipping'] ? 'true' : 'false'; ?>;

    if(shipping_methods){
    shipping_methods.hide();
    shipping_methods.update(response.shipping_method);
    shipping_methods.show();
    $$('dl.shipment-methods input').invoke('observe', 'click', get_separate_save_methods_function(url, update_payments));
    $$('dl.shipment-methods input').invoke('observe', 'click', function() {
    $$('div.onestepcheckout-shipment-method-error').each(function(item) {
    new Effect.Fade(item);
    });
    });
    }

    if(payment_methods){
    payment_methods.hide();
    payment_methods.replace(response.payment_method);
    payment_methods.show();

    paymentContainer = $('container_payment_method_' + payment.currentMethod);
    paymentForm = $('payment_form_' + payment.currentMethod);

    if(paymentContainer != null){
    paymentContainer.show();
    }

    if(paymentForm != null){
    paymentForm.show();
    }
    $$('div.payment-methods input[name="payment\[method\]"]').invoke('observe', 'click', get_separate_save_methods_function(url));
    $$('div.payment-methods input[name="payment\[method\]"]').invoke('observe', 'click', function() {
    $$('div.onestepcheckout-payment-method-error').each(function(item) {
    new Effect.Fade(item);
    });
    });
    }

    summary.hide();
    summary.update(response.summary);
    summary.show();

    couponNotice.hide();
    couponNotice.update(response.message);
    couponNotice.removeClassName('error-msg');
    couponNotice.addClassName('success-msg');
    couponNotice.show();
    }
    },
    onFailure: function(transport) {
    window.location.replace('<?php echo $this->getUrl('checkout/cart/', array('_secure'=>true)); ?>');
    }
    });
    });
    });
    </script>
    </div>
    <?php endif; ?>

    <?php if($this->settings['enable_giftcard']): ?>
    <div class="onestepcheckout-giftcards">
    <div id="giftcard-notice" style="display: none;"></div>
    <?php
    $_hasGiftCards = unserialize($this->getQuote()->getGiftCards());
    $_giftcardcode = $this->getQuote()->getgiftcardCode(); ?>
    <label for="id_giftcardcode"><?php echo $this->__('giftcard code:'); ?></label><br/>
    <input class="input-text" type="text" name="onestepcheckout-giftcardcode" id="id_giftcardcode" value="<?php echo Mage::helper('core')->escapeHtml($_giftcardcode); ?>" />
    <br/>
    <button id="onestepcheckout-giftcard-add" class="form-button-alt button" type="button"><span><span><?php echo $this->__('Apply gift card'); ?></span></span></button>
    <button id="onestepcheckout-giftcard-remove" class="form-button-alt button2" type="button" style="<?php if(empty($_hasGiftCards)) { echo 'display: none;'; } ?>"><span><span><?php echo $this->__('Cancel gift card'); ?></span></span></button>
    <script>
    document.observe('dom:loaded', function() {
    $('onestepcheckout-giftcard-add').observe('click', function(e) {
    var giftcard = $('id_giftcardcode').getValue();
    var giftcardNotice = $('giftcard-notice');
    giftcardNotice.hide();
    if(giftcard == '') {
    alert('<?php echo $this->__('Please enter a valid giftcard code.'); ?>');
    return;
    }

    var url = '<?php echo $this->getUrl('onestepcheckout/ajax/add_giftcard', array('_secure'=>true)); ?>';
    var parameters = {code: giftcard};
    var shipping_methods = $$('dl.shipment-methods').first();
    var payment_methods = $$('div.payment-methods').first();
    var summary = $$('div.onestepcheckout-summary').first();

    if(shipping_methods){
    shipping_methods.update('<div class="loading-ajax">&nbsp;</div>');
    }

    if(payment_methods){
    payment_methods.update('<div class="loading-ajax">&nbsp;</div>');
    }
    summary.update('<div class="loading-ajax">&nbsp;</div>');

    new Ajax.Request(url+Math.random(1000), {
    method: 'post',
    parameters: parameters,
    onSuccess: function(transport) {
    if(transport.status == 200) {

    var response = transport.responseText.evalJSON();

    var url = '<?php echo $this->getUrl('onestepcheckout/ajax/set_methods_separate', array('_secure'=>true)); ?>';
    var update_payments = <?php echo $this->settings['enable_update_payment_on_shipping'] ? 'true' : 'false'; ?>;

    if(shipping_methods){
    shipping_methods.hide();
    shipping_methods.update(response.shipping_method);
    shipping_methods.show();
    $$('dl.shipment-methods input').invoke('observe', 'click', get_separate_save_methods_function(url, update_payments));
    $$('dl.shipment-methods input').invoke('observe', 'click', function() {
    $$('div.onestepcheckout-shipment-method-error').each(function(item) {
    new Effect.Fade(item);
    });
    });
    }

    if(payment_methods){
    //payment_methods.hide();
    payment_methods.replace(response.payment_method);
    //payment_methods.show();

    paymentContainer = $('container_payment_method_' + payment.currentMethod);
    paymentForm = $('payment_form_' + payment.currentMethod);

    if(paymentContainer != null){
    paymentContainer.show();
    }
    if(paymentForm != null){
    paymentForm.show();
    }
    $$('div.payment-methods input[name="payment\[method\]"]').invoke('observe', 'click', get_separate_save_methods_function(url));
    $$('div.payment-methods input[name="payment\[method\]"]').invoke('observe', 'click', function() {
    $$('div.onestepcheckout-payment-method-error').each(function(item) {
    new Effect.Fade(item);
    });
    });
    }

    if(response.success) {
    summary.update(response.summary);
    giftcardNotice.update(response.message);
    giftcardNotice.removeClassName('error-msg');
    giftcardNotice.addClassName('success-msg');
    giftcardNotice.show();
    /* Show remove button */
    $('onestepcheckout-giftcard-remove').show();
    }
    else {
    summary.update(response.summary);
    giftcardNotice.update(response.message);
    giftcardNotice.removeClassName('success-msg');
    giftcardNotice.addClassName('error-msg');
    giftcardNotice.show();
    /* Hide remove button */
    //$('onestepcheckout-giftcard-remove').hide();
    }
    }
    },
    onFailure: function(transport) {
    window.location.replace('<?php echo $this->getUrl('checkout/cart/', array('_secure'=>true)); ?>');
    }
    });
    });

    $('onestepcheckout-giftcard-remove').observe('click', function(e) {
    var giftcard = $('id_giftcardcode').getValue();
    var giftcardNotice = $('giftcard-notice');
    giftcardNotice.hide();
    var url = '<?php echo $this->getUrl('onestepcheckout/ajax/add_giftcard', array('_secure'=>true)); ?>';
    var parameters = {code: giftcard, remove: '1'};
    var shipping_methods = $$('dl.shipment-methods').first();
    var payment_methods = $$('div.payment-methods').first();
    var summary = $$('div.onestepcheckout-summary').first();

    if(shipping_methods){
    shipping_methods.update('<div class="loading-ajax">&nbsp;</div>');
    }

    if(payment_methods){
    payment_methods.update('<div class="loading-ajax">&nbsp;</div>');
    }
    summary.update('<div class="loading-ajax">&nbsp;</div>');

    new Ajax.Request(url, {
    method: 'post',
    parameters: parameters,
    onSuccess: function(transport) {
    if(transport.status == 200) {
    var response = transport.responseText.evalJSON();

    var url = '<?php echo $this->getUrl('onestepcheckout/ajax/set_methods_separate', array('_secure'=>true)); ?>';
    var update_payments = <?php echo $this->settings['enable_update_payment_on_shipping'] ? 'true' : 'false'; ?>;

    if(shipping_methods){
    shipping_methods.hide();
    shipping_methods.update(response.shipping_method);
    shipping_methods.show();
    $$('dl.shipment-methods input').invoke('observe', 'click', get_separate_save_methods_function(url, update_payments));
    $$('dl.shipment-methods input').invoke('observe', 'click', function() {
    $$('div.onestepcheckout-shipment-method-error').each(function(item) {
    new Effect.Fade(item);
    });
    });
    }

    if(payment_methods){
    $$('div.payment-methods input[name="payment\[method\]"]').invoke('observe', 'click', get_separate_save_methods_function(url));
    $$('div.payment-methods input[name="payment\[method\]"]').invoke('observe', 'click', function() {
    $$('div.onestepcheckout-payment-method-error').each(function(item) {
    new Effect.Fade(item);
    });
    });
    payment_methods.hide();
    payment_methods.replace(response.payment_method);
    payment_methods.show();

    paymentContainer = $('container_payment_method_' + payment.currentMethod);
    paymentForm = $('payment_form_' + payment.currentMethod);

    if(paymentContainer != null){
    paymentContainer.show();
    }
    if(paymentForm != null){
    paymentForm.show();
    }
    }

    if(response.success){
    $('id_giftcardcode').setValue('')
    $('onestepcheckout-giftcard-remove').hide();
    }
    var summary = $$('div.onestepcheckout-summary').first();

    summary.hide();
    summary.update(response.summary);
    summary.show();

    giftcardNotice.hide();
    giftcardNotice.update(response.message);
    giftcardNotice.removeClassName('error-msg');
    giftcardNotice.addClassName('success-msg');
    giftcardNotice.show();
    }

    },
    onFailure: function(transport) {
    window.location.replace('<?php echo $this->getUrl('checkout/cart/', array('_secure'=>true)); ?>');
    }
    });
    });
    });
    </script>
    </div>
    <?php endif; ?>

    <?php
    $getComment = $this->getRequest()->getPost('onestepcheckout_comments', false);
    if($this->settings['enable_comments']): ?>
    <div class="onestepcheckout-comments">
    <label for="id_comments"><?php echo $this->__('Comments'); ?></label><br/>
    <textarea id="id_comments" name="onestepcheckout_comments"><?php if(isset($getComment)) { echo Mage::helper('core')->escapeHtml($getComment); } ?></textarea>
    </div>
    <?php endif; ?>

    <?php if($this->settings['enable_gift_messages']): ?>
    <div id="onestepcheckout-giftmessages">
    <div class="onestepcheckout-giftmessagecontainer">
    <?php echo $this->helper('onestepcheckout/message')->getInline('onepage_checkout', $this->getQuote(), $this->getDontDisplayContainer()) ?>
    </div>
    </div>
    <?php endif; ?>

    <?php $customerEmail = (($this->isCustomerLoggedIn())) ? $this->getQuote()->getCustomer()->getEmail() : false ;?>
    <?php if($this->settings['enable_newsletter'] && !$this->isSubScribed($customerEmail)): ?>
    <div class="onestepcheckout-enable-newsletter">
    <input type="checkbox" id="id_subscribe_newsletter" name="subscribe_newsletter" value="1" <?php if($this->settings['newsletter_default_checked']): ?>checked="checked"<?php endif; ?> />
    <label for="id_subscribe_newsletter"><?php echo $this->__('Subscribe to our newsletter'); ?></label>
    </div>
    <?php endif; ?>

    <?php $_extraProductsHelper = Mage::helper('onestepcheckout/extraproducts'); ?>
    <?php if($_extraProductsHelper->hasExtraProducts()): ?>
    <div class="onestepcheckout-extraproducts">
    <ul>
    <?php foreach($_extraProductsHelper->getExtraProducts() as $product): ?>
    <li><input type="checkbox" class="onestepcheckout-extra-product"
    <?php if($_extraProductsHelper->productInCart($product->getId())): ?>
    checked="checked" <?php endif; ?>
    name="extra_products_<?php echo $product->getId(); ?>"
    id="id_extra_product_<?php echo $product->getId(); ?>" />
    <label for="id_extra_product_<?php echo $product->getId(); ?>"> <?php echo $product->getName(); ?>
    <span><?php echo Mage::helper('checkout')->formatPrice($product->getPrice()); ?></span>
    </label></li>
    <?php endforeach; ?>
    </ul>
    </div>

    <script>
    Event.observe(window, 'load', function() {
    $$('input.onestepcheckout-extra-product').invoke('observe', 'click', function(e) {
    var id_temp = e.element().id.split('id_extra_product_');
    if(id_temp.length == 2) {
    var product_id = id_temp[1];
    var url = '<?php echo $this->getUrl('onestepcheckout/ajax/add_extra_product'); ?>';
    var parameters = {
    product_id: product_id
    }

    if(!e.element().checked) {
    parameters['remove'] = 1;
    }

    var summary = $$('div.onestepcheckout-summary').first();
    summary.update('<div class="loading-ajax">&nbsp;</div>');

    new Ajax.Request(url, {
    method: 'post',
    parameters: parameters,
    onSuccess: function(transport) {
    summary.update(transport.responseText);
    },
    onFailure: function(transport) {
    window.location.replace('<?php echo $this->getUrl('checkout/cart/', array('_secure'=>true)); ?>');
    }
    });
    };
    });
    });
    </script>
    <?php endif; ?>

    <?php
    /**
    * Feedbackdropdown start
    */
    ?>
    <?php if(!empty($this->settings['feedback']['enable_feedback']) && !empty($this->settings['feedback']['feedback_values'])):?>
    <?php
    $selectedFeedBackFields = $this->getRequest()->getPost('onestepcheckout-feedback', false);
    $feedbackValues = unserialize($this->settings['feedback']['feedback_values']);
    ?>
    <div class="onestepcheckout-feedback" id="">
    <label for="id_feedback"><?php echo $this->__('How did you hear about us?'); ?></label><br>
    <select style="" name="onestepcheckout-feedback" id="id_feedback" defaultvalue="">
    <option value=""><?php echo $this->__('Please choose'); ?></option>
    <?php foreach($feedbackValues as $value => $label):
    $selected= (!empty($selectedFeedBackFields) && $selectedFeedBackFields == $value) ? ' selected' : '';
    ?>
    <option value="<?php echo $value?>" <?php echo $selected;?>><?php echo $label['value']?></option>
    <?php endforeach;?>
    <?php if(!empty($this->settings['feedback']['enable_feedback_freetext'])):
    $selected= (empty($feedbackValues[$selectedFeedBackFields]) && $selectedFeedBackFields != '') ? ' selected' : '';
    ?>
    <option value="freetext" <?php echo $selected;?>><?php echo $this->__('Other'); ?></option>
    <?php endif;?>
    </select>
    <?php if(!empty($this->settings['feedback']['enable_feedback_freetext'])):?>
    <script type="text/javascript">
    $('id_feedback').observe('change', function (event){
    if(this.getValue() == 'freetext'){
    $('id_feedback_freetext_div').show();
    } else {
    $('id_feedback_freetext_div').hide();
    }
    });
    </script>
    <div id='id_feedback_freetext_div' class="onestepcheckout-feedback-freetext"<?php echo ((!empty($selectedFeedBackFields) && $selectedFeedBackFields == 'freetext') ? '' : ' style="display: none;"'); ?>>
    <label for="id_feedback_freetext"><?php echo $this->__('Please specify:'); ?></label><br/>
    <textarea id="id_feedback_freetext" name="onestepcheckout-feedback-freetext"><?php echo Mage::helper('core')->escapeHtml($this->getRequest()->getPost('onestepcheckout-feedback-freetext', false));?></textarea>
    </div>
    <?php endif; ?>
    </div>
    <?php endif; ?>
    <?php
    /**
    * Feedbackdropdown end
    */
    ?>

    <?php if($this->settings['enable_terms']): //deprecated?>
    <div class="onestepcheckout-enable-terms">
    <?php
    if (isset($this->formErrors['terms_error']) && $this->formErrors['terms_error']) {
    $terms_error = true;
    } else {
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $terms_error = false;
    } else {
    $terms_error = true;
    }
    }
    ?>

    <input class="required-entry" type="checkbox" id="id_accept_terms" name="accept_terms" value="1" <?php if(!$terms_error) echo "checked=\"checked\""; ?> />
    <label for="id_accept_terms"><?php echo $this->__('I accept the <a id="onestepcheckout-toc-link" target="_blank" href="javascript:void(0);">Terms and Conditions</a>'); ?></label>

    <?php if(isset($this->formErrors['terms_error']) && $this->formErrors['terms_error']): ?>
    <div class="onestepcheckout-error onestepcheckout-terms-error">
    <?php echo $this->__('You must accept our terms to continue.'); ?>
    </div>
    <?php endif; ?>

    </div>
    <?php endif; ?>

    <?php
    /**
    * Default magento agreements
    */
    ?>
    <?php if($this->settings['enable_default_terms']): ?>
    <?php if(!empty($this->formErrors['agreements_error'])):?>
    <div class="onestepcheckout-error onestepcheckout-terms-error">
    <?php echo $this->__('Please agree to all the terms and conditions before placing the order.'); ?>
    </div>
    <?php endif;?>
    <?php echo $this->getChildHtml('agreements') ?>
    <script type="text/javascript">

    var termsmodals = new Object;

    document.observe('dom:loaded', function() {
    $$('.osc-checkout-agreements li p input').each(
    function(elem){
    elem.addClassName('required-entry');
    }
    );
    });

    <?php if($this->settings['enable_textarea']):?>
    document.observe('dom:loaded', function() {
    $$('.osc-checkout-agreements li p label').each(
    function(elem){
    elem.up().insert('<a href="javascript:void(0);" onclick="termsmodals[\'' + elem.htmlFor + '\'].open();">' + elem.innerHTML + '</a>');
    elem.hide();
    }
    );
    $$('div.osc-agreement-content').each(
    function(element){
    element.id = 'agreement-div-' + element.up('li').down('input').id;
    element.addClassName('oscmodal');
    element.insert('<button data-remodal-action="close" class="remodal-close"></button>')
    $$('body')[0].insert(element);
    }
    );
    $$('.osc-checkout-agreements li p input').each(
    function(elem){
    window.termsmodals[elem.id] = jQuery('#agreement-div-' + elem.id).remodal();
    }
    );
    });
    <?php endif;?>

    </script>
    <?php endif;?>
    <?php
    /**
    * Default magento agreements end
    */
    ?>

    <div class="onestepcheckout-place-order-wrapper">
    <button type="button" title="<?php echo $this->__('Place order now'); ?>" id="onestepcheckout-place-order" class="button onestepcheckout-button onestepcheckout-place-order" onclick="javascript:void(0);"><span><span><?php echo $this->__('Place order now'); ?></span></span></button>
    </div>
    </div>
    </div>
    <div style="clear: both;">&nbsp;</div>
    </div>
    </fieldset>
    </form>

    <?php if(!$this->isCustomerLoggedIn() && $helper->showLoginLink()): ?>
    <?php echo $this->getChildHtml('login-popup'); ?>
    <?php endif; ?>

    <?php if($helper->isValidateEmail()): ?>
    <script>
    $('billing:email').observe('blur', function(e) {
    var url = '<?php echo $this->getUrl('onestepcheckout/ajax/check_email', array('_secure'=>true)); ?>';
    var email = e.element().getValue();
    var parameters = { email: email };

    new Ajax.Request(url, {
    parameters: parameters,
    onComplete: function(response) {
    if(response.status == 200) {
    var result = response.responseText.evalJSON().result;
    if(result == 'invalid') {
    $('onestepcheckout-email-error-message').update('<?php echo $this->__('Invalid email address.'); ?>');
    $('onestepcheckout-email-error').show();
    }
    else if(result == 'exists') {
    <?php if($this->settings['registration_order_without_password']): ?>
    // Remove the password fields if the email exists in database
    var pwd = $('onestepcheckout-li-password');
    if(pwd){
    pwd.hide();
    }
    <?php endif; ?>
    $('onestepcheckout-email-error-message').update('<?php echo $this->__('Email address already registered. Please <a href="javascript:void(0);" onclick="login_popup.show(); return false;">login now</a> or use a different email address.'); ?>');
    $('onestepcheckout-email-error').show();
    $('id_onestepcheckout_username').value = email;
    }
    else {
    $('onestepcheckout-email-error').hide();
    }
    }
    }
    })

    });
    Validation.add('validate-email', '<?php echo $this->__('This is a required field.') ?>', function(v) {
    var url = '<?php echo $this->getUrl('onestepcheckout/ajax/check_email', array('_secure'=>true)); ?>';
    var email = v;
    var parameters = { email: email };
    var value = Validation.get('IsEmpty').test(v) || /^([a-z0-9,!\#\$%&'\*\+\/=\?\^_`\{\|\}~-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z0-9,!\#\$%&'\*\+\/=\?\^_`\{\|\}~-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*@([a-z0-9-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z0-9-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*\.(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]){2,})$/i.test(v)

    new Ajax.Request(url, {
    parameters: parameters,
    asynchronous: false,
    onComplete: function(response) {
    if(response.status == 200) {
    var result = response.responseText.evalJSON().result;
    if(result == 'invalid') {
    value = false;
    } else if(result == 'exists') {
    <?php if($this->settings['registration_order_without_password']): ?>
    var pwd = $('onestepcheckout-li-password');
    if(pwd){
    pwd.hide();
    }
    <?php endif; ?>
    $('onestepcheckout-email-error-message').update('<?php echo $this->__('Email address already registered. Please <a href="javascript:void(0);" onclick="login_popup.show(); return false;">login now</a> or use a different email address.'); ?>');
    $('onestepcheckout-email-error').show();
    $('id_onestepcheckout_username').value = email;
    value = false;
    }
    }
    }
    })
    return value;
    });
    </script>
    <?php endif; ?>

    <?php if($this->settings['enable_terms']): ?>
    <div id="onestepcheckout-toc-popup" style="display: none;">

    <div class="onestepcheckout-popup-wrapper">
    <div class="onestepcheckout-popup-wrapper-inner">
    <h1><?php echo $this->settings['terms_title']; ?></h1>

    <div class="onestepcheckout-toc-terms">
    <?php echo $this->settings['terms_contents']; ?>
    </div>

    <p class="close"><a href="javascript:void(0);"><?php echo $this->__('Close'); ?></a></p>
    </div>
    </div>
    <div class="onestepcheckout-popup-footer">&nbsp;</div>
    </div>
    <script>
    Event.observe(window, 'load', function() {

    var termsPopupOptions = {
    'modifier': 'oldterms-modal',
    'hashTracking': false};
    var termsPopup = jQuery('#onestepcheckout-toc-popup').remodal(termsPopupOptions);

    $('onestepcheckout-toc-link').observe('click', function(e) {
    e.preventDefault();
    termsPopup.open();
    });

    $$('div#onestepcheckout-toc-popup p.close a').invoke('observe', 'click', function(e) {
    e.preventDefault();
    termsPopup.close();
    });

    });


    </script>
    <?php endif; ?>





    <script>
    <?php if($this->hasFormErrors()): ?>
    if($$('div.input-error').length > 0) {
    var input = $$('div.input-error')[0].select('input');
    if(input.length == 1) {
    input[0].focus();
    }
    }
    <?php endif; ?>
    </script>

    <?php if(!$this->settings['exclude_region']): ?>
    <script type="text/javascript">countryRegions = <?php echo $this->helper('directory')->getRegionJson() ?></script>
    <script type="text/javascript">
    //<![CDATA[
    var bregionid = $("billing:region_id");
    if (bregionid) {
    var billingRegionUpdater = new RegionUpdater('billing:country_id', 'billing:region', 'billing:region_id', countryRegions, undefined, 'billing:postcode');
    }
    <?php if($this->settings['enable_different_shipping'] && !$this->isVirtual()): ?>
    var shregionid = $("shipping:region_id")
    if (shregionid) {
    var shippingRegionUpdater = new RegionUpdater('shipping:country_id', 'shipping:region', 'shipping:region_id', countryRegions, undefined, 'shipping:postcode');
    }
    <?php endif; ?>
    //]]>
    </script>
    <?php endif; ?>


    <script type="text/javascript">

    Event.observe(window, 'load', function() {
    if ($$('div.shopping-cart-totals').length == 1) {
    }
    else {

    already_placing_order = false;
    review = false;
    reviewmodal = false;

    /* Handle place order click event */
    $$('.onestepcheckout-place-order').each(function(elem){
    elem.observe('click', function(e) {
    Event.stop(e);

    // First validate the form
    var form = new VarienForm('onestepcheckout-form');

    // fix for ios safari not focusing on validated inputs
    var userAgent = window.navigator.userAgent;
    if (userAgent && (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i))) {
    form.validator.validate = form.validator.validate.wrap(function(originalMethod) {
    var result = originalMethod();
    if(!result){
    var failedElem = $$('#onestepcheckout-form .validation-failed').first();
    if(failedElem){
    var failedParent = failedElem.up('li');
    if(failedParent){
    failedParent.scrollIntoView();
    } else {
    failedElem.scrollIntoView();
    }
    }
    }
    return result;
    });
    }
    //end fix for ios safari not focusing on validated inputs

    if(!form.validator.validate()) {
    Event.stop(e);
    } else {

    if(!already_placing_order && $$('.loading-ajax').length <= 0 ) {
    <?php if(!empty($helper->settings['addressreview']['enable_addressreview'])):?>
    var addressTemplates = {
    shipping: '<?php echo str_replace("\r", '', str_replace("\n", '', $helper->settings['addressreview']['shipping_template']));?>',
    billing: '<?php echo str_replace("\r", '', str_replace("\n", '', $helper->settings['addressreview']['billing_template']));?>'
    };
    addressPreview(addressTemplates, 'addressreview');
    if(!review){
    review = true;
    if(!reviewmodal){
    reviewmodal = jQuery('#addressreview').remodal();
    }
    reviewmodal.open();
    jQuery(document).on('closing', '#addressreview', function (e) {
    review = false;
    });
    return true;
    Event.stop(e);
    } else {
    reviewmodal.close();
    }
    <?php endif;?>
    already_placing_order = true;

    var submitelement = $('onestepcheckout-place-order');
    /* Disable button to avoid multiple clicks */
    submitelement.removeClassName('orange').addClassName('grey');
    submitelement.disabled = true;

    var loaderelement = new Element('span').
    addClassName('onestepcheckout-place-order-loading').
    update('<?php echo $this->__('Please wait, processing your order...'); ?>');

    submitelement.parentNode.appendChild(loaderelement);

    /* Submit the form */
    $('onestepcheckout-form').submit();
    }
    }
    });
    });


    // This is a separate page
    var url = '<?php echo $this->getUrl('onestepcheckout/ajax/set_methods_separate', array('_secure'=>true)); ?>';
    var update_payments = <?php echo $this->settings['enable_update_payment_on_shipping'] ? 'true' : 'false'; ?>;

    $$('dl.shipment-methods input').invoke('observe', 'click', get_separate_save_methods_function(url, update_payments));
    $$('div.payment-methods input[name="payment\[method\]"]').invoke('observe', 'click', get_separate_save_methods_function(url));

    $$('div.payment-methods input[name="payment\[method\]"]').invoke('observe', 'click', function() {
    $$('div.onestepcheckout-payment-method-error').each(function(item) {
    new Effect.Fade(item);
    });
    });

    $$('dl.shipment-methods input').invoke('observe', 'click', function() {
    $$('div.onestepcheckout-shipment-method-error').each(function(item) {
    new Effect.Fade(item);
    });
    });

    var has_hidden_terms = false;

    if($('id_accept_terms') != null) {

    $('id_accept_terms').observe('click', function(e) {
    var element = e.element();

    if(element.checked) {
    $$('div.onestepcheckout-terms-error').each(function(item) {
    new Effect.Fade(item);
    has_hidden_terms = true;
    });
    }
    else {
    if(has_hidden_terms) {
    $$('div.onestepcheckout-terms-error').each(function(item) {
    new Effect.Appear(item);
    has_hidden_terms = false;
    });
    }
    }
    });
    }
    }

    var form = $('onestepcheckout-form');

    /* Highlight selected payment method if one set */
    if($RF(form, 'payment[method]') != null) {
    try {
    var payment_method = $RF(form, 'payment[method]');
    $('container_payment_method_' + payment_method).show();
    $('payment_form_' + payment_method).show();
    } catch(err) {

    }
    }

    /* Set default shipping method if not set */
    if($RF(form, 'shipping_method') == null) {
    try {
    var method = '<?php echo $this->_getDefaultShippingMethod(); ?>';
    if(method != '') {
    $('s_method_' + method).checked = true;
    get_separate_save_methods_function(url);
    }
    } catch(err) {

    }
    }
    //submit what's available on load
    get_separate_save_methods_function(url)();

    <?php if($this->differentShippingAvailable()): ?>
    $('billing:use_for_shipping_yes').observe('click', function(e) {
    var element = e.element();
    if(element.checked){
    $('shipping_address').hide();
    } else {
    if($('shipping-address-select') && $('shipping-address-select').value == ''){
    $('shipping_address_list').show()
    }
    $('shipping_address').show();
    <?php if(!$this->isCustomerLoggedIn()):?>
    $('shipping_address_list').show()
    <?php endif;?>
    <?php if($this->isCustomerLoggedIn()):?>
    if(!$('shipping-address-select') && $('shipping_address_list').getStyle('display')=='none'){
    $('shipping_address_list').show()
    }
    <?php endif;?>
    }

    <?php if($this->settings['enable_ajax_save_billing']): ?>
    get_save_billing_function('<?php echo $this->getUrl('onestepcheckout/ajax/save_billing', array('_secure'=>true)); ?>', '<?php echo $this->getUrl('onestepcheckout/ajax/set_methods_separate', array('_secure'=>true)); ?>', <?php echo $this->settings['enable_update_payment_on_shipping'] ? 'true' : 'false'; ?>, true)();
    <?php endif; ?>

    });
    <?php endif; ?>
    <?php
    $triggers = Mage::getStoreConfig('onestepcheckout/ajax_update/ajax_save_billing_fields');
    if(!empty($triggers)){
    $triggers = str_replace('country', 'country_id', $triggers);
    $triggers = str_replace('state/region', 'region_id', $triggers);
    $triggers = explode(',',$triggers);
    if(in_array('region_id',$triggers)){
    $triggers[] = 'region';
    }
    }
    ?>

    <?php if(Mage::getStoreConfig('onestepcheckout/ajax_update/enable_ajax_save_billing') && !empty($triggers)):?>

    var url_save_billing = '<?php echo $this->getUrl('onestepcheckout/ajax/save_billing', array('_secure'=>true)); ?>';
    var url_set_methods = '<?php echo $this->getUrl('onestepcheckout/ajax/set_methods_separate', array('_secure'=>true)); ?>';
    var update_payments = <?php echo $this->settings['enable_update_payment_on_shipping'] ? 'true' : 'false'; ?>;
    var update_on_initial = false;

    var euvat = $('euvat_action_validate_taxvat');

    if(euvat !== null){
    euvat.observe('change', get_save_billing_function(url_save_billing, url_set_methods, update_payments, true));
    }

    var euvatid = $('billing:vat_id');

    if(euvatid !== null){
    euvatid.observe('change', get_save_billing_function(url_save_billing, url_set_methods, update_payments, true));
    }

    triggers = ['<?php echo implode ('\',\'',$triggers)?>'];
    btriggered = [];
    striggered = [];

    <?php
    foreach($triggers as $value){
    echo (($this->getQuote()->getBillingAddress()->getData($value)) ? 'btriggered.push(\'billing:'.$value.'\');' : '');
    echo (($this->getQuote()->getShippingAddress()->getData($value)) ? 'striggered.push(\'shipping:'.$value.'\');' : '');
    }
    ?>


    bcountry_id = $('billing:country_id');
    if(bcountry_id){
    if(bcountry_id.getValue()){
    if(!btriggered.include('billing:country_id')){
    btriggered.push('billing:country_id');
    }
    }
    }
    scountry_id = $('shipping:country_id');
    if(scountry_id){
    if(scountry_id.getValue()){
    if(!striggered.include('shipping:country_id')){
    striggered.push('shipping:country_id');
    }
    }
    }

    batriggered = false;
    satriggered = false;

    changeTimer = false;
    changeInterval = 1000;

    triggers.each(function(item){
    var belement = $('billing:'+item);
    if(belement){
    belement.observe('change', function(e){
    var element = e.element();
    var id = element.id;
    var tagname = element.tagName;
    if(tagname === 'SELECT'){
    clearTimeout(changeTimer);
    changeTimer = setTimeout(bcallbackEvent, changeInterval, id);
    } else {
    bcallbackEvent(id);
    }
    });
    }

    var selement = $('shipping:'+item);
    if(selement){
    selement.observe('change', function(e){
    var element = e.element();
    var id = element.id;
    var tagname = element.tagName;
    if(tagname === 'SELECT'){
    clearTimeout(changeTimer);
    changeTimer = setTimeout(scallbackEvent, changeInterval, id);
    } else {
    scallbackEvent(id);
    }
    });
    }
    });

    function scallbackEvent (id){
    if(!striggered.include(id)){
    striggered.push(id);
    }
    if(striggered.length >= triggers.length-1){
    satriggered = true;
    }
    get_save_billing_function(url_save_billing, url_set_methods, update_payments, satriggered)();
    }


    function bcallbackEvent (id){
    if(!btriggered.include(id)){
    btriggered.push(id);
    }
    if(btriggered.length >= triggers.length-1){
    batriggered = true;
    }
    get_save_billing_function(url_save_billing, url_set_methods, update_payments, batriggered)();
    }


    <?php if($this->isCustomerLoggedIn()):?>
    var bselect = $('billing-address-select');
    var sselect = $('shipping-address-select');
    if(bselect){
    bselect.observe('change', get_save_billing_function(url_save_billing, url_set_methods, update_payments, true));
    }
    if(sselect){
    sselect.observe('change', get_save_billing_function(url_save_billing, url_set_methods, update_payments, true));
    }
    <?php endif;?>

    <?php endif; ?>

    });

    </script>


    <?php endif; ?>

    <div id="onestepcheckout_popup_overlay" style="display: none;">&nbsp;</div>


    <div id="loading-process" style="display: none;"></div>
    <script type="text/javascript">
    Translator.add('Are you sure you want to remove this item from the cart?','<?php echo $this->__('Are you sure you want to remove this item from the cart?')?>');
    Translator.add('Your order can not be completed at this time as there is no payment methods available for it.','<?php echo $this->__('Your order can not be completed at this time as there is no payment methods available for it.')?>');
    Translator.add('Please specify payment method.','<?php echo $this->__('Please specify payment method.')?>');
    </script>