jQuery(document).ready(function()
{
	jQuery(document).on('change', '.wcmca_product_address_select_menu', wcmca_reload_product_address);
	jQuery(document).on('update_checkout', wmca_checkout_updated);
	wmca_checkout_updated(null);
	wcmca_init_select_menus();
	//wcmca_move_product_shipping_boxes_after_variation();
});
function wmca_checkout_updated(event)
{
	//console.log("wmca_checkout_updated");
	//wcmca_move_product_shipping_boxes_after_variation();
	setTimeout(wcmca_init_add_new_addresses_button, 2500);
}
function wcmca_init_select_menus()
{
	//Initial state: selected emelemnt must be the first of the list (select box)
	jQuery('.wcmca_product_address_select_menu').each(function(index,elem)
	{
		jQuery(elem).val(jQuery(jQuery(elem).attr('id')+" option:first").val());
	});
}
function wcmca_move_product_shipping_boxes_after_variation()
{
	//console.log("move");
	jQuery('.wcmca_product_shipping_box').each(function(index,elem)
	{
		var result = jQuery(elem).parent()/* .find('.variation') */;
		//console.log(jQuery(result).last());
		var last_index =  jQuery(elem).parent().children().size() - 1;
		//console.log(last_index);
		if(result.length != 0 && jQuery(elem).index() != last_index)
		{
			//jQuery(elem).insertAfter(result);
			jQuery(elem).appendTo(result);
		}
	});
}
function wcmca_reload_product_address(event)
{
	var val = jQuery(event.currentTarget).val();
	var ids = val.split("-||-"); //[0] = cart_item_key; [1] = address_id; [2] = address_type;
	var type = ids[2]; 
	var random = Math.floor((Math.random() * 1000000) + 999);
	var formData = new FormData();

	if(ids[1] == "checkout_data")
	{
		//UI	
		jQuery('#wcmca_product_address_'+ids[0]).html(wcmca.default_address_message);
		return;
	}
	
	formData.append('action', 'wcmca_load_product_address');
	formData.append('cart_item_key', ids[0]);
	formData.append('address_id', ids[1]);
	formData.append('type', type);
	
	//UI
	//jQuery('#wcmca_product_address_loader_'+ids[0]).css('display', 'block');
	jQuery('#wcmca_product_address_'+ids[0]).html(wcmca.product_address_loading);
	
	jQuery.ajax({
		url: wcmca_ajax_url+"?nocache="+random,
		type: 'POST',
		data: formData,
		async: true,
		success: function (data) 
		{
			//UI	
			jQuery('#wcmca_product_address_'+ids[0]).html(data);
			//jQuery('#wcmca_product_address_loader_'+ids[0]).css('display', 'none');
						
		},
		error: function (data) 
		{
			//console.log(data);
			//alert("Error: "+data);
		},
		cache: false,
		contentType: false,
		processData: false
	});
}