$(document).ready(function(){
    $('.cartIcon, input:submit').css('cursor', 'pointer');
    
    $('.cartBtn').click(function(event){
        event.preventDefault();
        $(this).parent().next().children(".cartIcon").click();
    });
   
    $('.cartIcon').click(function(){
        var itemID = $(this).next("input[name=goodID]").val();
    
        $.ajax({
            type:  "POST",
            url:   "/cart/add/",
            data:  {
                itemID:   itemID,
				async:	1
            },
            cache: false,
            success: function(event)
            {
                if (typeof(GOODS_CNT) == 'undefined')
                    GOODS_CNT = 1;
                else
                    GOODS_CNT++;
                
                //$('#jGrowl').remove();
                $("#jGrowl .jGrowl-notification:last").remove();
                ShowCartInfo();
            }
        });
    });
    
    ShowCartInfo();
	
	$('.showModelsBtn a').click(ShowModels);
	
	$("div.pricesTable div.table").hide();
	$("div.pricesTable h2").click(function(){
		if ($("div.pricesTable div.table").is(":hidden")){
			$("div.pricesTable div.table").slideDown("slow",function(){
				$("div.pricesTable h2 img").attr("src","/images/icons/up.png");
			});
		}
		else{
			$("div.pricesTable div.table").hide();
			$("div.pricesTable h2 img").attr("src","/images/icons/down.png");
		}
	});

});

function ShowModels(event)
{
	event.preventDefault();
	var modelsBlock = $(this).parent().siblings('.hiddenModels');
	$(this).parent().remove();
	modelsBlock.slideDown('slow');
}

function ShowCartInfo()
{
	var location = window.location.href.split("/");
	// 2 раза, потому что путь может быть с последним слешом и без
	if (location.pop() == "cart" || location.pop() == "cart" || location.pop() == "cart")
		return;
    if (typeof(GOODS_CNT) != 'undefined' && GOODS_CNT > 0)
    {
        var text = '<img src="/images/cart.png" /> ' + GOODS_CNT + ' товар';
        var ending = '';
        
        if (GOODS_CNT != 1)
        {
            if (GOODS_CNT <= 4)
                ending = 'а';
            else 
                ending = 'ов';
        }
        
        text += ending;
        text += '<div style="text-align: right; margin-top: -15px;"><a href="/cart/">Оформить заказ</a></div>';
        
        $.jGrowl(text, {
            sticky: true
        });
        
        $('.jGrowl-notification').children('.close').remove();
    }
}

function standartAJAXResponseHandler(data, status)
{
	if (status == 'success')
	{
		if (data.error)
		{
			$.jGrowl(data.error);
			return false;
		}
	}
	else
	{
		$.jGrowl("Ошибка запроса");
		return false;
	}
	return true;
}
