Cart = new function()
{

  this.init = function()
  {
    $( '.ware-adder' ).click( function () {
        Cart.addWare( this.id.substr( 11 ) );
        return false;
    } )

    $( '.ware-remover' ).click( function () {
        Cart.removeWare( this.id.substr( 13 ) );
        return false;
    } )
    
    $( '.ware-count' ).keyup( function() {
      Cart.recountPrice();
    } )
  }

  this.recountPrice = function()
  {
    waresPriceAll = 0;
    $( '.ware-count' ).each( function( i, countInput ) {
      wareId = countInput.id.substr( 11 )
      warePrice = $( '#ware-price-' + wareId ).val()
      wareCount = countInput.value
      $( '#ware-price-sum-' + wareId ).html( wareCount * warePrice )
      waresPriceAll += wareCount * warePrice;
    } )

    $( '.cart-sum' ).html( 
      waresPriceAll + ' ' + Cart.declOfNum( waresPriceAll, [ 'рубль', 'рубля', 'рублей' ]  )
    )
  }

  this.addWare = function( wareId )
  {
    $.ajax( {
        url: '/~/cart/add/' + wareId,
        success: Cart.addWareSuccess,
        error: Cart.addWareError,
        type: 'POST',
        dataType: 'json',
        cache: false
      }
    )

  }


  this.addWareSuccess = function( data )
  {
    if( data.success )
    {
      html = '';
      html = '<a class="go-to-order" href="/order/">В вашей корзине</a> ' + data.wareCount + ' ' +
        Cart.declOfNum( data.wareCount, ['товар', 'товара', 'товаров'] ) +
        ' на сумму ' + Cart.numberFormat(data.warePriceSum, 0, '', ' ') +
        ' руб. <br /><br />'

      $('.cart-body').html( html )

      if( typeof( np_show_nice_popup ) != "undefined" )
      {
        html = '<p>Товар добавлен в вашу корзину. В вашей корзине ' + data.wareCount + ' ' +
          Cart.declOfNum( data.wareCount, ['товар', 'товара', 'товаров'] ) +
          ' на сумму ' + Cart.numberFormat(data.warePriceSum, 0, '', ' ') +
          ' руб. </p>' +
          '<p><a href="/order/">Оформить заказ</a></p>';

        np_show_nice_popup( html );
      }
    }
    else
    {
      $('#ware-adder-' + data.wareAddedId).html('<span>Ошибка... ' + data.errorMessage + '</span>')
    }     
  }

  this.addWareError = function( response )
  {
    alert(
      'Внутренняя ошибка, товар не добавлен; при повторении этой ошибки' +
        ' обратитесь к администратору ' + response.responseText
    )
  }

  this.removeWare = function( wareId )
  { 
    $.ajax( {
        url: '/~/cart/remove/' + wareId + '/',
        type: 'POST',
        success: Cart.removeWareSuccess,
        error: Cart.removeWareError,
        dataType: 'json',
        cache: false
      }
    )
  }


  this.removeWareSuccess = function( data )
  {  
    if( data.success )
    {    

      if ( !data.wareCount )
      {
        html = '';
        html = 'Корзина пуста<br /><br />'

        $('.cart-body').html( html )
      }
      else
      {
        html = '';
        html = '<a class="go-to-order" href="/order/">В вашей корзине</a> ' + data.wareCount + ' ' +
          Cart.declOfNum( data.wareCount, ['товар', 'товара', 'товаров'] ) +
          ' на сумму ' + Cart.numberFormat(data.warePriceSum, 0, '', ' ') +
          ' руб. <br /><br />'

        $('.cart-body').html( html )
      }
      $( '.ware-container-' + data.wareDeletedId ).remove();

      Cart.recountPrice();
    }
    else
    {
      $( '#ware-remover-' + data.wareDeletedId ).html('<span>Ошибка... ' + data.errorMessage + '</span>')
    }
  }

  this.removeWareError = function ( response )
  {
   alert(
     'Внутренняя ошибка, товар не удалён; при повторении этой ошибки' +
        ' обратитесь к администратору '
    )
  }
 
  this.declOfNum = function ($number, $titles)
  {
    $cases = [2, 0, 1, 1, 1, 2];
    return $titles[ ( $number%100 > 4 && $number % 100 < 20 ) ? 2 : $cases[ $number % 10 < 5 ? $number % 10 : 5 ] ];
  }


  this.numberFormat = function  (number, decimals, dec_point, thousands_sep)
  {
      var n = number, prec = decimals;

      var toFixedFix = function (n,prec) {
          var k = Math.pow(10,prec);
          return (Math.round(n*k)/k).toString();
      };

      n = !isFinite(+n) ? 0 : +n;
      prec = !isFinite(+prec) ? 0 : Math.abs(prec);
      var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
      var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

      var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

      var abs = toFixedFix(Math.abs(n), prec);
      var _, i;

      if (abs >= 1000) {
          _ = abs.split(/\D/);
          i = _[0].length % 3 || 3;

          _[0] = s.slice(0,i + (n < 0)) +
                _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
          s = _.join(dec);
      } else {
          s = s.replace('.', dec);
      }

      var decPos = s.indexOf(dec);
      if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
          s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
      }
      else if (prec >= 1 && decPos === -1) {
          s += dec+new Array(prec).join(0)+'0';
      }
      return s;
  }

}

$( function() { 
  Cart.init()
} )

