(function($) {

	$(function() {

		// cart hover
		var isOverWritten = false;
		jQuery.fn.cartHover = function (cartItems, duration) {
			var cartLink = $(this),
			t;
			duration = duration || 500;

			//$(cartItems).hide();

			cartLink.live('mouseenter mouseleave', function (e) {
				if (!isOverWritten) {
					if (e.type === 'mouseover') {
						$(cartItems).fadeIn();
					} else {
						t = setTimeout(function () {
							$(cartItems).fadeOut();
						}, duration);
					}
				}
			});

			$(cartItems).live('mouseenter mouseleave', function (e) {
				if (!isOverWritten) {
					if (e.type === 'mouseover') {
						clearTimeout(t);
						$(cartItems).show();
					} else {
						$(cartItems).fadeOut();
					}
				}
			});
		};

		//Autocomplete
		if (typeof installPath != 'undefined') {
			YAHOO.example.CustomFormatting();
		}

		$('.yui-ac-container').delegate('.yui-ac-hd a', 'click', function(event) {
			$(this).parents('form').submit();
			event.preventDefault();
		});

		$('select').each(function() {
			var self = $(this);
			var id = self.attr('id');
			if (id === 'billing:country_id' || id === 'shipping:country_id') {
				self.change(function () {
					if (self.val() === 'GB') {
						$('input').each(function (i, e) {
							if ($(e).attr('id') === 'billing:postcode') {
								if (id === 'billing:country_id') {
									$(e).addClass('required-entry').siblings('label').append('<span class="required"> *</span>');
								}
							} else if ($(e).attr('id') === 'shipping:postcode') {
								if (id === 'shipping:country_id') {
									$(e).addClass('required-entry').siblings('label').append('<span class="required"> *</span>');
								}
							}
						});
					} else {
						$('input').each(function (i, e) {
							if ($(e).attr('id') === 'billing:postcode') {
								if (id === 'billing:country_id') {
									$(e).removeClass('required-entry validation-passed validation-failed').siblings('label').find('.required').remove();
								}
							} else if ($(e).attr('id') === 'shipping:postcode') {
								if (id === 'shipping:country_id') {
									$(e).removeClass('required-entry validation-passed validation-failed').siblings('label').find('.required').remove();
								}
							}
						});
					}
					billingForm = new VarienForm('co-billing-form');
				});
			}
		});

		$('.mini-cart .cart-hover').cartHover('.cart-items');

		$('#controls').hide().bind({
			'mouseenter': function () {
				$('#controls').show();
			},
			'mouseleave': function () {
				$('#controls').hide();
			}
		});

		function loadCycle() {
			$('#banner').cycle({
				fx: 'scrollHorz',
				pause: 1,
				prev: '#left a',
				next: '#right a'
			}).bind({
				'mouseenter': function () {
					$('#controls').show();
				},
				'mouseleave': function () {
					$('#controls').hide();
				}
			});
		}

		if ($('#banner').length > 0) {
			loadCycle();
		}

		$('#tabs li a').click(function (event) {
			var el = $(this).parent('li'),
			butts = $('#tabs li'),
			banner = $('#banner'),
			id = this.id.substr(3);

			banner.ajaxSend(function () {
				banner.html('<div style="background:url(/shop/skin/frontend/default/default/images/ajax-loader.gif) no-repeat center;height:266px;width:682px;" />');
				butts.removeClass('selected');
				el.addClass('selected');
			}).load('hometabs.php?category_id=' + id, {}, function () {
				setTimeout(function () {
					loadCycle();
				}, 500);
			});
			event.preventDefault();
		});

		// Nothing above here breaks the page


		// Cutting Info
		$('.cutting-hover').hover(function () {
			$('.cutting-info').show();
		}, function () {
			$('.cutting-info').hide();
		});


		// Load header cart
		$('#cart').load('/cart.php', {
			cache: false
		});


		$('.banner-slide').not(':first').hide();

		var j = 1,
		tabs = $('#banner ul li a').length;

		$('#banner ul li a').each(function (i, e) {
			$(e).click(function (event) {
				$('#banner .selected').removeClass('selected');
				$('.banner-slide').fadeOut().eq(i).fadeIn();
				$(this).addClass('selected');
				j = i;
				event.preventDefault();
			});
		});

		setInterval(function () {
			if (j === tabs) {
				j = 0;
			}
			$('#banner ul li a:eq(' + j + ')').click();
			j++;
		}, 4000);

		$('.up-sell table').not(':first').hide();

		$('.head #tabs li:first').addClass('selected');
		$('.head #tabs li').each(function (i, e) {
			$(e).click(function (event) {
				$('.head #tabs li').removeClass('selected');
				$(e).addClass('selected');
				$('.up-sell table:visible').hide();
				$('.up-sell table:eq(' + i + ')').show();
				event.preventDefault();
			});
		});


		// AJAX add to cart
		var cartDiv = $('#cart'),
		html_body = $('html, body'),
		cartItems = $('.cart-items');
		$('.add-to-cart-form').submit(function (e) {
			var self = $(this),
			action = self.attr('action'),
			submit = $('button', self),
			ajax = function () {
				$.ajax({
					beforeSend: function () {
						submit.attr('disabled', 'disabled').addClass('disabled');
						submit.after('<span class="loading">Loading...</span>');
						isOverWritten = true;
					},
					data: self.serialize(),
					success: function (data) {
						cartDiv.load('/ajax-cart.php', function () {
							submit.attr('disabled', '').removeClass('disabled');
							$('.loading').remove();
							html_body.animate({
								scrollTop: 0
							});
							$('.cart-items').fadeIn();
							setTimeout(function () {
								cartItems.fadeOut();
								isOverWritten = false;
							}, 3000);
						});
					},
					url: action
				});
			};

			if (typeof new VarienForm('product_addtocart_form').validator == 'undefined') {
				ajax();
			} else if (new VarienForm('product_addtocart_form').validator.validate()) {
				ajax();
			}

			e.preventDefault();
		});

		// FAQ

		$('.tut-content').hide();
		$('.box h3 a').click(function (e) {
			$(this).parent().next('.tut-content').toggle();
			e.preventDefault();
		});

		/* Ireland post code fixer
		var no_post_code = ['IE'];
		$('select[title=Country]').live('change', function (e) {
			var val = $(this).val(),
			post_code_input = $('input[title="Zip/Postal Code"]'),
			post_code_label = $('label[for="billing:postcode"] .required, label[for="zip"] .required');

			if ($.inArray(val, no_post_code) >= 0) {
				post_code_input.removeClass('required-entry');
				post_code_label.hide();
			} else {
				post_code_input.addClass('required-entry');
				post_code_label.show();
			}
		});*/


		// videos / tutorials dropdown
		$('#tutorial-box a').bind('click', function (e) {
			$('#tutorial-box-toggle').slideToggle();
			e.preventDefault();
		});

		/*$('#latest-videos a:first').bind('click', function (e) {
			$('#latest-videos-toggle').slideToggle();
			e.preventDefault();
		});*/

		// Show hide description
		$('.listing-item, .product').each(function (i, e) {
			var moreLink = $('.more-link', e),
			moreText = $('.more-text', e);
			moreLink.find('a').click(function (e) {
				moreLink.hide();
				moreText.show();
				e.preventDefault();
			});
		});

		// Hide border on tables
		$('table th:last').css({
			borderRight: 0
		});

		// Equal heights
		$('#content, #best-sellers').equalHeight();

		$('#category-list, #banner-container').equalHeight();

		$('.listing-type-grid .listing-item').equalHeight();

		//Mini Search toggle
		$('.mini-search .head h2 a').each(function (i, el) {
			$(el).click(function (e) {
				$('.mini-search .head h2 a').removeClass('selected');
				$(this).addClass('selected');
				if (i === 0) {
					$('#advanced-search-container').hide();
					$('#search-container').show();
				} else if (i == 1) {
					$('#search-container').hide();
					$('#advanced-search-container').show();
				}
				e.preventDefault();
			});
		});

		// A fix for an IE8 problem regarding CSS3PIE
		$('#search-container').hide();
		setTimeout(function() {
			$('#search-container').show();
		}, 200);

		// Definition List Toggle
		$('.toggle dt').click(function (e) {
			$(this).next('dd').slideToggle();
			e.preventDefault();
		});

		// Glossary opener

		if (window.location.hash == '#glossary') {
			$('.glossary').show();
		}

		// Captcha Code
		$('#refresh').click(function (e) {
			$('#captchacode').attr('src', '/lib/captcha/generate.php?' + Math.round(Math.random() * 100));
			e.preventDefault();
		});

		// External links
		$('a:external, a[rel="external"]').each(function () {
			$(this).click(function (event) {
				window.open($(this).attr('href'));
				event.preventDefault();
			});
		});
	});
}(this.jQuery));
