function getStxt(string) {
	if (typeof(stxt[string]) == 'undefined') {
		stxt[string] = string;
	}
	return stxt[string];
}

var timeframePossible = function(deliveryTimestamp) {
	return true;
}

$(document).ready(function() {
	/**
	 * @copyright Kingsquare information Services <code@kingsquare.nl>
	 * @author Marc van Duivenvoorde <marc@kingsquare.nl>
	 * @created 2010-03-17
	 *
	 * !!! Make sure you include a language file first. !!!
	 * {custom}/view/layout/flowerShop/{language}.js
	 */

	var productPrices = {};

	/**
	 * This will return a string in yyyymmdd format from a date object
	 */
	function getFormattedDate(dateObj) {
		var day = dateObj.getDate(),
			month = (dateObj.getMonth() + 1),
			year = dateObj.getFullYear();
		return year.toString()+ month.toString()+ day.toString()
	}

	
	/**
		Regular dynafix delivery (e.g. delivery with timeframe and 'Delivery outside NL') is NOT possible on
		delivery is today
		//delivery is sunday <-- shouldnt be in select in the first place, if it IS there, it's an separately added exception
		now > 17 and delivery is tomorrow
		delivery is Monday and product is flowers
		today is saturday and delivery is upcoming monday
		today is friday >17h and delvery upcoming monday
		delivery is on sunday
	*/
	function deliveryDynafixPossible(deliveryTimestamp) {
		//currentTimestamp exists in global scope
		return !(
				(date('dmY', currentTimestamp) == date('dmY', deliveryTimestamp)) 
				|| (date('dmY', deliveryTimestamp) == date('dmY', currentTimestamp+86400)
						&& (parseInt(date('G', currentTimestamp)) >= 17)
				)
				|| ((date('w', deliveryTimestamp) == '1') && isFlowers)
				|| (date('w', currentTimestamp) == '6'
						&& (date('dmY', deliveryTimestamp) == date('dmY', currentTimestamp+172800))
				)
				|| ((date('w', currentTimestamp) == '5')
						&& (parseInt(date('G', currentTimestamp)) >= 17)
						&& (date('dmY', deliveryTimestamp) == date('dmY', currentTimestamp+259200))
				)
		);
	}

	/** is possible in the following circumstances
	 * deliveryAddres is in the Netherlands
		delivery is NOT on saturday or sunday
		delivery is handled by Dynafix
	 **/
	function deliveryTimeframePossible(deliveryTimestamp, countryCode) {
		return (
				(countryCode == 'NL') &&
				(date('w', deliveryTimestamp) != '6') &&
				(date('w', deliveryTimestamp) != 0) &&
				timeframePossible(deliveryTimestamp) &&
				//default dynafix rules
				deliveryDynafixPossible(deliveryTimestamp)

		);
	}

	/**
	Do we need to show the customer that the product might possibly be delivered by a colleague?
		delivery is today
		//delivery is sunday <-- shouldnt be in select in the first place, if it IS there, it's an separately added exception
		delivery is monday
		now > 17 and delivery is tomorrow
	*/
	function colleagueDeliveryPossible(deliveryTimestamp) {
		return (
			(date('dmY', currentTimestamp) == date('dmY', deliveryTimestamp)) ||
			//(date('w', deliveryTimestamp) == '0') ||
			(date('w', deliveryTimestamp) == '1') ||
			(date('dmY', deliveryTimestamp) == date('dmY', currentTimestamp+86400) && (parseInt(date('G', currentTimestamp)) >= 17))
		);			
	}

	/**
	 * Callback for deliverydate changes
	 */
	var onDeliveryDateChange = function() {
		var dateArray = $('#deliveryDateSelect').val().split('-');
		//please note that radix is required for parseInt: strings starting with "0" are processed as octal by default.
		var deliveryTimestamp = mktime(0, 0, 0, parseInt(dateArray[1], 10),  parseInt(dateArray[0], 10),  parseInt(dateArray[2], 10));

		//check country options
		if (!deliveryDynafixPossible(deliveryTimestamp)) {
			if ($('#country').val() != 'NL') {
				alert(getStxt('deliveryOutsideNlNotPossible'));
				$('#country').val('NL');
			}
		}

		// check timeframe options
		if (deliveryTimeframePossible(deliveryTimestamp, $('#country').val())) {
			$('#timeframeSelect').addClass('notMinusOne').parent('li').show();
			$('#deliveryDateTimeframeInfo').hide();
		} else {
			$('#timeframeSelect').removeClass('notMinusOne').parent('li').hide();
			$('#timeframeSelect').val($('#timeframeSelect option:eq(1)').val());
			if ($('#country').val() == 'NL') {
				$('#deliveryDateTimeframeInfo').show();
			}
		}
		
		//check deliveryDateInfo
		if (colleagueDeliveryPossible(deliveryTimestamp)) {
			$('#deliveryDateInfo').show();
		} else {
			$('#deliveryDateInfo').hide();
		}
	};

	/**
	 * Callback for card changes
	 */
	var onCardChange = function() {
		switch($('#card').val()) {
			case "mcard2":
			case "3539232": // ribbon flowers4u
				$('#txtCard1').hide();
				$('#txtCard2').show();
				$('#cardText2, #cardText3').show().keyup();
				break;

			case undefined:
			case "-1":
			case "3539240":
			case "card0":
			case "mcard0":
				$('#txtCard1, #txtCard2').hide();
				break;

			default:
				$('#txtCard1').show();
				$('#txtCard2').hide();
				$('#cardText1').keyup();
		}
		return true;
	};

	/**
	 * callback for country changes
	 */
	var onCountryChange = function() {
		switch ($('#country').val()) {
			case 'NL':
				$('#phone').removeClass('required');
				$('#zipcode').addClass('zipcodeNL');
				break;

			default:
				$('#phone').addClass('required');
				$('#zipcode').removeClass('zipcodeNL');
				$('#zipcode').valid();
				$('#deliveryDateTimeframeInfo').hide();
				break;
		}
		onDeliveryDateChange();
	};

	/**
	 * Callback for webproduct, productcollectionmember changes. This will recalculate the vaseprice.
	 */
	var onWebProductProductCollectionMemberIdChange = function() {
		var vasePrice = 0,
			productPrice = productPrices[$('#webProductProductCollectionMemberId').val()];

		$.get('/gateway/flowerShop',
			{
				localAction: 'getVasePrice',
				price: productPrice
			},
			function(data) {
				vasePrice = data;

				if ($('#vase')) {
					$('#vase option').each(function() {
						if ($(this).val() == 1) {
							var label = getStxt('fittingVase');
							if (vasePrice > 0) {
								label += '   \u20ac '+ vasePrice.toString().replace('.', ',');
							}
							$(this).html(label);
						}
					});
				}
			},
			'json'
		);
	};

	/**
	 * Fill the select options for the webProductCollectionMember
	 */
	$.get(
			'/gateway/flowerShop/webProduct/',
			{
				localAction: 'webProductCollectionMemberPrices',
				webProductId: $('input[name=webProductId]').val()
			},
			function(data) {
				$('#webProductProductCollectionMemberId').html('');
				for (i in data) {
					var description = data[i].description;
					if (data[i].price > 0) {
						description	+= '  \u20ac '+ number_format(data[i].price, 2).toString().replace('.', ',');
					}

					$('#webProductProductCollectionMemberId').append($('<option></option>')
						.attr('value', data[i].id)
						.text(description));

					productPrices[data[i].id] = data[i].price;
				}
				if ($('#selectedWebProductProductCollectionMemberId')) {
					$('#webProductProductCollectionMemberId').val($('#selectedWebProductProductCollectionMemberId').val());
				}
			},
			'json'
	);

	/**
	 * Check whether it is possible to select a timeframe for delivery on the chosen date.
	 */
	$('#deliveryDateSelect').change(onDeliveryDateChange);

	/**
	 * Check the vase price which corresponds with the selected product.
	 */
	$('#webProductProductCollectionMemberId').change(onWebProductProductCollectionMemberIdChange);

	/**
	 * Trigger a keyup event on filling in of the cardText textfields. The fields have a maximum length for the string.
	 * 1: regular card
	 * 2: mourning card/ribbon
	 * 3: mourning card/ribbon
	 */
	$('#cardText1, #cardText2, #cardText3').keyup(function() {
		var identifier = $(this).attr('id').substr(8),
			strLength = $(this).val().length;
		
		switch (identifier) {
			case 2:
			case '2':
			case 3:
			case '3':
				maxLength = 40;
				break;
				
			case 1:
			case '1':
			default:
				maxLength = 150;
				break;
		}

		if (strLength >= maxLength) {
			$(this).val($(this).val().substring(0, maxLength));
			$('#textLeft'+ identifier).html('0');
			alert(getStxt('noCharactersLeft'));
		} else {
			$('#textLeft'+ identifier).html(maxLength - strLength);
		}
	});

	/**
	 * Change event handler for #card. Hide or show some blocks based on the chosen card and fire some
	 * keyup events to trigger the testing of the maximum length of the string in the formfields.
	 */
	$('#card').change(onCardChange);

	/**
	 * When switching a country, change the zipcode check. Only check valid dutch zipcode when NL is selected.
	 */
	$('#country').change(onCountryChange);

	/**
	 * Fire some events
	 */
	onDeliveryDateChange();
	onWebProductProductCollectionMemberIdChange();
	onCardChange();
	onCountryChange();
	$('#deliveryDateInfo').qtip({
		content: getStxt('deliveryByColleague')
	});
	$('#deliveryDateTimeframeInfo').qtip({
		content: getStxt('deliveryTimeInformation'),
		position: {
			corner: {
				target: 'topRight',
				tooltip: 'bottomLeft'
			}
		}
	});
	$('#deliveryDateSelect').focus();
});