$(document).ready(function() {
	//ShopInintCart();
});
function ShopInintCart()
{
	$.ajax({
		url: '/shop/',
		dataType: 'json',
		type: 'POST',
		data: {
			action: 'init_cart'
		},
		success: function(data){
			if (data.status == 'ok')
			{
				$('#cart').html(data.cart_block);
			}
			else if (data.status == 'cart_empty')
				return;
		}
	});
}
function ChangeCountItems(id, type)
{
	var curr_cnt = $('#count_'+ id).val();
	curr_cnt = parseInt(curr_cnt);
	
	if (type == 1)
		curr_cnt++;
	else if (type == 0)
		curr_cnt--;
	
	if (curr_cnt < 0)
		curr_cnt = 0;
	
	$('#count_'+ id).val(curr_cnt);	
	CorrectCountItems(id);
}
function CorrectCountItems(id)
{
	var curr_cnt = $('#count_'+ id).val();
	
	curr_cnt = parseInt(curr_cnt);
	
	if (isNaN(curr_cnt))
		curr_cnt = 0;
	
	$('#count_'+ id).val(curr_cnt);

	return;
}
function AddInCart(id)
{
	var count = $('#count_'+ id).val();
	if (count < 1)
	{
		//$('#message_' + id).html('<span class="err_string">Добавляемое количество меньше одного</span>');
		//return;
		count = 0;
	}
	$('#loader_' + id).show();
	$('#message_' + id).html('');
	
	$.ajax({
		dataType: 'json',
		url: '/shop/',
		type: 'POST',
		data: {
			action: 'add_in_cart',
			id: id,
			count: count
		},
		success: function(data)	{
			
			$('#loader_' + id).hide();
			
			if (data.status == 'ok')
			{
				$('#count_'+ id).val(count);
				//$('#message_'+ id).html(data.msg);
				$('#in_cart_' + id).html('<a href="/shop/cart/">В корзине</a>');
				$('#cart').html(data.cart);
			}
			else if (data.status == 'error')
			{
				//$('#message_' + id).html('<span class="err_string">'+ data.msg +'</span>');
				alert(data.msg);
				$('#cart').html(data.cart);
			}
		}
	});
}
function DeleteItem(id)
{
	if (!confirm('Вы действительно хотите удалить эту позицию из своей корзины?'))
		return;
	
	$('#RecheckButton').attr('disabled', true);
	$('#CartLoader').show();
	
	$.ajax({
		dataType: 'json',
		url: '/shop/',
		type: 'POST',
		data: {
			action: 'delete_item_from_cart',
			id: id
		},
		success: function(data)	{
			if (data.status == 'ok')
			{
				$('#cart_data').html(data.cart_data);
				$('#cart').html(data.cart);
			}
			else if (data.status == 'error')
			{
				alert('Ошибка удаления товара из корзины.');
			}				
		}
	});
}
function ClearCart()
{
	if (!confirm('Вы действительно хотите очистить свою корзину?'))
		return;
	
	$('#RecheckButton').attr('disabled', true);
	$('#CartLoader').show();
	
	$.ajax({
		dataType: 'json',
		url: '/shop/',
		type: 'POST',
		data: {
			action: 'clear_cart'
		},
		success: function(data)	{
			if (data.status == 'ok')
			{
				$('#cart_data').html(data.cart_data);
				$('#cart').html(data.cart);
				$('#can_order').remove();
			}
		}
	});
}
function RecheckCart()
{
	$('#RecheckButton').attr('disabled', true);
	$('#CartLoader').show();
	
	var options = {
		dataType: 'json',
		url: '/shop/',
		type: 'POST',
		data: {
			action: 'recheck_cart'
		},
		success: function(data)	{
			if (data.status == 'ok')
			{
				$('#cart_data').html(data.cart_data);
				$('#cart').html(data.cart);
				
				if (data.can_order == 1 && $('#can_order').hasClass('err_string'))
				{
					$('#can_order').removeClass('err_string');
					$('#can_order').html('<a href="/shop/cart/order/">Продолжить оформление &raquo;</a>');
				}
				else if (data.can_order == 0 && !$('#can_order').hasClass('err_string'))
				{
					$('#can_order').addClass('err_string');
					$('#can_order').html('Вы не можете сдлеать заказ, т.к. некоторый товар отсутствует на складе.');
				}
			}
		}
	};
	
	$('#cart_form').ajaxSubmit(options);
}
function SendOrder(type)
{
	$('#CartLoader').show();
	
	var options = {
		dataType: 'json',
		url: '/shop/',
		type: 'POST',
		data: {
			action: 'send_order',
			type: type
		},
		success: function(data)	{
			$('#CartLoader').hide();
			if (data.status == 'ok')
			{
				if (type == 'order')
					window.location = '/shop/cart/order/dostavka/';
				else
					window.location = '/shop/cart/order/confirm/';
				
				return true;
			}
			else if (data.status == 'error')
			{
				var msg = '';
				for(var i in data.data) 
				{
					if (!data.data.hasOwnProperty(i)) 
						continue;
						
					$('#'+ i).addClass('err_inp');
					msg+= data.data[i] +"\n";
				}
				alert(msg);
				return false;
			}				
		}
	};
	$('#cart_form').ajaxSubmit(options);
}
function ConfirmOrder()
{
	$('#ReservButton').attr('disabled', true);
	$('#CartLoader').show();
	
	$.ajax({
		url: '/shop/',
		dataType: 'json',
		type: 'POST',
		data: {
			action: 'confirm_order'
		},
		success: function(data){
			if (data.status == 'ok')
			{
				window.location = '/shop/cart/order/done/'+ data.order +'/';
			}
			else if (data.status == 'error')
			{
				alert(data.msg);				
			}
		}
	});	
}
function RatingVote(id, vote)
{
	$.ajax({
		url: '/shop/',
		dataType: 'json',
		type: 'POST',
		data: {
			action: 'add_vote',
			id: id,
			vote: vote
		},
		success: function(data){
			if (data.status == 'ok')
			{
				$('.rating #current_rating').css('width', data.data.width +'px');
				$('.rating #current_my_rating').css('width', data.data.my_width +'px');
				$('.rating_avg').html(data.data.avg);
				$('.rating .rating1, .rating .rating2, .rating .rating3, .rating .rating4, .rating .rating5').remove();
				$('#rating').val(vote);
				alert('Ваш голос учтён. Спасибо за голосование.');
			}
			else if (data.status == 'error')
			{
				alert(data.message);
			}
		}
	});
	
	return false;	
}
function ReportMe(id)
{
	$.ajax({
		url: '/shop/',
		dataType: 'json',
		type: 'POST',
		data: {
			action: 'report_me',
			id: id
		},
		success: function(data){
			if (data.status == 'ok')
			{
				$('#otsut_'+ id).html('<strong>Вы первые узнаете<br />о поступлении этого товара<br />на склад</strong>');
				/*alert('При поступлении товара на склад, мы Вам сообщим.');*/
			}
			else if (data.status == 'error')
			{
				alert(data.message);
			}
		}
	});
}
function RegKupon(id)
{
	var kupon = $('#'+ id).val();
	
	if (kupon == '' || kupon == 'Код купона')
	{
		alert('Введите код купона');
		return;
	}
	
	$('#KuponButton').attr('disabled', true);
	$('#KuponLoader').show();
	
	$.ajax({
		url: '/shop/',
		dataType: 'json',
		type: 'POST',
		data: {
			action: 'activate_kupon',
			kupon: kupon
		},
		success: function(data) 
		{
			$('#KuponButton').attr('disabled', false);
			$('#KuponLoader').hide();
	
			if (data.status == 'ok')
			{
				alert(data.message);
				RecheckCart();
			}
			else if (data.status == 'error')
			{
				alert(data.message);
			}
		}
	});
}
function RegCert(id)
{
	var cert = $('#'+ id).val();
	
	if (cert == '' || cert == 'Код сертификата')
	{
		alert('Введите код сертификата');
		return;
	}
	
	$('#CertButton').attr('disabled', true);
	$('#CertLoader').show();
	
	$.ajax({
		url: '/shop/',
		dataType: 'json',
		type: 'POST',
		data: {
			action: 'activate_cert',
			cert: cert
		},
		success: function(data) 
		{
			$('#CertButton').attr('disabled', false);
			$('#CertLoader').hide();
	
			if (data.status == 'ok')
			{
				alert(data.message);
				RecheckCart();
			}
			else if (data.status == 'error')
			{
				alert(data.message);
			}
		}
	});
}
function ShopInintOrder()
{
	$('#addresses input[type="radio"]').each(function(){
		$(this).click(function(){
			var value = $(this).val();
			if (value == -1)
			{
				$('#other_address').slideDown('fast');
			}
			else
				$('#other_address').slideUp('fast');
		});
	});
}

function number_format(_number, _cfg)
{
	function obj_merge(obj_first, obj_second)
	{
		var obj_return = {};
		for (key in obj_first)
		{
			if (typeof obj_second[key] !== 'undefined') obj_return[key] = obj_second[key];
			else obj_return[key] = obj_first[key];
		}
		return obj_return;
	}
	function thousands_sep(_num, _sep)
	{
		if (_num.length <= 3) return _num;
		var _count = _num.length;
		var _num_parser = '';
		var _count_digits = 0;
		for (var _p = (_count - 1); _p >= 0; _p--)
		{
			var _num_digit = _num.substr(_p, 1);
			if (_count_digits % 3 == 0 && _count_digits != 0 && !isNaN(parseFloat(_num_digit)))
				_num_parser = _sep + _num_parser;
			_num_parser = _num_digit + _num_parser;
			_count_digits++;
		}
		return _num_parser;
	}
	if (typeof _number !== 'number')
	{
		_number = parseFloat(_number);
		if (isNaN(_number)) return false;
	}
	var _cfg_default = {
		before: '', 
		after: '', 
		decimals: 2, 
		dec_point: '.', 
		thousands_sep: ' '
	};
	if (_cfg && typeof _cfg === 'object')
	{
		_cfg = obj_merge(_cfg_default, _cfg);
	}
	else 
		_cfg = _cfg_default;
		
	_number = _number.toFixed(_cfg.decimals);
	
	if(_number.indexOf('.') != -1)
	{
		var _number_arr = _number.split('.');
		var _number = thousands_sep(_number_arr[0], _cfg.thousands_sep) + _cfg.dec_point + _number_arr[1];
	}
	else 
		var _number = thousands_sep(_number, _cfg.thousands_sep);
	return _cfg.before + _number + _cfg.after;
}

