/*
  $Id: checkout.js $
  TomatoCart Open Source Shopping Cart Solutions
  http://www.tomatocart.com

  Copyright (c) 2009 Wuxi Elootec Technology Co., Ltd;

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License v2 (1991)
  as published by the Free Software Foundation.
*/

var CnCheckout = new Class({
  Implements: Options,
  
  options: {
    remoteUrl: 'json.php',
    sessionName: 'sid',
    sessionId: null,
    isLoggedOn: false
  },
  
  sendRequest: function(data, fnSuccess) {
    data.module = 'cn_checkout';
    data[this.options.sessionName] = this.options.sessionId;
    
    var loadRequest = new Request({
      url: this.options.remoteUrl,
      data: data,
      onSuccess: fnSuccess.bind(this)
    }).send();
  },
  
  initialize: function(options) {
  	if ($defined($('gift_wrapping'))) {
      $('gift_wrapping').addEvent('click', function(e) {
      	var params = {action: 'save_gift_wrapping'};
      	
        params.gift_wrapping = $('gift_wrapping').checked;
        
        this.sendRequest(params, function(response) {
          var result = JSON.decode(response);
          
          if (result.success == true) {
            $('check_order_information').getElement('div').set('html', result.order_confirmation_form);
          }
        });
    
      }.bind(this));
  	}
  },
  
  iniConfirmOrder: function() {
    $('btnConfirmOrder').addEvent('click', function(e) {
    	var payment_methods = document.getElementsByName("payment_method"); 
      var payment_method = null;
      
      $each(payment_methods, function(method) {
        if (method.type == 'radio') {
          if (method.checked) {
            payment_method = method.value;
          }
        } else if (method.type == 'hidden') {
          payment_method = method.value;
        }
      });
      
      if ( payment_method == null ) {
        alert('请先选择一种支付方式!');
        
        return false;
      } else {
        var params = {};
        
        if ( $defined($('shipping_comments')) ) {
          params.shipping_comments = $('shipping_comments').value;
        }
        
        if ( $defined($('payment_comments')) ) {
          params.payment_comments = $('payment_comments').value;
        }
        
        if ( $defined($('gift_wrapping_comments')) ) {
          params.gift_wrapping_comments = $('gift_wrapping_comments').value;
        }
        
        if ( params.shipping_comments != '' || params.payment_comments != '' || params.gift_wrapping_comments != '' ) {
          this.saveComments(params);
        } else {
          document.forms['checkout_confirmation'].submit();
        }
      }
    }.bind(this));
  },
  
  saveComments: function(params) {
  	params.action = 'save_comments';
    
    this.sendRequest(params, function(response) {
      var result = JSON.decode(response);
      
      if (result.success == true) {
        document.forms['checkout_confirmation'].submit();
      }
    });
  },
  
  iniPaymentMethodInformation: function() {
    //btnRedeemCoupon
    if ($defined($('btnRedeemCoupon'))) {
      $('btnRedeemCoupon').addEvent('click', function(e) {
        this.btnRedeemCouponClick(e);
      }.bind(this)); 
    }
    
    if ($defined($('btnDeleteCoupon'))) {
      $('btnDeleteCoupon').addEvent('click', function(e) {
        this.btnDeleteCouponClick(e);
      }.bind(this)); 
    }
    
    //btnRedeemGiftCertificate
    if ($defined($('btnRedeemGiftCertificate'))) {
      $('btnRedeemGiftCertificate').addEvent('click', function(e) {
        this.btnRedeemGiftCertificateClick();
      }.bind(this)); 
    }
    
    $$('.btnDeleteGiftCertificate').each(function(btn){
      btn.addEvent('click', function(e) {
        this.btnDeleteGiftCertificateClick(btn.getParent().id);
      }.bind(this)); 
    }.bind(this));
  },
  
  iniShippingAddress: function() {
    $('shipping_country').addEvent('change', function(e) {
      this.countryChange('shipping');
    }.bind(this));
    
    //shipping state change
    $('shipping_state').addEvent('change', function(e) {
      this.stateChange('shipping');
    }.bind(this));
    
    //shipping city change
    $('shipping_city').addEvent('change', function(e) {
      this.cityChange('shipping');
    }.bind(this));
    
    //save shipping information
    $('btnSaveShippingInformation').addEvent('click', function(e) {
      this.btnSaveShippingInformationClick();          
    }.bind(this));
  },
  
  iniBillingAddress: function() {
    $('billing_country').addEvent('change', function(e) {
      this.countryChange('billing');
    }.bind(this));
    
    //billing state change
    $('billing_state').addEvent('change', function(e) {
      this.stateChange('billing');
    }.bind(this));
    
    //billing city change
    $('billing_city').addEvent('change', function(e) {
      this.cityChange('billing');
    }.bind(this));
    
    //save billing information
    $('btnSaveBillingInformation').addEvent('click', function(e) {
      this.btnSaveBillingInformationClick();          
    }.bind(this));
  },
  
  btnSaveShippingInformationClick: function() {
    var params = {action: 'save_shipping_address'};
    
    if ( $defined($('shipping_gender1')) ) {
      if ($('shipping_gender1').checked == true) {
        params.shipping_gender = 'm';  
      } else {
        params.shipping_gender = 'f';
      }
    } else {
      params.shipping_gender = '';
    }
    
    params.shipping_firstname = $('shipping_firstname').value;
    params.shipping_lastname = $('shipping_lastname').value;
    params.shipping_company = ($defined($('shipping_company')) ? $('shipping_company').value : '');
    params.shipping_street_address = $('shipping_street_address').value;
    params.shipping_suburb = ($defined($('shipping_suburb')) ? $('shipping_suburb').value : '');
    params.shipping_postcode = ($defined($('shipping_postcode')) ? $('shipping_postcode').value : '');
    params.shipping_city = $('shipping_city').value;
    params.shipping_state = ($defined($('shipping_state')) ? $('shipping_state').value : '');
    params.shipping_country = $('shipping_country').value;
    params.shipping_telephone = ($defined($('shipping_telephone')) ? $('shipping_telephone').value : '');
    params.shipping_fax = ($defined($('shipping_fax')) ? $('shipping_fax').value : '');
    
    this.sendRequest(params, function(response) {
      var result = JSON.decode(response);
      
      if (result.success == true) {
        window.location.href = result.url;
        window.reload();
      } else {
        alert(result.errors.join('\n'));
      }
    });
  },
  
  btnRedeemCouponClick: function(e) {
    var params = {
      action: 'redeem_coupon',
      coupon_redeem_code: $('coupon_redeem_code').value
    };
    
    this.sendRequest(params, function(response) {
      var result = JSON.decode(response);

      if (result.success == true) {
        $('check_payment_method').getElement('div').set('html', result.payment_method_form);
        $('check_order_information').getElement('div').set('html', result.order_confirmation_form);
        
        this.iniPaymentMethodInformation();
      }
    });
  },
  
  btnDeleteCouponClick: function(e) {
    var params = {
      action: 'delete_coupon'
    };
    
    this.sendRequest(params, function(response) {
      var result = JSON.decode(response);
        
      if (result.success == true) {
        $('check_payment_method').getElement('div').set('html', result.payment_method_form);
        $('check_order_information').getElement('div').set('html', result.order_confirmation_form);
        this.iniPaymentMethodInformation();
      }
    });
  },  
   
  btnRedeemGiftCertificateClick: function(e) {
    var params = {
      action: 'redeem_gift_certificate',
      gift_certificate_code: $('gift_certificate_code').value
    };
    
    this.sendRequest(params, function(response) {
      var result = JSON.decode(response);
        
      if (result.success == true) {
        $('check_payment_method').getElement('div').set('html', result.payment_method_form);
        $('check_order_information').getElement('div').set('html', result.order_confirmation_form);
        this.iniPaymentMethodInformation();
      } else {
        alert(result.errors);
      }
    });
  },    
  
  btnDeleteGiftCertificateClick: function(gift_certificate_code, e) {
    var params = {
      action: 'delete_gift_certificate',
      gift_certificate_code: gift_certificate_code
    };

    this.sendRequest(params, function(response) {
      var result = JSON.decode(response);
        
      if (result.success == true) {
        $('check_payment_method').getElement('div').set('html', result.payment_method_form);
        $('check_order_information').getElement('div').set('html', result.order_confirmation_form);
        this.iniPaymentMethodInformation();
      }
    });
  },
  
  countryChange: function(type) {
    country_id = $(type + '_country').value;
    
    if (country_id > 0) {
      var params = {
        action: 'country_change',
        country_id: country_id,
        type: type
      };
    
      this.sendRequest(params, function(response) {
        var result = JSON.decode(response);

        if (result.success == true) {
          $(type + '-state').set('html', result.html);
          this.stateChange(type);
          
          $(type + '_state').addEvent('change', function(e) {
            this.stateChange(type);
          }.bind(this));
        }
      });
    }
  },
  
  stateChange: function(type) {
    state_name = $(type + '_state').value;
    
    var params = {
      action: 'state_change',
      state_name: state_name,
      type: type
    };
  
    this.sendRequest(params, function(response) {
      var result = JSON.decode(response);

      if (result.success == true) {
        $(type + '-city').set('html', result.html);
        this.cityChange(type);
        
        $(type + '_city').addEvent('change', function(e) {
          this.cityChange(type);
        }.bind(this));
      }
    });
  },
  
  cityChange: function(type) {
    city_name = $(type + '_city').value;
    
    var params = {
      action: 'city_change',
      city_name: city_name,
      type: type
    };
  
    this.sendRequest(params, function(response) {
      var result = JSON.decode(response);

      if (result.success == true) {
        $(type + '-suburb').set('html', result.html);
      }
    });
  },

  showNotify: function(image) {
    image.set('src', 'images/ajax-loader.gif');
  },
  
  hideNotify: function(image) {
    image.set('src', 'templates/' + this.options.template + '/images/buttons/languages/' + this.options.languageCode + '/button_continue.gif');
  }
});

function selectRowEffect(form, object) {
  $$('#' + form + ' .moduleRowSelected').each(function(row) {
    row.className = 'moduleRow';
  });

  object.className = 'moduleRowSelected';
}