var Catalogue = {
    init : function() {
        $('.advanced-toggle').click(function(){
           $('#advanced div.variation').toggle();

           return false;
        });
        $('.to-basket').click(Catalogue._basketHandle);
        if ($('#basket').length != 0) {
            Catalogue._loadBasketBlock();
        }
    },
    _initBasket : function() {
        $('.remove').click(Catalogue._removeHandle);
    },
    _basketHandle : function() {
        var id = $(this).attr('id').replace('item-', '');
        var button = $(this).hide();
        var loader = $('<div>').addClass('basket-indicator');
        $(this).after(loader);
        $.get('/',{
				mode		: 'front-gateway',
				module		: 'text_market_2',
				controller	: 'api',
				format		: 'json',
				action		: 'add_to_basket',
				id			: id
			},
			function (result) {
                loader.remove();
                button.show();
				if (result.success) {
                    var newButton = $('<a>').text('В корзине').addClass('in-basket').attr('href', '/catalogue/basket/');
                    button.replaceWith(newButton);
                    $('#basket').html(result.content);
                    $('#basket').show();
                    Catalogue._initBasket();
                } else {
                    alert(result.errors[0]);
                }
            }, 'json'
        );
        return false;
    },
    _removeHandle : function (){
        var id = $(this).attr('id').replace('item-', '');
        $.get('/',{
				mode		: 'front-gateway',
				module		: 'text_market_2',
				controller	: 'api',
				format		: 'json',
				action		: 'remove',
                id          : id
			},
			function (result) {
				if (result.success) {
                    $('#basket').html(result.content);
                    Catalogue._initBasket();
                } else {
                    alert(result.error);
                }
            }, 'json'
        );
    },
    _loadBasketBlock : function() {
        $.get('/',{
				mode		: 'front-gateway',
				module		: 'text_market_2',
				controller	: 'api',
				format		: 'json',
				action		: 'get_basket'
			},
			function (result) {
				if (result.success) {
                    $('#basket').html(result.content);
                     Catalogue._initBasket();
                } else {
                    alert(result.error);
                }
            }, 'json'
        );
    }
}


$(document).ready(function(){
	Catalogue.init();
});