var addToCart = function(id, anchor) {
	var parent = $(anchor).parent();
	var info = jQuery(anchor).parents('.item_info')

	parent.addClass('in_process');
	
	var size = 0;
	if($('#size' + id).length > 0) {
		size = $('#size' + id).val();
	}
	
	var data = {id: id, quantity: 1, size: size, action: 'add'};
	$.getJSON(cart_proc_url, data, function(json) {

		showCartDialog(function(){

			$('#totalSum').html(json.totalSum);
			$('#itemsCount').html(json.itemsCount);

			$.growlUI('Товар добавлен в корзину');

			parent.removeClass('in_process');


			if(!info.find('#size' + id).length) {
				//info.find('.buy_button').hide();
			}

//			if (!info.find(".pass").length) {
//
//				if (info.find('#size' + id).length) {
//
//					info.find('.add_info').html('В корзине 1 шт. ' +
//						'<a href="' + cart_url + '" class="pass">Оформить заказ</a>');
//					info.find('.add_info').show();
//				} else {
//
//					parent.html('В корзине 1 шт. ' +
//					'<a href="' + cart_url + '" class="pass">Оформить заказ</a>');
//				}
//
//			} else {
//
				info.find('.add_info').html('В корзине <span id="quantitylist_' + id + '">'+json.quantityallsizes+'</span> шт. <br/>' +
					'<a href="' + cart_url + '" class="pass">Оформить заказ</a>');
				info.find('.add_info').show();
//			}

		});
	});
}

function showCartDialog(callback) {
	$('#cart_dialog').load(cart_dialog_url, function() {
		if(callback) {
			callback();
		}
		$('#cart_dialog a.delete').click(function() {
			if(!confirm('Вы уверены что хотите удалить этот товар из корзины?')) {
				return false;
			}

			$.ajax({
				url: this.href,
				success: function() {
					$(this).parent()
				}
			});
		});
		$.blockUI({ message: $('#cart_dialog'), 'css': {width: '450px', top: '20%'}});
		$('.blockUI .close').click(function(){
			$.unblockUI(); return false;
		});
		$('.blockUI .continue_shop').click(function(){
			$.unblockUI(); return false;
		});
		$('.blockOverlay').click(function(){
			$.unblockUI(); return false;
		});
	});
}


function preOrderForm(id) {
	$.blockUI({ 
            message: '<p>Пожалуйста, подождите...</p>'
	});
	
	$.ajax({
		type: "GET",
		url: preorderUrl + '?p=' + id,
		success: function(data) {
			$.blockUI({ 
		            message: data
			});
			
			$('.blockOverlay').click($.unblockUI);
		}
	});
}

function processPreOrderForm(form) {
	if(!preOrderFormIsValid(form)) {
		return false;
	}
	
	$.blockUI({ 
            message: '<p>Пожалуйста, подождите...</p>'
	});
	
	$.ajax({
		type: "POST",
		url: preorderUrl,
		data: $(form).serialize(),
		success: function(data) {
			$.blockUI({ 
		            message: data
			});
			
			$('.blockOverlay').click($.unblockUI);
		}
	});
	
	return false;
}

function preOrderFormIsValid(form) {
	var errors = [];
	
	if(!form.name.value) {
		errors.push('Вы не ввели имя');
	}
	
	if(!form.phone.value) {
		errors.push('Вы не ввели телефон');
	}
	
	if(errors.length > 0) {
		var message = '';
		for(var i in errors) {
			message += errors[i] + "\n";
		}
		alert(message);
		return false;
	} else {
		return true;
	}
}

function processShipment() {
    $('.shipment_info').hide();
    if($('#shipinfo' + $(this).attr('id'))) {
        $('#shipinfo' + $(this).attr('id')).show();
    }

	// get allowed payment ids
	var allowedPaymentIds = $(this).attr('payments').split(",");

	console.log(allowedPaymentIds);

	// mark allowed as active
	jQuery('[name=payment_method]').removeClass('active');
	for (var allowedPaymentId in allowedPaymentIds) {
		var paymentId = allowedPaymentIds[allowedPaymentId];
		jQuery('[name=payment_method][id="pm' + paymentId + '"]').addClass('active');
	}

	// hide and show
	jQuery('[name=payment_method]').parents('tr.payment').hide();
	jQuery('.active[name=payment_method]').parents('tr.payment').show();

	// if inactive was selected, select first active
	if (jQuery('.active[name=payment_method]:checked').length == 0) {
		jQuery('.active[name=payment_method]:first').attr('checked', 'checked');
	}

	exclude_fields = new Array();

    if($(this).attr('no_index')) {
        $('tr.f_index').hide();
		exclude_fields.push('post_index');
    } else {
		$('tr.f_index').show();
	}

    if($(this).attr('no_city')) {
        $('tr.f_city').hide();
        exclude_fields.push('city');
    } else {
		$('tr.f_city').show();
	}

    if($(this).attr('no_address')) {
        $('tr.f_address').hide();
        exclude_fields.push('address');
    } else {
		$('tr.f_address').show();
	}

	if(exclude_fields.length >= 2) {
		$('.address_caption').hide();
	} else {
		$('.address_caption').show();
	}

	jQuery('[name="shipmentId"]').val($(this).attr('id'));

	var shipment = Math.ceil(jQuery(this).attr('price'));
	var order = Math.ceil(jQuery('[name="totalSum"]').val());
	var total = Math.ceil(order) + Math.ceil(shipment);

	jQuery('#deliverySpan').html(formatPrice(shipment));
	jQuery('#totalSpan').html(formatPrice(total));
}

function formatPrice(str){
	str = str.toString();
	return str.replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ');
}

function showAdvInfoAboutShipment(e) {
	e.preventDefault();
	$('.ship_adv_info_box').toggle();
}

function setPrices(json, item_id, size_id) {
	console.log(json);
	var total_sum;
		var total_sum_new;

		if(jQuery(".ajax_totalSum_old")) {
			total_sum		=	jQuery(".ajax_totalSum_old");
			total_sum_new	=	jQuery(".ajax_totalSum");
		} else {
			total_sum = jQuery(".ajax_totalSum");
		}

		if(jQuery('[name="shipment_type"]:checked')) {

			var price = parseInt(jQuery('[name="shipment_type"]:checked').attr('price'));
			price += parseInt(json._totalSum);
			jQuery('#totalSpan').html(formatPrice(price));
		}

		total_sum.html(json.totalSum);
		if(total_sum_new) {
			total_sum_new.html(json.totalSum_discount);
		}

		jQuery(".ajax_itemsCount").html(json.itemsCount);
		if(json.quantityallsizes) {
			jQuery("#quantity_" + item_id + "_" + size_id).html(json.itemQuantity);
			jQuery("#quantitylist_" + item_id).text(json.quantityallsizes);
		}
		else {
			jQuery("#quantitylist_" + item_id).parents('.add_info').empty();
			jQuery('#bay_button_' + item_id).show();
		}
		jQuery("#quantity_" + item_id + "_" + size_id + '_input').val(json.itemQuantity);

		var current_sum;
		var current_sum_new;

		if(jQuery("#sum_old_" + item_id + "_" + size_id)) {
			current_sum		=	jQuery("#sum_old_" + item_id + "_" + size_id);
			current_sum_new	=	jQuery("#sum_" + item_id + "_" + size_id);
		} else {
			current_sum		=	jQuery("#sum_" + item_id + "_" + size_id);
		}

		current_sum.html(json.itemSum);
		if(total_sum_new) {
			current_sum_new.html(json.itemSum_discount);
		}
}

$(function() {
	$('a.ship_adv_info_link').click(showAdvInfoAboutShipment);
	$('.ship_adv_info div.close').click(showAdvInfoAboutShipment);
});

function ajax_increase(item_id, size_id) {

	var data = {id: item_id, quantity: 1, size: size_id, action: 'add'};

	jQuery.getJSON(cart_proc_url, data, function(json) {
		setPrices(json, item_id, size_id);
	});

	return false;
}

function ajax_decrease(item_id, size_id) {

	var data = {id: item_id, quantity: 1, size: size_id, action: 'decrease'};

	var proceed = true;

	if((jQuery('#quantity_' + item_id + '_' + size_id + '_input').val() == 1) || (parseInt(jQuery('#quantity_' + item_id + '_' + size_id).html()) == 1)) {
		if(!confirm("У вас в коризне всего один товар этого вида, он будет удален. Удалить?")) {
			proceed = false;
		}
	}

	if(proceed) {
		jQuery.getJSON(cart_proc_url, data, function(json) {
			setPrices(json, item_id, size_id);

			if(!json.itemQuantity) {
				jQuery('#row_' + item_id + '_' + size_id).remove();
				jQuery('#item_row_' + item_id + '_' + size_id).remove();
			}
		});
	}

	return false;
}

function attachPhoneMask() {
	jQuery("#phone").mask("+38 (999)-999-99-99");
}
