$(function(){

	function get_count()
	{
		return parseInt($('#nav_links .basket span').text());
	}

	function set_count(count)
	{
		$('#basket_count').html(count + 'шт.');
	}

	function inc_count(i)
	{
		var count = get_count();
		set_count(count+i);
	}
  
	function setBasketBlock()
	{
		$.get(
			'/basket/basketBlock',
			function(response) {
				$('#basket_container').replaceWith(response);        
			}
			);
	}

	function reprocess()
	{
		var count = 0;
		var sum = 0;
		$('.order .count').each(function(){
			var c = parseFloat($('input', this).val());
			var s = parseFloat($(this).next().text()) * parseFloat($('input', this).val());
			if(isNaN(s) == false)
			{
				$(this).nextAll('.price').text(s);
				sum += s;
				count += c;
			}
		});
		/*set_count(count);*/
		setBasketBlock();
		if(sum == 0)
		{
			$('.order .price:last').text('договорная');
		}
		else
		{
			$('.order .price:last').text(sum + ' руб.');
		}
		$('.order tr:has(.count):odd').addClass('dark');
		$('.order tr:has(.count):even').removeClass('dark');
	}

	function initBasketAdd() {
		$('.basket-add').click(function(e){
			e.preventDefault();
			var container = $(this).parent();

            if ($(this).attr('type') == 'off') {
                var types = 0;
            }
            else {
                var types = $('#types_form').serialize();
            }

            $(this).nextAll('.loader').show();
			$.ajax({
				type: "POST",
				url: this.href,
				data: types,
				success: function(response) {
					container.html(response);  
					//initBasketAdd();          
					setBasketBlock();
				}
			});
		});
	}
	initBasketAdd();

	$('.basket-del').click(function(e){
		e.preventDefault();
		var row = $(this).parent().parent();
		$(this).nextAll('.loader').show();
		$(this).hide();
		$.get(
			this.href,
			function(response) {
				row.remove();
				reprocess();
			}
			);
	});

	$('.basket-count').keyup(function(e){
		if(e.which == 8 || e.which == 46 || e.which == 27 || e.which == 32)
		{
			return false;
		}
		
		var count = 1;
		if(isNaN(parseFloat(this.value)) == false)
		{
			count = parseFloat(this.value);
		}
		
		var party_count = 1;
		if($(this).attr('party_count') != undefined)
    {
			party_count = parseFloat($(this).attr('party_count'));
    }
		if(count < party_count)
		{
			this.value = party_count;
			return false;
		}
		
		this.value = Math.round(this.value/party_count)*party_count;
		
		var url = $('#basket-form').attr('action');
		var id = this.id.substr(8);
		$.post(
			url,
			{
				//id:    this.id.substr(8),
				id:        parseInt(id),
				option_id: id.substr(id.indexOf('-') + 1),
				count: this.value
			},
			function(response){
				if (response)
				{
					reprocess();
				}
			}
		);
		
	});

	$('#basket-form').submit(function(e){
		e.preventDefault();
	});

	$('#order-link').click(function(e){
		e.preventDefault();
		$('#photo_show').show();
	});

	$('#photo_show .close-img').click(function(){
		$('#photo_show').hide();
	});

});
