$(document).ready(function() {
	/*
	 * Some default easing.
	 */
	$.easing.def = 'easeInOutSine';



	/*
	 * Some shortcuts.
	 */
	$.extend({
		min: function(a, b) { return a < b ? a : b; },
		max: function(a, b) { return a > b ? a : b; }
	});



	/*
	 * IE6 ...
	 */
	if ($.browser.msie && $.browser.version.substr(0, 1) <= 6) {

		function checkLeftColumn() {
			if ($('#left').length == 1) {
				var p = $('#left').position();
				if (p.left > 100) {
					var c = $('#container');
					c.css('width', c.width() == 570 ? '571' : 570);
				}
			}
		}

		setInterval(checkLeftColumn, 150);
	}

	/*
	 * Fix IE6/7 ignoring table padding.
	 */
	if ($.browser.msie && $.browser.version.substr(0, 1) <= 7) {
		$('.infoBox:not(#newProducts, #alsoPurchasedProducts) .infoBoxContents table').wrap('<div style="padding: 4px;"></div>');
	}

	/*
	 * Fix IE7 no content footer padding (also no table padding).
	 */
	if ($.browser.msie && $.browser.version.substr(0, 1) == 7) {
		$('#contentFooter .infoBoxContents table').wrap('<div style="padding: 4px;"></div>');
	}



	/*
	 * Page shadows.
	 */
	$('body')
		.width(968);
	$('#page')
		.wrap('<div style="padding-left: 4px; background: #ffffff url(\'/images/shadow-left.jpg\') repeat-y top left;"></div>')
		.wrap('<div style="padding-right: 4px; background: #ffffff url(\'/images/shadow-right.jpg\') repeat-y top right;"></div>');



	/*
	 * Menu links effect.
	 */
	if ($.support.opacity) {
		// Prepare images that are to be highlighted by cross fading another image and handle hover event for (objects containing) images with highlight.
		$('.crossFadeHighlight').each(
			function(h) {
				$(this)
					.wrap('<div></div>')
					.clone()
						.addClass('hover')
						.attr('src', $(this).attr('src').replace('.', '-glow.'))
						.css({'opacity' : '0', 'position' : 'absolute', 'left' : $(this).position().left + 'px', 'top' : $(this).position().top + 'px'})
						.appendTo($(this).parent())
					.parent().hover(
						function(event) {
							$(event.currentTarget).children(':not(.hover)').stop().fadeTo(500, 0);
							$(event.currentTarget).children('.hover').stop().fadeTo(500, 1);
						}, function(event) {
							$(event.currentTarget).children('.hover').stop().fadeTo(500, 0);
							$(event.currentTarget).children(':not(.hover)').stop().fadeTo(500, 1);
						}
					);
			}
		);
	} else {
		// Non animated version for browsers that don't support opacity with PNGs (IE 6, 7, 8 that is).
		$('.crossFadeHighlight').each(
			function(h) {
				$(this)
					.wrap('<div></div>')
					.clone()
						.addClass('hover')
						.attr('src', $(this).attr('src').replace('.', '-glow.'))
						.css({ 'display' : 'none', 'position' : 'absolute', 'left' : $(this).position().left + 'px', 'top' : $(this).position().top + 'px'})
						.appendTo($(this).parent())
					.parent()
						.css('cursor', 'pointer') /* This is only needed for IE6 & IE7. */
						.hover(
							function(event) {
								$(event.currentTarget).children(':not(.hover)').hide();
								$(event.currentTarget).children('.hover').show();
							}, function(event) {
								$(event.currentTarget).children('.hover').hide();
								$(event.currentTarget).children(':not(.hover)').show();
							}
						);
			}
		);

		// IE 6 also requires a complete PNG alpha fix. 
		if ($.browser.msie && $.browser.version.substr(0, 1) <= 6) {
			$('.crossFadeHighlight').each(
				function(h) {
					$(this).css('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + $(this).attr('src') + '",sizingMethod="image")');
					$(this).attr('src', '/images/pixel_trans.gif');
				}
			);
		}

		// In IE 6 and 7 links are unclickable. 
		if ($.browser.msie && $.browser.version.substr(0, 1) <= 7) {
			$('.crossFadeHighlight').each(
				function(h) {
					$(this).parent()
						.click(
							function(event) {
								window.location.href = $(this).parent().attr('href');
							}
						);
				});
		}
	}



	/**
	 * Submit forms on enter.
	 */
	$('input').keypress(function(e) {
		if (e.which == 13) {
			$(this).closest('form').submit();
			e.preventDefault();
			return false;
		}
	});

	// Focus the first input in some forms on default. TODO: Opera scrolls, placing the focused element at the top of the window.
	// $('#checkoutShipping, #checkoutPayment, form[name="reviews_write"]').find(':input:visible:enabled:first').focus();



	/*
	 * Marking/unmarking rows. Note that using .selector really checks if objects where created using the same DOM object here.
	 */
	var selected = $('#defaultSelected');
	if (selected) {
		selected.css('background-color', '#c5fc6f');
	}

	// Prevent selecting text.
	$('.selectableRow, .hoverRow, .checkBoxRow').each(function() {
		if ($.browser.mozilla) {
			$(this).css('MozUserSelect', 'none');
		} else if ($.browser.msie) {
			$(this).bind('selectstart', function() {return false; });
		} else {
			$(this).mousedown(function() { return false; });
		}
	});

	// One is always selected, color changes on hover, clicking marks any radio buttons contained.
	$('.selectableRow')
		.hover(
			function(event) {
				if (event.currentTarget != selected[0]) {
					$(event.currentTarget).css('background-color', '#dfffad');
				}
			}, function(event) {
				if (event.currentTarget != selected[0]) {
					$(event.currentTarget).css('background-color', '');
				}
			})
		.click(
			function(event) {
				selected.css('background-color', '');
				selected = $(event.currentTarget);
				selected.css('background-color', '#c5fc6f');
				selected.find(':radio').attr('checked', true).focus(); // Focus, so enter confirms the form.
			});

	// Color changes.
	$('.hoverRow, .checkBoxRow, .productsRemove')
		.hover(
			function(event) {
				$(this).css('background-color', '#dfffad');
			}, function(event) {
				$(this).css('background-color', '');
			});

	// Toggle contained checkboxes unless a checkbox itself has been clicked.
	$('.checkBoxRow')
		.click(
			function(event) {
				if (!$(event.target).is(':checkbox') && (!$(event.target).is('label') || ($.browser.msie && $.browser.version.substr(0, 1) <= 6))) {
					$(event.currentTarget).find(':checkbox').each(function(i) {
						$(this).attr('checked', !$(this).attr('checked'));
					});
				}
			})



	/*
	 * Preload images used in menu effects (other then already created through scripting).
	 */
	$.each(['/images/category-selected.jpg'], function() {
		$('<img src="' + this + '" />');
	});



	/*
	 * Add lightbox to selected image links.
	 */
	$('a[rel*=lightbox]').facebox();



	/*
	 * Form inputs background on focus.
	 */
	$('input:not(#headerSearchKeywords)')
		.focus(function() {
			$(this).css('background-color', '#fff8e6');
		})
		.blur(function() {
			$(this).css('background-color', '');
		});
		



	/*
	 * Cart subtotal updating and dynamic elements.
	 */
	function currency(value) {
		var c = String(Math.round(value * 100) / 100).replace('.', ',');
		var i = c.indexOf(',');
		if (i == -1) {
			c += ',00';
		} else if (i == c.length - 2) {
			c += '0';
		}
		return c + ' zł';
	}

	function parseCurrency(currency) {
		return Number(currency.replace(' zł', '').replace(',', '.'));
	}

	function updateSubtotal() {
		var st = 0;
		$('.productsTotal').each(function() {
			if ($(this).closest('tr').find('.productsRemove :checkbox').is(':not(:checked)')) {
				st += parseCurrency($(this).text());
			}
		});
		$('#subtotal').text(currency(st));
	}

	$('.productsQuantity input')
		.change(function() {
			var q = $(this);
			var r = q.closest('tr');
			q.val(Number(q.val().replace(/\D/, '')));
			r.find('.productsTotal').text(currency(Number(q.val()) * parseCurrency(r.find('.productsPrice').text())));
			updateSubtotal();

			if ($.browser.msie && $.browser.version.substr(0, 1) <= 6) {
				checkLeftColumn();
			}
 		})
		.keyup(function() {
			$(this).change();
		});

	$('.productsRemove')
		.click(function(event) {
			var t = $(this);
			var c = t.find(':checkbox');
			if (!$(event.target).is(':checkbox')) {
				c.attr('checked', !c.attr('checked'));
			}
			t.closest('tr').find('td, td *')
				.css('text-decoration', (c.is(':checked') ? 'line-through' : ''))
				.css('color', (c.is(':checked') ? '#999999' : '#000000'));
			updateSubtotal();
		})
		.css('cursor', 'pointer')
		.find(':checkbox').css('cursor', 'pointer');



	// If there are some google maps on the page, dynamically load the API, the page is responsible for defining initilizeMap function in the global scope.
	if ($('.googleMap').length > 0) {
		// Dynamically load maps API and let it call back (getScript won't work here, unless maybe with Google AJAX loader).
		$(document).append('<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&amp;sensor=false&amp;callback=initializeMap&amp;language=pl"><\/script>');
	}
});

