function addToBasket(id, many, basketpath, add_id, added_id) {
    JsHttpRequest.query(
        basketpath + '?action=add2basket',
        {
            "id": id,
            "many": many
        },
        function(result, errors) {
            if (errors) {
                alert(errors);
                return;
            }
            reloadBasketBlock(result['basket']);
            hideLink(add_id, added_id);
            animateItem(id);
        },
        true
    );
}

function inttostr(integer, str1, str2, str3) {
    var last = substr(integer, -1);
    var prelast = substr(integer, -2);
    
    if (last == 0 || (last >= 5 && last <= 9) || prelast >= 11 && prelast <= 14) return str3;
    else if (last >= 2 && last <= 4) return str2;
    else return str1;
}

function number_format( 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);
    }
    if (s.indexOf(dec) === -1 && prec > 1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

function substr( f_string, f_start, f_length ) {
    f_string += '';
 
    if(f_start < 0) {
        f_start += f_string.length;
    }
 
    if(f_length == undefined) {
        f_length = f_string.length;
    } else if(f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }
 
    if(f_length < f_start) {
        f_length = f_start;
    }
 
    return f_string.substring(f_start, f_length);
}

function reloadBasketBlock(basket) {
    /*if (!parseInt(basket['items_count'])) {
        document.getElementById('basket_block').style.display = 'none';
        return false;
    }
    if (document.getElementById('basket_block').style.display != 'block') {
        document.getElementById('basket_block').style.display = 'block';
    }*/
   
    document.getElementById('items').innerHTML = inttostr(parseInt((basket['items_count'] ? basket['items_count'] : '0')), 'товар', 'товара', 'товаров');
    document.getElementById('parents').innerHTML = inttostr(parseInt((basket['parents'] ? basket['parents'] : '0')), 'позиции', 'позициях', 'позициях');
    
    document.getElementById('items_count').innerHTML = (basket['items_count'] ? basket['items_count'] : '0');
    document.getElementById('parents_count').innerHTML = (basket['parents'] ? basket['parents'] : '0');
    document.getElementById('summ').innerHTML = (basket['summ'] ? basket['summ'] : '0');
}

function hideLink(add_id, added_id) {
    if (document.getElementById(add_id)) {
        document.getElementById(add_id).style.display = 'none';
    }
    if (document.getElementById(added_id)) {
        document.getElementById(added_id).style.display = 'block';
    }
}

function animateItem(id) {
    if (document.getElementById('img' + id)) {
        var pos = getElementPosition('img' + id);
        var basket_pos = getElementPosition('basket_icon');
        
        var new_img = document.createElement('IMG');
        new_img.src = $('img' + id).src;
        new_img.width = $('img' + id).width;
        new_img.height = $('img' + id).height;
        new_img.style.display = 'block';
        new_img.style.position = 'absolute';
        new_img.style.top = pos.top + 'px';
        new_img.style.left = pos.left + 'px';
        $('locator').appendChild(new_img);
        
        var p = (new_img.width > 200 ? 1.5 : 2);
        
        var new_width = new_img.width * p;
        var new_height = new_img.height * p;
        
        var left_margin = pos.left + (new_img.width - new_width) / 2;
        var top_margin = pos.top + (new_img.height - new_height) / 2;
        
        Animation.add(new_img, {
            'top': pos.top + 'px',
            'left': pos.left + 'px'
        }).add(new_img, {
            'width': new_img.width + 'px',
            'height': new_img.height + 'px'
        }).add(new_img, {
            'width': new_width + 'px',
            'height': new_height + 'px',
            'left': left_margin + 'px',
            'top': top_margin + 'px'
        }, 200, 'slow').add(new_img, {
            'width': '20',
            'height': '20',
            'opacity': '30',
            'top': basket_pos.top + 'px',
            'left': basket_pos.left + 5 + 'px'
        }, 500, 'slow', function(){
            $('locator').removeChild(new_img);
            animateBasket();
        });
    }
}

function animateBasket() {
    Animation.add(
        'basket_icon', {'width': '20px', 'height': '21px', 'left': '0', 'top': '0'}
    ).add(
        'basket_icon', {'width': '30px', 'height': '31px', 'left': '-5px', 'top': '-5px'}, 200, 'slow'
    ).add(
        'basket_icon', {'width': '20px', 'height': '21px', 'left': '0px', 'top': '0px'}, 200, 'fast'
    );
}

function getElementPosition(elemId) {
    var elem = document.getElementById(elemId);
    
    var w = elem.offsetWidth;
    var h = elem.offsetHeight;
    
    var l = 0;
    var t = 0;
    
    while (elem) {
        l += elem.offsetLeft;
        t += elem.offsetTop;
        elem = elem.offsetParent;
    }
    
    return {"left":l, "top":t, "width": w, "height":h};
}

function dropFromBasket(id, basketpath) {
    if (!confirm('Удалить товар из корзины?')) return false;
    
    JsHttpRequest.query(
        basketpath + '?action=dropFromBasket',
        {
            "id": id
        },
        function(result, errors) {
            if (errors) {
                alert(errors);
                return;
            }
            reloadBasketBlock(result['basket']);
            $('basket_summ').innerHTML = result['basket']['summ'];
            dropLine('tr_' + id);
            if (!parseInt(result['basket']['items_count'])) {
                $('basket_list').style.display = 'none';
                $('basket_empty').style.display = 'block';
            }
        },
        true
    );
    
    return false;
}

function dropLine(id) {
    var tr = $(id);
    tr.parentNode.removeChild(tr);
    
    var iterations = $('basket_table').getElementsByTagName('FONT');
    var j = 1;
    for (var i = 0; i < iterations.length; i++) {
        iterations[i].innerHTML = j;
        j++;
    }
}

function calcMany(id, basketpath, many, price) {
    JsHttpRequest.query(
        basketpath + '?action=add2basket',
        {
            "id": id,
            "many": many
        },
        function(result, errors) {
            if (errors) {
                alert(errors);
                return;
            }
            reloadBasketBlock(result['basket']);
            
            $('summ_' + id).innerHTML = number_format(price * getMany(many), 2, ',', ' ');
            $('basket_summ').innerHTML = result['basket']['summ'];
        },
        true
    );
}

function getMany(many) {
    return many.replace(/[^\d]/gi, '');
}