//TODO требуется рефакторинг, большую часть вещей отсюда желательно вынести
// В класс для работы с заказами.
/**
 * Класс для работы с корзиной пользователя
 */
function  Basket(count, goods){

    /**
     * Количество товаров
     */
    this.count  =  count;

    /**
     * Товары для заказа
     */
    this.goods  =  goods;

    if(goods){
        this.goods  =  {};


        for(var i in goods){
            this.goods[goods[i]['id']]  =  goods[i];
            this.goods[goods[i]['id']]['count']  =  1;
        }
    }

    /**
     * Текущий вид формы заказа товаров.
     */
    this.currentListType  =  null;

    var _this  =  this;

    /**
     * Суммарная стоимость заказываемых товаров
     *
     *@type Float
     */
    this.sum  =  0;

    $('body').ready(function(){
        $('button.basket').click(function(){
            _this.add(this);
        });

        _this.drowTopBlock();
        _this.drowOrderBlock();
    });
}


/**
 * Добавляем товар в корзину
 */
Basket.prototype.add  =  function(el){

    $(this).attr('disabled', 'disabled').text('Обрабатывается');

    var _this  =  this;
    var  goodId  =  $(el).attr('goodId');

    $.ajax({
        url: '/basket/add/',
        data: {id:goodId},
        type: 'post',
        goodId:goodId,
        success: function(data){
            $('#td-basket-'+goodId).text('в заказе');
            ++_this.count;
            _this.drowTopBlock();
        }
    });
}


/**
 * Отрисовываем блок вверху страницы
 */
Basket.prototype.drowTopBlock  =  function(){
    if(this.count > 0){
        var  countText  =  number2String(this.count, 'товар',
                                                    'товара', 'товаров');

        var  href  =  this.goods === false
            ?  '&nbsp;<a href="/zapros/">Заказать&raquo;</a>'
            :  '';

        $('#basketTop').html('В заказе '+countText+'.'+href);
    }
}


/**
 * Отрисовываем блок заказа
 */
Basket.prototype.drowOrderBlock  =  function(){
    var _this  =  this;
    if(this.goods  ===  false || this.goods == {}){
        $('#simpleList').show();
    }
    else{
        var orderTable  =  $('<table>').addClass('order-list');

        $('<tr>').html('<th>Название</th>\n\
                        <th>Количество</th>\n\
                        <th>Стоимость</th>\n\
                        <th>Суммарно</th>').appendTo(orderTable);

        for(var id in this.goods){
            var good  =  this.goods[id];
            var tr  =  $('<tr>');

            $('<td></td>').text(good['name']).appendTo(tr);

            var countCol  =  $('<td>').appendTo(tr);

            $('<input type="text" />').attr({
                 name:'count['+id+']',
                 goodId:id,
                 cost: good['cost'],
                 size: 3,
                 value: good['count']
             })
              .appendTo(countCol).css('width', '21px').addClass('order-count');

            $('<td>').text(good['cost']).appendTo(tr);
            $('<td>').text(good['cost']).appendTo(tr).attr('id', 'sum'+id);

            this.sum  +=  parseInt(good['cost']);
            $(tr).appendTo(orderTable)
        }

        var sumTr  =  $('<tr>').appendTo(orderTable).get(0);
        var sumText  =  'Итого: '+_this.sum;
        
        $('<td>').attr({'colspan': 4, 'id':'fullSum'}).css({'text-align': 'right', 'font-weight': 'bold'})
            .appendTo(sumTr).text(sumText);
        $(orderTable).appendTo($('#catalogList').show().get(0));

        /**
         *  По нажатию(набору) и измененю(вставкой мышой из буфера обмена)
         *  пересчитываем кол-во товаров в корзине
         */
        $('input.order-count').keyup(function(){
            _this.recalculate(this);
        }).change(function(){
            _this.recalculate(this);
        });

        $('#orderListSwitch')
            .text('Хочу заполнить в свободной форме')
            .css('cursor', 'pointer')
            .click(function(){
                _this.switchListType();
            });
        this.currentListType  =  'catalog';
    }
}


/**
 * Переключаем вид списка товаров
 */
Basket.prototype.switchListType  =  function(){
    if(this.currentListType == 'catalog'){
        $('#catalogList').hide();
        $('#simpleList').show();
        $('#orderListSwitch').text('Хочу указать количество');
        this.currentListType  =  'simple';
    }
    else{
        $('#simpleList').hide();
        $('#catalogList').show();
        $('#orderListSwitch').text('Хочу заполнить в сводной форме');
        this.currentListType  =  'catalog';
    }
}


/**
 * Пересчитываем товары в корзине
 *
 * @param el Input инпут в котором поправили кол-во товара
 */
Basket.prototype.recalculate  =  function(el){
    var count  =  parseInt($(el).attr('value'));
    var good  =  this.goods[$(el).attr('goodId')];

    if(count.toString() == $(el).attr('value')){
        var diff  =  count  -  good['count'];
        this.sum  =  this.sum  +  diff*parseInt(good['cost']);
        good['count']  =  count;
        $('#sum'+good['id']).text(good['count']*parseInt(good['cost']));
        $('#fullSum').text(this.sum);
    }
    else{
        this.sum  =  this.sum  -  good['count']*parseInt(good['cost']);
        good['count']  =  0;
        $('#sum'+good['id']).text('0');
        $('#fullSum').text(this.sum);
    }
}


/**
 * Проверяем можено ли заказать товар(указана хотя бы одна единица товара)
 */
Basket.prototype.canOrder  =  function(){

    var  result  =  false;

    for(var i in this.goods){
        if(this.goods['count'] > 0){
            result  =  true;
            break;
        }
    }

    return  result;
}


/**
 * Данные по товарам в текстовом виде для отправки письма
 */
Basket.prototype.toString  =  function(){

    var str  =  '<table>\n\
                    <tr>\n\
                        <th>Наименование</th>\n\
                        <th>Артикул</th>\n\
                        <th>Количество</th>\n\
                    </tr>';

    for(var i in this.goods){
        var good  =  this.goods[i];

        if(good['count'] > 0){
            str  +=  '<tr>\n\
                        <td>'+good['name']+'</td>\n\
                        <td>'+good['art']+'</td>\n\
                        <td>'+good['count']+'</td>\n\
                      </tr>';
        }
    }

    str += '</table>';
    
    return  str;
}