var cart_price = 0.0;
var delivery_price = 0.0;
var order_price = 0.0;
var today = 0;
var date_now = new Date();
var date_ptr = new Date();
function updateCartItem(item_id, quantity, personalise) {
	//window.alert('Update cart item has been called..');
	$.post("/assets/php/cart.php", {
		prodID: item_id,
		prodQty: quantity,
		prodAction: 'edit'
	},
	function(data) {
		data = jQuery.parseJSON(data);
		if(data.quantity == 0) {
			$('#' + data.compositeid).remove();
		}
		if(data.error) {
			alert(data.error);
			$('#' + data.compositeid + ' .item-qty').val(data.quantity);
		}
		$(".totalQty").html(data.cart_quantity);
		cart_price = parseFloat(data.cart_price);
		delivery_cost($('#order_type').val(), cart_price);
		order_cost();
		calculate_subtotal();
		$('#' + data.compositeid + ' .totalItemPrice').html(data.price_total);
		$('#' + data.compositeid + ' .totalItemPrice').attr('data-value', data.price_total);
		update_subtotal();
        return false;
	});
}


	
function update_subtotal() {
	var totalCount = 0;
    $('.totalpriceupdate').each(function() {
        var price = $(this).attr('data-value');
    	totalCount += parseFloat(price);
	});
	totalCount += parseFloat($('#gw_total_price').attr('data-price'));
	var discount = parseFloat($('.totaldiscounts').attr('data-value'));
}

var days = [
	['17:30', '23:00'], [], ['17:30', '23:00'], 
	['17:30', '23:00'], ['17:30', '23:30'], ['17:30', '23:30'],
	['17:30', '23:00']
];
function selectdelivery() {
	var length = days.length;
	$('#delivery_time option').remove();
	var day_select = document.getElementById('delivery_day');
	var date_count = 0;
	if(day_select) {
		var index = day_select.selectedIndex;
		if(!index) {
			index = 0;
		}
		var day_info = days[day_select.options[index].value];
		date_ptr.setTime(date_now);
		var date_start = new Date();
		var date_end = new Date();
		date_start.setHours(day_info[0].substr(0, 2), day_info[0].substr(3, 2), 0, 0);
		date_end.setHours(day_info[1].substr(0, 2), day_info[1].substr(3, 2), 0, 0);
		if(day_info.length) {
			if(date_now.getHours() == 21 && date_now.getMinutes() < 15) {
				date_now.setHours(21);
				date_now.setMinutes(00);
				date_ptr = new Date(date_now);
			}
			else if(index < 4) {
				if(date_now.getHours() == 22) {
					if(date_now.getMinutes() < 15) {
						date_now.setHours(21);
						date_now.setMinutes(00);
						date_ptr = new Date(date_now);
					}
				}
			}
			else
			{
				if(date_now.getHours() == 22) {
					if(date_now.getMinutes() < 45) {
						date_now.setHours(21);
						date_now.setMinutes(59);
						date_ptr = new Date(date_now);
					}
				}
			}
			while(date_start.getTime() < date_end.getTime()) {
				var text = date_start.getHours().toString() + ':' + zero_pad(date_start.getMinutes());
				date_start.setTime(date_start.getTime() + (30 * 60 * 1000));
				date_ptr.setTime(date_start.getTime() + (30 * 60 * 1000));
				if(date_now.getHours() + 1 < date_ptr.getHours()|| today != index) {
				console.log(date_now.getHours() + 1);
				console.log(date_ptr.getHours());					
					date_count++;
					text += ' - ' + date_start.getHours().toString() + ':' + zero_pad(date_start.getMinutes());
					var option = document.createElement('option');
					option.value = text;
					option.innerHTML = text;
					document.getElementById('delivery_time').appendChild(option);
				}
			}
			
		}
		if(!day_info.length || !date_count) {
			var option = document.createElement('option');
			option.value = "";
			option.innerHTML = 'Closed';
			document.getElementById('delivery_time').appendChild(option);
		}
	}
}

function zero_pad(number) {
	if(number < 10) {
		return '0' + number.toString();
	}
	return number;
}

$(document).ready(function() {
	$(".add").click(function(e) {
		var jselect = $(this).parent().children('select');
		if(!jselect.length || jselect.val()) {
			e.preventDefault();
					$.post("/assets/php/cart.php", {
					prodID: $(this).attr('data-id'),
					prodQty: 1,
					prodOptions: $('.prod-options').map(function () { return $(this).val(); }).get(),
					prodAction: 'add'
				}
				, function(data) {
					if(data) {
						data = jQuery.parseJSON(data);
						if(data.error) {
							alert(data.error);
						}
						else
						{
							if(!document.getElementById(data.compositeid)) {
								var element = document.createElement('div');
								var quantity = document.createElement('input');
								var product = document.createElement('span');
								var price = document.createElement('span');
								var remove = document.createElement('a');
								remove.className = 'item-remove';
								price.className = "price";
								product.className = "product";
								element.appendChild(quantity);
								element.appendChild(product);
								element.appendChild(price);
								element.appendChild(remove);
								element.id = data.compositeid;
								quantity.value = data.quantity;
								price.innerHTML = ('&pound;'+data.price_total+' <br /><a class="item-remove" data-id="'+data.compositeid+'">Remove</a>');
								product.innerHTML = data.product_name;
								if(data.option_name) {
									product.innerHTML += ' ' + data.option_name;
								}
								document.getElementById('cart_items').appendChild(element);
							}
							else
							{
								$('#' + data.compositeid + ' input').val(data.quantity); 
							}
							$(".totalQty").html(data.cart_quantity);
							cart_price = parseFloat(data.cart_price);
						}
					}
			})
		}
		return false;
	});
	  
	  
	  
	$('.item-qty').change(function() {
		//window.alert('A quantity has changed..');
		var jthis = $(this);
		var jval = jthis.val();
		var item_id = jthis.parent().parent().attr('data-id');
		if(jval && item_id) {
			updateCartItem(item_id, jval);
		}
	});
	
	$('.item-remove').live('click', function(event) {
		var id = $(this).attr('data-id');
		updateCartItem(id, 0);
		$(id).remove();
	});
	var date_now = new Date();
	$('#delivery_day').change(selectdelivery);
	today = date_now.getDay() - 1;
	if(today == 5) {
		today = 0;
	}
	else if(today == -1) {
		today = 6;
	}
	$('#delivery_day option').eq(today).prop('selected', 'selected');
	
	$('#order_type').change(function() {
		delivery_cost($(this).val(), cart_price);
		calculate_subtotal();
	});
	$('#payment_type').change(function() {
		order_cost();
		calculate_subtotal();
	});
	order_cost();
	selectdelivery();
	cart_price = parseFloat($('.subtotal').text(), 10);
	calculate_subtotal();
});

$('.prod-options').change(function() {
	var jchild = $(this).children(':selected');
	$('#product_' + jchild.attr('data-id')).children('.price').html('&pound;' + (jchild.attr('data-price') / 100).toFixed(2));
});


$('.checkoutsubmit').click(function(e) {
	e.preventDefault();

	$.post("/assets/php/store_cvals.php",
		{
			orderType: $('#order_type option:selected').val(),
			deliveryDay: $('#delivery_day option:selected').val(),
			deliveryTime: $('#delivery_time option:selected').val(),
			paymentType: $('#payment_type option:selected').val(),
			title: $('#delivery_title').val(),
			firstname: $('#delivery_firstname').val(),
			surname: $('#delivery_surname').val(),
			email: $('#delivery_email').val(),
			telephone: $('#delivery_phone').val(),
			address_1: $('#delivery_address_1').val(),
			address_2: $('#delivery_address_2').val(),
			town: $('#delivery_address_town').val(),
			postcode: $('#delivery_address_postcode').val(),
			additional_information: $('#additional_information').val()
		},
		function(data){
			if(data=="Success"){
				window.location = '/order/confirm';
				return false;
			}
			else{
				window.alert('Sorry, something went wrong.');
			}
		}
	)
});


function delivery_cost(type, order_cost) {
	delivery_price = 0;
	if(type == 'collect' || order_cost > 10) {
		$('#delivery_cost').text('FREE');
	}
	else
	{
		delivery_price = parseFloat(2);
		$('#delivery_cost').html('&pound;2.00');
	}
	calculate_subtotal();
}

function order_cost() {
	order_price = 0;
	if($('#payment_type').val() == 'credit') {
		order_price = parseFloat(0.5);
	}
}

function calculate_subtotal() {
	$('.subtotal').html(parseFloat(Math.floor((cart_price + delivery_price + order_price) * 100) / 100).toFixed(2));
}
