$(document).ready(function() {
	/**
	 * Set some global variables for date calculations
	 */
	var today = date('d-m-Y', currentTimestamp);
	var tomorrow = date('d-m-Y', (currentTimestamp + 86400));

	var printCards = new Array();

	/**
	 * Create a date in dd-mm-yyyy format based on the given date object.
	 */
	function getValidDate(date) {
		var d = date.getDate() +'-'+ (date.getMonth() + 1) +'-'+ date.getFullYear();
		var elements = d.split('-');
		for (i in elements) {
			if (elements[i].length < 2) {
				elements[i] = '0' + elements[i];
			}
		}
		return elements[0]+'-'+elements[1]+'-'+elements[2];
	}

	/**
	 * Check the deliveryDateToday. Can we send a certain product today for the zipcode?
	 */
	function checkDeliveryDateAndZipcode(currentWebProductType, zipcode) {
		var url, canOrderCadeau;

		url = '/gateway/topBloemen/';

		$('#checkDeliveryTodayMessage').html('');
		$('#checkDeliveryTodayFormClose').hide();

		canOrderCadeau = (currentWebProductType == 1);
		orderDate = $('#deliveryDateSelect').val();

		$.get(url, 
			{
				localAction: 'CheckDeliveryDateAndZipcode',
				pc: zipcode,
				date: orderDate,
				kd: canOrderCadeau
			},
			function(data) {
				$.post('/cart&localAction=registerDeliveryToday', {type: canOrderCadeau, deliverable: data});
				if (data == 0) {
					$('#deliveryDateSelect option').each(function() {
						if ($(this).val() == today
								|| ($(this).val() == tomorrow && date('G', currentTimestamp) >= 17)
								|| $(this).val() == orderDate) {
							$(this).remove();
						}
					});
					$('#checkDeliveryTodayMessage').html(getStxt('productNotDeliverableTodayAtZipcode'));
					$('#deliveryDateSelect').val(-1);
				} else {
					$('#checkDeliveryTodayMessage').html(getStxt('productDeliverableTodayAtZipcode'));
				}
			}
		);
		$('#checkDeliveryTodayFormClose').show();
	}

	/**
	 * Add custom validation rules to prevent posting the form without selecting any of the
	 * select options.
	 */
	jQuery.validator.addMethod("notMinusOne", function(value, element, params) {
		return this.optional(element) || value != -1;
	}, "U dient een selectie te maken.");

	jQuery.validator.addClassRules({
		notMinusOne: 		{ notMinusOne: true }
	});

	/**
	 * The stuff to do when everything is ready.
	 */

	/**
	 * business account js code. It's possible to use a preselected address from the ba profile. It's also
	 * possible to fill in an address from the select. If this address is posted it will be used on the
	 * order.
	 */
	if (hasBusinessAccount == true) {
		$.get('/gateway/businessAccount', {localAction: 'getDeliveryAddresses'}, function(data) {
			var addressStrings = data.addressStrings;
			var addresses = data.addresses;

			$('#street').autocomplete(addressStrings);
			$('#street').result(function() {
				for (i in addressStrings) {
					if (addressStrings[i] == $(this).val()) {
						$('#baSelectedAddressId').val(addresses[i].id);
						$('#street').val(addresses[i].street);
						$('#streetNumber').val(addresses[i].streetNumber);
						$('#zipcode').val(addresses[i].zipcode);
						$('#city').val(addresses[i].city);
					}
				}
			});
		}, 'json');
	}


	/**
	 * Delivery date change functionality
	 */
	$('#deliveryDateSelect').change(function() {
		if ($('#country option:selected').val() == -1) {
			$('#country').val('NL');
		}
		var val = $('#deliveryDateSelect').val();
		var deliveryTimestamp = mktime(0, 0, 0, val.substring(3, 5), val.substring(0, 2), val.substring(6, 10));

		/**
		 * if we can deliver today and it's past 12:00 or the selected product is not a flower product
		 * (currentWebProductType = 1), do a zipcode check
		 *
		 * else if: delivery on saturday outside NL, for a present or flowers on friday after 17:00
		 */
		if (deliveryToday == true || date('w', deliveryTimestamp) == 0) {
			if (($(this).val() == today
					&& (currentWebProductType == 1 || date('G', currentTimestamp) >= 12)
					&& date('w', currentTimestamp) != 6)
				|| date('w', deliveryTimestamp) == 0
			) {
				$('#checkDeliveryToday').jqmShow();
			} else if ($(this).val() == today
					&& (currentWebProductType == 1 || date('G', currentTimestamp) >= 12)
					&& date('w', currentTimestamp) == 6
			) {
				$('#deliveryDateSelect :selected').remove();
				$('#deliveryDateSelect').val($('#deliveryDateSelect option:eq(0)').val());
			}
		} else if ((date('w', deliveryTimestamp) == 6
						&& !isFlowers && $('#country').val() != 'NL'
				)
				|| (date('w', deliveryTimestamp) == 6 
						&& isFlowers && $('#country').val() != 'NL'
						&& date('w', currentTimestamp) == 5
						&& date('H', currentTimestamp) >= 17
				)
			) {
			$('#country').val('NL');
			$('#deliveryDateSelect').val($('#deliveryDateSelect option:eq(0)').val());
			alert(getStxt('deliveryOutsideNlNotPossible'));
		}
		
		/**
		 * if we have selected today (or tomorrow and the current time is later than 17:00),
		 * show the delivery by a collegue link.
		 */
		if (val == today) {
			$('#deliveryDateDiv').show();
		} else {
			if (val == tomorrow && date('G', currentTimestamp) >= 17) {
				if (currentWebProductType == 1) {
					$('#checkDeliveryToday').jqmShow();
				}
				$('#deliveryDateDiv').show();
			} else {
				$('#deliveryDateDiv').hide();
			}
		}
	});

	/**
	 * Is a delivery today possible js code.
	 */
	$('#checkDeliveryTodayFormClose').hide();

	$('#checkDeliveryToday').jqm({modal: true, trigger: 'a.showDialog'});
	
	/* IE6 needs the div to not be in the content */
	$('#checkDeliveryToday').appendTo('body');

	$('#checkDeliveryTodayForm').submit(function() {
		var zipcode = $('#checkDeliveryTodayFormZipcode').val();
		$('#checkDeliveryTodayFormClose').hide();
		checkDeliveryDateAndZipcode(currentWebProductType, zipcode);
		return false;
	});

	$('#checkDeliveryTodayFormPost').click(function() {
		$('#checkDeliveryTodayForm').submit();
		return false;
	});

	$('#checkDeliveryTodayFormClose').click(function() {
		$('#checkDeliveryToday').jqmHide();
	});

	$('#checkDeliveryTodayFormZipcode').focus(function() {
		$('#checkDeliveryTodayFormClose').hide();
	});

	$('body').append($('#checkDeliveryToday'));

	$('.formUl .zipcodeLi input, .formUl .deliveryDateLi select').change(function() {
		var zipcodeNumber = $('.formUl .zipcodeLi input').val().substring(0, 4);
		if (zipcodeNumber.length > 0 && (zipcodeNumber < 1000 || zipcodeNumber >= 4000)
				&& $('.formUl .deliveryDateLi select').val() == '14-02-2010') {
			alert('Helaas kan op deze datum niet bezorgd worden op de aangegeven postcode. Bezorging is alleen mogelijk voor de postcodes tussen 1000 en 3999.');
			$('.formUl .deliveryDateLi select').val(-1);
		}
	});
	
	$('#card').change(function() {
		$('#gelegenheidDiv').hide();	
		for (var i = 0; i < noGelegenheidCardIds.length; i++) {
			if (noGelegenheidCardIds[i] == $(this).val()) {
				$('#gelegenheidDiv').show();
				break;
			}
		}
	});

	$('#country').change(function() {
		$('#deliveryDateSelect').change();
	});

	/**
	 * General stuff to do when ready.
	 */
	$('#startOrderForm').validate();
	$('#checkDeliveryToday').hide();
});
