$(document).ready(function(){
	if($('input.focused:first,textarea.focused:first').length == 1){
		$('input.focused:first,textarea.focused:first').focus();
	}
	
	 $('form.stdForm').submit(function(){
		if(!stdFormCheck(this)) return false;
		b = $(this).find('button.saveButton').attr('disabled', 'disabled');
		
		if($(b).val()) $(b).html($(b).val());
		
		$(this).find('button.loadIndicator').append('...');
	 });		
});

function stdFormCheck(f){
	$(f).find('.needed').removeClass('wrong');
	$(f).find('.needed').each(function(){
		if($(this).val().match(/^\s*$/)) $(this).addClass('wrong');
	});	
	
	if($(f).find('.wrong').length){
		$(f).find('.wrong:first').focus();
		return false;
	}
	
	return true;	
	
}

function addToCart(itemID, colorID){
	if(!itemID)
		itemID = $('#itemID').val();
	if(!colorID)
		colorID = $('#selectedColor').val();
	
	$('#myCart').html('Обновление корзины...');
	
	$.post(AJAXPath + '/add2cart.php', {
		id: itemID, color_id: colorID
	}, function(data){
		$('#myCart').html(data);
	});
}

function removeItem(itemID){
	$('#myCart').html('Обновление корзины...');
	
	$.post(AJAXPath + '/removeItem.php', {
		id: itemID
	}, function(data){
		$('#myCart').html(data);
	});
}

function clearCart(){
	$('#myCart').html('Очистка корзины...');
	
	$.post(AJAXPath + '/removeItem.php', {
		id: 'all'
	}, function(data){
		$('#myCart').html(data);
	});
}


function doVote(f){
	if( $('.voteVariant:checked').length < 1 ){
		return false;
	}
	
	$(f).find('button').attr('disabled', 'disabled').html('Голосуем...');
	
	$.ajax({
		url: AJAXPath + 'vote.php', dataType: 'text', type: 'post', 
		data: $(f).serialize(),
		success: function(data){
			if(data){
				$('#votes .br').html(data);
			}else{
				alert('Произошла ошибка. Попробуйте еще раз');
				$(f).find('input,button').removeAttr('disabled');
			}
		},
		error: function(){
			alert('Произошла ошибка! Попробуйте еще раз');
			$(f).find('input,button').removeAttr('disabled');
		}
	});
	
	$(f).find('input').attr('disabled', 'disabled');
	
	return false;
}

