$(function(){
	if ( $('.price-prod').length !== 0 ) {
		$('.price-prod').bind('click',function(){
			$('.price-prod').removeClass('selected');
			$(this).addClass('selected');
			updateMaterials();
			mathPrice();
		});
	}
});

unbindMaterials = function(){
	$('.price-mat').unbind('click',false);
}

bindMaterials = function(){
	unbindMaterials();
	$('.price-mat:not(.locked)').bind('click',function(){
		$('.price-mat').removeClass('selected');
		$(this).addClass('selected');
		mathPrice();
	});
}

updateMaterials = function(){
	$('.price-mat').removeClass('selected').addClass('locked');
	unbindMaterials();
	if ( $('.price-prod.selected').length === 0 ) {
		return;
	}
	var attr_id = $('.price-prod.selected').attr('id');
	var prod_id = attr_id.replace( /^.*_([0-9]+)$/, "$1" );
	$.post( page_url, {'do':'update_mat',product:prod_id}, function(data){
		// лочим все материалы по умолчанию
		$('.price-mat').addClass('locked');
		if ( typeof data == 'object' ) {
			for( key in data ) {
				$('#price-mat_'+data[key]).removeClass('locked');
			}
		} else {
			alert('Не удалось получить данные.');
		}
		bindMaterials();
	},'json' );
}

mathPrice = function(){
	if ( $('.price-prod.selected').length !== 0 && $('.price-mat.selected').length !== 0 ) {
		var prod_attr_id = $('.price-prod.selected').attr('id'),
			prod_id = prod_attr_id.replace( /^.*_([0-9]+)$/, "$1" ),
			mat_attr_id = $('.price-mat.selected').attr('id'),
			mat_id = mat_attr_id.replace( /^.*_([0-9]+)$/, "$1" );
			$.post( page_url, {'do':'load_price',product:prod_id,material:mat_id}, function(price){
				if ( typeof price == 'string' ) {
					displayPrice( price );
				} else {
					alert('Не удалось получить данные.');
				}
			},'json');

	} else {
		hidePrice();
	}
}
hidePrice = function() {
	$('#price big').text('Выберите продукцию и материал');
}
displayPrice = function( price ) {
	$('#price-wrapper').show('slow');
	$('#price big').text( price+' руб.' );
}
