/*
	* Version 1.1
*/

function updateDeliveryTime (shippingMethod) {

	$.get ('?', { ajax: true, delivery_option: shippingMethod }, function (responseJson) {

			$('.shipping-info').fadeOut(function() {
				$('#shipping_info_description').html(responseJson.name);
				$('#shipping_info_time').html(responseJson.time);
				$('#shipping_info_estimate').html(responseJson.estimate);
				$('.grandtotal').html(responseJson.totalCost);
				$('.shipping-info').fadeIn();
				});

			}, 'json');
}
	$(function() {
		$('a.remove').livequery('click', function(e) {
			e.preventDefault();
			$(this).parent().parent().fadeOut();

			$.get('?', { ajax: true, 'delete': $(this).attr('rel') }, function (responseJson) {
				$('.subtotal').html(responseJson[1]);
				$('.grandtotal').html(responseJson[0]);

				if (responseJson[2] <= '0') {
					window.location = '/basket';
				}
			}, 'json');
		});

		$('a.update_basket').livequery('click', function(e) {
			e.preventDefault();

			$('#basket_form').submit();
		});
		
		$('#delivery_option').change(function() {
			updateDeliveryTime($('#delivery_option').val());
		});

		$('#crosssell_form').submit(function(e) {
			e.preventDefault();

			allFields = '';
			$('#crosssell_form input[type=checkbox]:checked').each(function(i) {
				allFields += $(this).val() + "&";
			});

			$.get('?', { ajax: true, crosssells: allFields }, function (responseJson) {
				$('#basket_data').fadeOut(function() {
					$('#basket_data').html(responseJson[0]);
					$('#basket_data').fadeIn();
				});

				$('.grandtotal').html(responseJson[1]);

			}, 'json');

		});



	$('#country').change(function() {
		var shippingCountry = $('#country').val();
		$.get('/basket', { ajax: true, shipping_country: shippingCountry, total_cost: $('#hidden_total_cost').val() }, function(responseJson) {
			var shippingOptionHtml = '';
			first = false;
			for(var i in responseJson) {
				shippingOptionHtml += '<option value="' + responseJson[i].id + '">' + responseJson[i].name + ' (' + responseJson[i].price + ')</option>';
				if (!first) {
					updateDeliveryTime(responseJson[i].id);
					first = true;
				}
			}
			$('#delivery_option').html(shippingOptionHtml);
			window.location = '/basket';
		}, 'json');

		if ($(this).val() == 'store') {
			$('#store_id').show();
			$('#delivery_option').hide();
			$('#shiptowhere').val('store');
			$('#store_id').change();
			$('.store-info').show();
			$('.shipping-info').hide();
			$('#selected_store').show();
			$('#store_id').change();
		} else {
			$('#store_id').hide();
			$('#delivery_option').show();
			$('#shiptowhere').val('');
			$('.store-info').hide();
			$('.shipping-info').show();
			$('#selected_store').hide();


		}

	});
		
	});

