
function updateShipsBy() {
	var shippingTime = productShippingTime();

	// Find the maximum shipping time for all the currently enabled accessories
	$('span.shipping-time').each(function (i, span) {
		if ($(span).closest('section').find('a.personalize-button:visible').length) {
			var acc = parseInt($(span).text(), 10);
			if (acc > shippingTime)	
				shippingTime = acc;
		}
	});

	var bo = new Date();
	// Add the backordered delay, if any
	$('#backordered-date:visible').each(function (i, e) {
		bo = new Date($(e).text().replace(/-/g, '/'));
	})

	bo = bo - 0; // convert to integer

	while (shippingTime > 0) {
		// Add one day to backorder time;
		bo += (24 * 60 * 60 * 1000);
		var dow = new Date(bo).getDay();
		if (dow > 0 && dow < 6) {
			// Mon..Fri
			--shippingTime;
		}
	}

	// convert back to date object
	bo = new Date(bo);

	var pad = function(i) { return i < 9 ? '0' + i : i }
	$('#ship-by-date').text(pad(bo.getMonth() + 1) + '/' + pad(bo.getDate()) + '/' + bo.getFullYear());
}

function bind_order_form() {
	// If we're show a KA product, we have to wait for the async ajax call to finish
	if (typeof(getPersonalizationData) == 'function' && has_ka_p13n) {
		if (!kaAjaxComplete) {
			setTimeout('bind_order_form()', 100);
			return;
		}
	}

	$('#order-form section.accessory.optional')
		.find('.p13n-body').hide().end()
		.find('input.check-yes,input.check-no').change(function () {
			var $body = $(this).closest('section').find('.p13n-body');
			var $qty = $('#itm-qty-input');

			var fn = $(this).is('.check-yes:checked') ? $body.slideDown : $body.slideUp;

			fn.apply($body, [ 'fast', function() { if ($qty.val() !== '') $qty.validate(); updateShipsBy()} ]);
		}).end()
		.find('select.option.required').each(function (i, e) {
			$(e).validate({});
		});
};

function getQuantity() {
	var quantity, multiplier;

	quantity   = parseInt($('#itm-qty-input').val(), 10);
	multiplier = productMultiplier();

	return quantity * multiplier;
}

function setup_reviews() {
	// Chop reviews UL into 3-item ULs for pagination
	var $reviews = $('#reviews');
	var $items = $reviews.find('li');
	var $ul = null;

	$reviews.find('ul').remove();

	$items.each(function (i, e) {
		if (!$ul) { $ul = $('<ul/>'); }
		$ul.append(e);
		if ((i + 1) % 3 == 0) {
			// New page
			$reviews.append($ul);
			$ul = null;
		}
	});

	if ($ul) { $reviews.append($ul); }

	$('#reviews').cycle({ 
		fx:     'fade',
		speed:  300,
		timeout:  0,
		pager:  '#review-pager',
		next:   '#next-reviews',
		prev:   '#prev-reviews'
	});
} // function setup_reviews


$(function() {
	bind_order_form();

	//
	// Order form validation and processing
	//
	
	$('#order-form').submit(function(event) {
		var $form = $(this);

		if (!$form.isValid()) {
			event.preventDefault();
			return false;
		}

		$('#personalization-error').fadeOut();

		// Check that the user has applied personalization
		$('a.personalize-button:visible').each(function (i, $e) {
			$e = $($e);
			if ($e.closest('section').find('li.p13n-row').find('input:visible,select:visible').length === 0) {
				$('#personalization-error').fadeIn();	
				return false;
			}
		});

		if ($('#personalization-error:visible').size()) {
			return false;
		}

		if ($('#backordered').is(':visible') && !$('#backordered-accept').attr('checked')) {
			$('#backorder-error').fadeOut('fast', function () {
				$('#backorder-error').fadeIn('fast');
			});
			event.preventDefault();
			return false;
		}

		makePostFields = function(fields, name) {
			$(fields).each(function(i, $e) {
				var label, value;
				$e = $($e);

				label = $form.find('label[for=' + $e.attr('id') + ']:first');
				
				if (label.length) {
					label = label.text();
					// We have a label
					
					// Remove trailing colon
					label = $.trim(label.substr(0, label.length - 1));
				} else {
					// No label
					if ($e.closest('li.p13n-row').find('option:selected').text() == 'Monogram') {
						label = 'Monogram';
					} else {
						label = $e.attr('id');
					}
				}

				// Find the value of the field (different for input vs select)
				if ($e.is('input')) {
					value = $e.val();
				} else if ($e.is('select')) {
					// Select values are GUID, we want the text associated with that GUID
					value = $e.val();
					value = $e.find('option[value=' + value + ']').text();
				}

				$form.append($('<input type="hidden" />').attr('name', name + '[' + label + ']').attr('value', value));
			});
		};

		// Product-specific options
		makePostFields($form.find('section.ka-product-options').find('input:visible,select:visible'), 'p13n');

		//makePostFields($form.find('#tag-form .p13n-row').find('input:visible,select:visible'), 'tags-p13n');

		$('section.ka-accessory').each(function(i, $e) {
			$e = $($e);
			var accessoryId = $e.find('span.accessory-id').text();
			makePostFields($e.find('ul.p13n-body').find('input:visible,select:visible'), 'accessory-' + accessoryId);
		});
		
		// Enable any disabled FC p13n fields so they'll post
		$('#fashioncraftGlasswareDesign').removeAttr('disabled');
		$('#fashioncraftGlasswareColor').removeAttr('disabled');

		return true;
	
	})

	$('#itm-qty-input').validate({
		'filter'     : /^[0-9]$/,
		'pattern'    : /^[0-9]{1,4}$/,
		'max_length' : 4,
		'callback' : function (value) {
			value = parseInt(value, 10);

			var min = productMinQuantity();
			var multiplier = productMultiplier();
		
			if (value < min) {
				return 'This product has a minimum quantity of ' + min + '.  You must specify at least this amount.';
			}

			var msg = false;
			$('section.accessory').each(function (i, $e) {
				$e = $($e);
				if ($e.find('ul.p13n-body:visible').size()) {
					min = parseInt($e.find('span.min-qty').text());

					if ((value * multiplier) < min) {
						var name = $e.find('p').text();
						name = name.replace(/Add (.+) \(.*\)/, '$1');

						if (multiplier > 1) {
							msg = 'A minimum quantity of ' + Math.ceil(min / multiplier) + ' sets of ' +
								multiplier + ' is required when adding <b>' + name + '</b>';
						} else {
							msg = 'A minimum quantity of ' + Math.ceil(min / multiplier) +
								' is required when adding <b>' + name + '</b>';
						}

						return;
					}
				}
			});

			return msg ? msg : true;
		}
	}).focus(function () {
		$(this).data('last-value', $(this).val());
		$(this).val('');
	}).blur(function () {
		if ($(this).val() == '') {
			$(this).val($(this).data('last-value'));
		}
	});

	// Setup display of backordered products
	if ($('#backordered').length && !$('#backordered').hasClass('all-backordered')) {
		$('#backordered input:checkbox').change(function () {
			if ($(this).is(':checked')) {
				$('#backorder-error').hide();
			}
		});
		$('select.option.master').change(function () {
			var matches, text = $(this).find(':selected').text();
			var re = /^.+\(Available (\d\d\/\d\d\/\d\d\d\d)\)$/;

			if (matches = re.exec(text)) {
				// product is backordered
				$('#stock').addClass('out-of-stock').text('OUT OF STOCK');
				$('#backordered-date').text(matches[1]);
				$('#backordered-accept').removeAttr('checked');
				$('#backordered').show();
			} else {
				$('#stock').removeClass('out-of-stock').text('IN STOCK');
				$('#backordered').hide();
			}

			updateShipsBy();

		}).change();
	}

	$('#names').validate({ length : [1, 25] })
	$('#date').validate({ length : [1, 20] })

	$('#order-form select').live('change', function () {
		// TODO - this needs some thought; might not work
		if (!($.browser.msie && $.browser.version == '7.0')) {
			setTimeout("$.uniform.update('#order-form select');", 250);
			setTimeout("$.uniform.update('#order-form select');", 500);
		}
	});

	setup_reviews();
	//setup_ship_by_date();

	$('#live-chat-button a').click(function (event) {
		event.preventDefault();

		window.open('https://chat.livechatinc.net/licence/1032060/open_chat.cgi?lang=en&groups=0&dc=' +
			escape(document.cookie + ';l=' + document.location + ';r=' + document.referer + ';s='
			+ typeof lc_session),'chat_1032060', 'width=529,height=520,resizable=yes,scrollbars=no,status=1');
	
		return false;
	});

	// Full Sized Image
	$("a#see-full-image").fancybox({ scrolling:'no', titleShow:false });

	$("#email-this").fancybox({
		scrolling : 'no',
		autoScale : false,
		onComplete: function() {

			$('#sender-name,#recipient-name').validate({ length : [1,50] });
			$('#sender-email,#recipient-email').validateAs('email');
			$('#email-message').validate({ length : [1,500] }).watermark('Write your message here...');

			$('#email-form form').ajaxForm({
				response : '#email-response',
				success : function () { 
					$(this)
						.find('#send-email').hide().end()
						.find('div.captcha').hide();

					setTimeout('$.fancybox.close()', 2000);
				},
				failure : function () {
					Recaptcha.reload();
				}
			});

		}
	});
	
	(function() {
		var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
		po.src = 'https://apis.google.com/js/plusone.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
	})();

	$('#qty-calculator').fancybox({ scroll : false });
	$('#calculate-itm-qty').validate({
		filter: /\d/
	});
	
	$('#set-calculator form').submit(function (event) {
		event.preventDefault();
		var total = parseInt($('#calculate-itm-qty').val(), 10);
		var sets = Math.ceil(total / productMultiplier());
		$('#required-qty').text(sets);
		$('#sets').text(sets == 1 ? 'set' : 'sets');
	});

	$('#calculate-checkout').click(function (event) {
		event.preventDefault();

		$('#set-calculator form').submit();

		$('#itm-qty-input').val($('#required-qty').text());

		$.fancybox.close();
	});

	updateShipsBy();

	// Display the submit button oncen all other JS has run
	$('#submit strong').html('<button id="add-to-cart" type="submit"><span>Add to Cart</span></button>');
});


