$(document).ready(function() {
	$("a.lightbox").lightBox({
		imageBlank: "/template/lightbox-blank.gif",
		imageBtnClose: "/template/lightbox-btn-close.gif",
		imageBtnPrev: "/template/lightbox-btn-prev.gif",
		imageBtnNext: "/template/lightbox-btn-next.gif",
		imageLoading: "/template/lightbox-ico-loading.gif"
	});
	
	$("label.infield").inFieldLabels();
	$("#delivery-date").datepicker({
		appendText: 'pick date...',
		buttonImage: '/template/right-arrow.png',
		buttonImageOnly: true,
		buttonText: 'Pick Date...',
		dateFormat: 'dd/mm/yy',
		showOn: 'button',
		beforeShowDay: nonWorkingDates
	});
	
	function nonWorkingDates(date) {
		var day = date.getDay(), Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6;
		var closedDates = [/*[7, 29, 2009], [8, 25, 2010]*/];
		var closedDays = [[Sunday], [Monday]];
		for (var i = 0; i < closedDays.length; i++) {
			if (day == closedDays[i][0]) {
				return [false];
			}
		}
		
		for (i = 0; i < closedDates.length; i++) {
			if (date.getMonth() == closedDates[i][0] - 1 &&
			date.getDate() == closedDates[i][1] &&
			date.getFullYear() == closedDates[i][2]) {
				return [false];
			}
		}
		return [true];
	}
	
	$("#order-form").validationEngine({
		validationEventTriggers: "keyup blur"
	});
	$("#delivery-date").change(function() {
		if ($(this).val()) {
			$.validationEngine.closePrompt($(this));
		}
	});
	
	$("#order-submit").click(function(e) {									  
		var day = $("#delivery-date").datepicker("getDate").getDay();
		if (day == 6) {
			$("#shipping").val(10);
		}
		
		if ($('#festive-hoop').is(':checked') && $('#festive-hoop-coupon').val()) {
			$.ajax({
				cache: false,
				data: {coupon: $('#festive-hoop-coupon').val()},
				dataType: 'html',
				type: 'POST',
				url: '/includes/check-coupon-code.php',
				success: function(data) {
					if (data == 'OK') {
						$("#discount_amount").val(5);
					}
					
					setFields();
				}
			});
		}
		else {	
			setFields();
		}
		
		e.preventDefault();
	});
		
	function setFields() {
		var items = "";
		var amount = 0;
		
		$("input[name^='product[']:checked").each(function(index) {
			var elementName = $(this).attr("name");
			var elementIndex = (elementName).substring(8, elementName.length - 1);
			
			if (index > 0) { items += ", "; }
			items += $(this).val();
			amount += parseInt($("input[name=product_amount[" + elementIndex + "]]").val());		
		});
								
		$("#item_name").val(items);
		$("#amount").val(amount);
		
		$('#order-form').submit();
	}
});
