$().ready( function(){
	var basketitems = $('#basket-items').html();
	var basketitems_name = declension( basketitems, new Array ("продукт","продукта","продуктов")  );
	$('#basket-items-word').html(basketitems_name);
	
	
	$(".creditcheck").bind("change", function(){
		update_basket_price();
	})
})

function delete_basket(){
	if(!confirm('Уверены что хотите очистить корзину?')) return false;
	
	window.location = '/catalog/basket.html?clear=1';
}

function submit_basket_doplata(){
	var items = new Array;
	$(".creditcheck-doplata").each( function(){
		var credit_id = $(this).attr('creditid');
		if( $(this).is(":checked") ) items.push(credit_id);
	});
	$("#params").val(items.join(','));	
	document.getElementById('basket-form').submit();
	return true;
}

function submit_basket(){
	
	var items = new Array;
	$("tr.credit").each( function() {
		var tr = $(this);
		var order_id = $(this).attr('orderid');
		items[order_id] = new Array;
		
		$("tr.list-"+order_id).each( function() {
			
			$("input:checked", this).each(function(){
				var val = $(this).val();
				items[order_id].push( val );
			});			
		});
	});

	var params = '';
	for(n in items){
		var arr = items[n];
		params = params ? params + "&"+n+"=" + arr.join(',') : n+"=" + arr.join(',');
	}
	$("#params").val(params);
	
	document.getElementById('basket-form').submit();
	return true;
	
}

function basket_delete_item(button, item_id, confirmtext){
	if(!confirm(confirmtext)) return false;
	
	$.ajax({
	url: "/catalog/deleteitem.html",
	contentType: 'application/json',
	dataType: 'json',
	beforeSend: function(){
			$('#content').css('cursor', 'progress');
			$(button).css('cursor', 'progress');
	},

	success: function(data){
    			$('#content').css('cursor', 'default');
				$(button).css('cursor', 'pointer');

				if(data.error){
					alert(data.error);
				} else{
					if(data.deleted){
						$(button).parents("tr.bask-order").fadeOut().remove();
						$("tr.tr-credit-"+item_id).fadeOut().remove();
						
						update_basket_authblock_items(data.items);
					}
					if(data.updated){
						var count = toInt( $(".count-"+item_id).html() );
						count--;
						$(".count-"+item_id).html(count);
					}
					update_basket_price();
					update_basket_price();
				}
	},
	error: function(data){
    	$('#content').css('cursor', 'default');
		$(button).css('cursor', 'pointer');
		alert('Ошибка удаления товара');
	},
	data: "itemid="+item_id
});
}

function update_basket_authblock_items(items){
	var name = declension( items, new Array ("продукт","продукта","продуктов")  );
	$('#basket-items-word').html(name);
	$('#basket-items').html(items);
}

function update_basket_price(){
	
	$("tr.credit").each( function() {
		
		var tr = $(this);
		var order_id = $(this).attr('orderid');
		var order_price = toInt( $("#k_oplate-firstpayd-"+order_id).attr('price') );
		// UPDAT FIRST CREDIT PRICE
		var count = toInt( $(".count-"+order_id).html() );
		var firstprice =  toInt( $(".credit-month-price-"+order_id).attr('price') );
		var firstnewprice = count * firstprice;
		$("#k_oplate-firstpayd-"+order_id).attr('price', firstnewprice);
		$("#k_oplate-firstpayd-"+order_id).html( firstnewprice );
		
		$("tr.list-"+order_id).each( function() {
			// 
			var count = toInt( $(".count-"+order_id, this).html() );
			var monthprice = toInt( $(".credit-month-price-"+order_id, this).attr('price') );
			var new_price = count * monthprice;
			$(".credit-price", this).attr('price', new_price);
			$(".credit-price", this).html( new_price );
			
			if( $("input.creditcheck", this).is(":checked") ){
				var credit_id = $("input.creditcheck", this).attr('creditid');
				order_price += toInt( $("#k_oplate-credit-"+credit_id).attr('price') );
			}
		});
		$("#k_oplate-order-"+order_id).attr('price', order_price);
		
		$("#k_oplate-order-"+order_id).html ( order_price );

	});

	$("tr.bask-nocredit").each( function() {
		var count = toInt( $(".count", this).html() );
		var price = toInt( $(".order-price", this).attr('price') );
		var total = count * price;
		$(".k_oplate", this).attr('price', total);
		$(".k_oplate", this).html( total );
	});

	var totalprice = 0;
	$("tr.bask-order").each( function() {
		var tr = $(this);
		var price = $("em.k_oplate", tr).attr('price');
		totalprice += toInt( price );
	});
	$("#result-price").attr('price', totalprice);
	
	var totalprice_formated = priceFormat(totalprice);
	$("#result-price").html( totalprice_formated + " руб.");

	$(".numberformat").each(function(){
		var val = toInt( $(this).attr('price') ) ;
		if(val){
			$(this).html( priceFormat(val) );
		}
	});
}

function priceFormat( order_price ){
	$("#priceformat").val(order_price);
	$("#priceformat").priceFormat({prefix: '',centsSeparator: '',thousandsSeparator: ' ', centsLimit: 0});
	return $("#priceformat").val();
}

function toInt(x){
    return (parseInt(x) + 0);
}


function addItem(button, item_id, auth){
	if(auth==0){
		alert('Для добавление товара в корзину необходимо авторизоваться');
		return false;
	}
	$.ajax({
		url: "/catalog/additem.html",
  		contentType: 'application/json',
  		dataType: 'json',
  		beforeSend: function(){
    			$('#content').css('cursor', 'progress');
				$(button).css('cursor', 'progress');
		},

   		success: function(data){
	    			$('#content').css('cursor', 'default');
					$(button).css('cursor', 'pointer');

					if(data.error){
						alert(data.error);
					} else{
						update_basket_authblock_items(data.items);
					}
		},
   		error: function(data){
	    	$('#content').css('cursor', 'default');
			$(button).css('cursor', 'pointer');
   			alert('Ошибка добавления товара в корзину');
   		},
   		data: "itemid="+item_id
	});
}

function declension(num, expressions) {
    var result;
    count = num % 100;
    if (count >= 5 && count <= 20) {
        result = expressions['2'];
    } else {
        count = count % 10;
        if (count == 1) {
            result = expressions['0'];
        } else if (count >= 2 && count <= 4) {
            result = expressions['1'];
        } else {
            result = expressions['2'];
        }
    }
    return result;
}

