/**
 * Championship Manager Shop - JavaScript Library
 * jQuery Cart plugin
 *
 * @date 2009-08-26
 * @version 1.0
 * @copyright Eidos Interactive Ltd 2009
 */

(function ($) {
  /**
   *
   */
  $.fn.cart = {
    _params: {
      'classNamePwyw': 'cart-pwyw-value',
      'classNameTotal': 'cart-total-value',
      'cname': 'pwyw',
      'couponId': 'form-cm-game-seasonlive'
    },
    _globals: {
      'total': 0,
      'pwyw': 0,
      'coupon': '',
    },
    initialize: function() {
      var plugin_cart = this; // Reference to plugin;
      // Original PWYW value
      this._globals.pwyw = $('.'+this._params.classNamePwyw).attr('value');
      // Store original total value
      this._globals.total = $('.'+this._params.classNameTotal+' > input').attr('value');
      // Store original coupon value if exists
      this._globals.coupon = $('#'+this._params.couponId+' > input#coupon').attr('value');
      
      // Add coupon behaviour if coupon present on page
      if (this._globals.coupon) {
        $('#'+this._params.couponId).bind('submit', function() { 
          var result = plugin_cart.checkCoupon();
          
          return result;
        });
      }
      
      if (typeof(this._globals.pwyw) === 'undefined') {
        // no PWYW item in Cart -> init PWYW bid
        this.setPwyw(null);
        return;
      }
      
      // check that PWYW has not already been submitted
      if (parseInt(this._globals.pwyw) > 0) {
        // PWYW was submitted
        if (this.formatFloat(this.getPwyw()) !== this.formatFloat(this._globals.pwyw)) {
          // page was refreshed (manual refresh, or new item added to cart)
          //  -> remove original PWYW bid from total
          this._globals.total = this._globals.total - this._globals.pwyw;
          $('.'+this._params.classNameTotal+' > input').attr('value', this._globals.total);
          //  -> reset PWYW bid with cookie value
          this._globals.pwyw = this.getPwyw();
          $('.'+this._params.classNamePwyw).attr('value', this.formatFloat(this.getPwyw()));
        } else {
          // coming from other page
          //  -> remove PWYW from total, as it is already counted in
          this._globals.total -= this._globals.pwyw;
        }
      } else {
        // PWYW either not submitted, or unset
        //  -> use cookie value
        this._globals.pwyw = this.getPwyw();
        $('.'+this._params.classNamePwyw).attr('value', this.formatFloat(this.getPwyw()));
      }
      
      // reset total
      this.setTotal();
      
      // bind onKeyUp events
      $('.'+this._params.classNamePwyw).bind('keyup', function(e) {
        plugin_cart.setPwyw(this.value);
        plugin_cart.setTotal();
      });
    },
    
    setPwyw: function(v) {
      // store the raw value in cookie
      var exdate = new Date();
      exdate.setDate(exdate.getDate()+1);
      document.cookie = this._params.cname+ "=" +escape(v)
        + ";domain="+document.domain
        + ";expires="+exdate.toGMTString()
        + ";path=/";
      // store value in session for later use
      $.get('/cart/addpwyw/?pwyw='+v);
    },
    
    getPwyw: function() {
      var pwyw = 0;
      if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(this._params.cname + "=");
        if (c_start != -1) {
          c_start = c_start + this._params.cname.length + 1;
          c_end = document.cookie.indexOf(";",c_start);
          if (c_end == -1) c_end = document.cookie.length;
          pwyw = unescape(document.cookie.substring(c_start,c_end));
          pwyw = parseFloat(pwyw);
          if (isNaN(pwyw)) { return 0; }
        }
      }
      return pwyw;
    },
    
    setTotal: function() {
      // Total = original total (fee + penny) + PWYW bid
      var newTotal = this.formatFloat(parseFloat(this._globals.total) + this.getPwyw());
      $('.'+this._params.classNameTotal+' > input').attr('value', newTotal);
    },
    
    formatFloat: function(f) {
      var fl = Math.round(100*(f)) / 100;
      fl = fl.toString();
      if (fl.indexOf('.') == -1) {
        fl += '.00';
      }
      return fl;
    },
    
    // Coupon methods
    checkCoupon: function() {
      var c_value = $('#'+this._params.couponId+' > input#coupon').attr('value');
      if (c_value == this._globals.coupon) {
        // no coupon entered -> continue
        return true;
      } else {
        var caller = this;
        $.get('/shop/checkcoupon/?coupon='+c_value, false, function(data, textStatus) { 
          if (textStatus === 'success') {
            if (caller.isNumeric(data)) {
              // The code is valid
              // unbind form
              $('#'+caller._params.couponId).unbind('submit');
              // submit form
              $('#'+caller._params.couponId).submit();
            } else {
              // The code is NOT valid
              // alert error message
              alert(data);
            }
          }
        });
        return false;
      }
    },
    
    isNumeric: function(s) {
      var validChars = "0123456789.";
      var isNumber = true;
      var char;
      for (i = 0; i < s.length && isNumber == true; i++) { 
        char = s.charAt(i);
        if (validChars.indexOf(char) == -1) {
          isNumber = false;
        }
      }
      return isNumber;
    },
    
    trace: function(t) {
      $('#debug').html($('#debug').html() + '<br />' + t);
    }
  };

})(jQuery);