Cart = new function()
{

  this.initializeOrderWareList = function()
  {
    $( '.order-list .ware-count' ).keyup(
      function()
      {
//        var value = '';
//        value = $( this ).val();

//        value = value.replace( /[\.]/g, ',' );
//        value = value.replace( /[^0-9\,\.]/g, '' );
//        value = value.replace( /[,]+/g, '.' );
//        value = Math.round( value * 10 ) / 10;

//        $( this ).val( value );

        Cart.setWareCount( $( this ).attr( 'rel' ), $( this ).val() );
      }
    );

    $( '.order-list .increase-ware-count' ).click(
      function()
      {
        var count = $( '#ware-count-input-' + $( this ).attr( 'rel' ) ).val();
        count = parseFloat( count ) + 1;
        count = Math.round( count * 10 ) / 10;
        
        $( '#ware-count-input-' + $( this ).attr( 'rel' ) ).val( count );
        $( '#ware-count-input-' + $( this ).attr( 'rel' ) ).keyup();

        return false;
      }
    );

    $( '.order-list .decrease-ware-count' ).click(
      function()
      {
        var count = $( '#ware-count-input-' + $( this ).attr( 'rel' ) ).val();

        if( count > 0 )
        {
          count = parseFloat( count ) - 1;
          count = Math.round( count * 10 ) / 10;
          $( '#ware-count-input-' + $( this ).attr( 'rel' ) ).val( count );
          $( '#ware-count-input-' + $( this ).attr( 'rel' ) ).keyup();
        }
        else
        {
          idf( 'Message.notice', 'Воспользуйтесь кнопкой "удалить" чтобы убрать товар из корзины' );
        }

        return false;
      }
    );

    $( '.removeLink' ).click(
      function()
      {
        Cart.remove( $( this ).attr( 'rel' ) );
        return false;
      }
    );

  }

  this.setWareCountTimeout = {}

  this.setWareCount = function( wareId, count )
  {
    if(
      typeof( this.setWareCountTimeout[ wareId ] ) != 'undefined' &&
      this.setWareCountTimeout[ wareId ] != null
    )
    {
      window.clearTimeout( this.setWareCountTimeout[ wareId ] );
      this.setWareCountTimeout[ wareId ] = null;
    }
    
    this.setWareCountTimeout[ wareId ] = setTimeout(
      'idf( \'RPC.call.CartJson.setWareCount\', ' + wareId + ', ' + count +
        ', Cart.setWareCountSuccess )', 500
    );
  }


  this.setWareCountSuccess = function( result )
  {
    if( result == false )
    {
      idf( 'Message.errorDefault', 'Ошибка изменения количества товара; ' );
      return ;
    }

    Cart.updateCartHtml( result.count, result.amount );
    Cart.updateWareHtml( result.wareId, result.wareCount, result.wareAmount );
  }


  this.add = function( wareId, count )
  {
    if ( !( wareId > 0 ) )
    {
      idf( 'Message.errorDefault', 'Ошибка добавления товара в корзину, ' );
      return false;
    }
    if ( ( count > 0 ) && ( count < 100 ) )
    {
      idf( 'RPC.call.CartJson.addWare', wareId, count, Cart.addSuccess );
    }
    else
    {
      idf( 'Message.notice', 'Введите число, большее нуля' );
    }
  }


  this.addSuccess = function( result )
  {
    if( result == false )
    {
      idf( 'Message.errorDefault', 'Ошибка добавления товара в корзину' );
    }
    
    Cart.updateCartHtml( result.count, result.amount,
      result.cart_html );

    if ( result.current_count == 1)
    {
      idf( 'Message.notice', 'Товар добавлен в корзину' );
    }
    else
    {
      idf( 'Message.notice', 'Товары добавлены в корзину' );
    }
  }


  this.remove = function( wareId )
  {
    idf( 'RPC.call.CartJson.removeWare', wareId, Cart.removeSuccess );
  }


  this.removeSuccess = function( result )
  {
    if( result == false )
    {
      idf( 'Message.errorDefault', 'Ошибка удаления товара из корзины' );
    }

    Cart.updateCartHtml( result.count, result.amount, 
      result.cart_html, result.cart_list_html );

    idf( 'Message.notice', 'Товар удалён из корзины' );
  }


  this.increase = function( wareId )
  {
    idf( 'RPC.call.CartJson.increaseWareCount', wareId, Cart.increaseSuccess );
  }


  this.increaseSuccess = function( result )
  {
    if( result == false )
    {
      idf( 'Message.errorDefault', 'Ошибка увеличения количества товара' );
    }

    Cart.updateCartHtml( result.count, result.amount,
      result.cart_html, result.cart_list_html );

    idf( 'Message.notice', 'Количество товара увеличено' );
  }


  this.decrease = function( wareId )
  {
    idf( 'RPC.call.CartJson.decreaseWareCount', wareId, Cart.decreaseSuccess );
  }


  this.decreaseSuccess = function( result )
  {
    if( result == false )
    {
      idf( 'Message.errorDefault', 'Ошибка уменьшения количества товара' );
    }

    Cart.updateCartHtml( result.count, result.amount,
      result.cart_html, result.cart_list_html );

    idf( 'Message.notice', 'Количество товара уменьшено' );
  }


  this.updateCartHtml = function( count, amount, cart_html, cart_list_html )
  {
    if ( !count )
    {
      count = 0;
    }
    
    $( '.cart_warecount' ).html( 'Товаров: ' + parseInt( count ) );
    $( '.cart_wareamount' ).html( 'На сумму: ' + amount + ' руб.' );
    $( 'div.cart_panel').html( cart_html );
    $( 'div.main_content' ).html( cart_list_html );
    
    cart();

/*
    amount = Cart.number_format( amount, 0, '', ' ' );
    count = Math.round( count );

    $( '.h-basket' ).html(
    '<a href="/order/" title="Перейти к корзине">\n\
        <span class="icon basket"></span>\n\
      </a>\n\
      В вашей корзине <br />\n\
      <a href="/order/" title="Перейти в корзину" class="goods-count">' + count +
          ' ' + Cart.declension( count, [ 'товар', 'товара', 'товаров' ] ) +
          '</a> на сумму <strong>' + amount + ' ' +
          Cart.declension( amount, [ 'рубль', 'рубля', 'рублей' ] ) + '</strong>'
    );
      
    $( '.cart-amount' ).html( amount );*/
  }


  this.updateWareHtml = function( wareId, count, amount )
  {
    amount = Cart.number_format( amount, 0, '', ' ' );
    $( '#ware-count-input-' + wareId ).val( count );
    $( '#ware-amount-' + wareId ).html( amount );
  }


  this.declension = 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] ];
  }

  // phpjs.org

  this.number_format = function (number, decimals, dec_point, thousands_sep)
  {
    number = (number+'').replace(',', '').replace(' ', '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
  }

}

  $(document).ready(function(){
        cart();
        
        window.onresize = function() {
         cart();
        };

  });

  function cart ( )
  {
    var offset = $("li.cart").offset();
    $(".cart_panel").css({top: offset.top + 21,left: offset.left + 11});
  }

  var show = function( result )
        {
            $('#cart').html(result);
            cart();
            $("#panel").css({display:'block'});
        }

