function facebookLogin(response) {
	window.location = "/members/memberauthentication/facebooklogin/?AuthToken="+response.authResponse.accessToken+"&RedirectTo=/";
}

//function facebookLogout() {
//	FB.logout(function(response) {
//	});
//}

function miniBasketInit() {
//	$.get('/ShopPurchase/Basket/MiniBasketAjax/',
//		function(data) {
//			$('.miniBasket').html(data.MiniBasketHtml);
//			$("div.miniBasket input.spin-button").SpinButton({ min: 1 });
//			setupIframePopups();
//		}
//	);
}

//Share box overlay
function ShareDropDown() {

	$(".share > a").click(function(e) {
		e.preventDefault();
		$(this).next('div').toggle();
		$(".share").toggleClass("openDropDown");
	});

	$(".share .dropDownContent").mouseup(function() {
		return false;
	});

	$(document).mouseup(function(e) {
		if ($(e.target).parent(".share").length == 0) {
			$(".share").removeClass("openDropDown");
			$(".share .dropDownContent").hide();
		}
	});

	$(".dropDownContent .close").click(function(e) {
		e.preventDefault();
		$(".share").removeClass("openDropDown");
		$(".dropDownContent").hide();
	});

	$(".addthis_button_expanded").click(function() {
		$(".share .dropDownContent").hide();
		$(".share").removeClass("openDropDown");
	});
}

//Main nav drop down
function DropDownMenu() {

	var display_timeout = 0;

	var showTimer = null;

	$("li.has-subnav").hover(
		function() {

			$("li.has-subnav").removeClass('subnav-active');
			if (display_timeout != 0) { clearTimeout(display_timeout); }

			var this_element = this;
			showTimer = setTimeout(function() {
				$(this_element).addClass('subnav-active');
			}, 300);

		},
	function() {

		if (display_timeout != 0) { clearTimeout(display_timeout); }
		var this_element = this;

		display_timeout = setTimeout(function() {
			display_timeout = 0;
			$(this_element).removeClass('subnav-active');
		}, 500);

		if (showTimer != null) {
			clearTimeout(showTimer);
		}

	}
	);

}

//Edit User Details - Accordion of forms
function UserDetailFormAccordion() {

	var fieldsets = $('fieldset.userDetailFieldset');

	fieldsets.each(function(index) {

		if ($(this).find('.alert').length == 0 && $(this).parent().prev().hasClass('alert') == false) {

			$(this).children('h2').css('cursor', 'pointer').next().hide();

			$("h2 a", this).click(function(e) {

				e.preventDefault();

				var elToShow = $(this).parent().next();

				if (elToShow.css("display") == "none") {

					hideOtherUserDetailsAccordions(fieldsets, index);
					elToShow.show('slow');

				}

			});

			$("h2 a", this).focus(function() {

				var elToShow = $(this).parent().next();

				if (elToShow.css("display") == "none") {

					hideOtherUserDetailsAccordions(fieldsets, index);
					elToShow.show('slow');

				}

			});

		}

	});
}

function hideOtherUserDetailsAccordions(fieldsets, indexToIgnore) {

	fieldsets.each(function(index) {

		if (index != indexToIgnore) {

			$("h2", this).next().hide("slow");

		}

	});

}

$(window).load(function() {
	resizeContentHeight();
})

function resizeContentHeight() {
	//Set content Height
	var bannerHeight = $('#bannerWrap').outerHeight();
	var heightToSet = $('#contentWrap').outerHeight() - $('#pageLinks').outerHeight() - $('#contentFoot').outerHeight() - 25 - bannerHeight;

	if (heightToSet < $('#sideCol').outerHeight()) {
		$('#content').height(heightToSet);
	}
	else {
		$('#content').height('auto');
	}
}

//Mini Basket drop down
function DropDownBasket() {

	var display_timeout = 0;
	$(".miniBasket.hasItems").hover(function() {
		$(".miniBasket.hasItems").removeClass('basket-active');
		if (display_timeout != 0) { clearTimeout(display_timeout); }
		var this_element = this;
		$(this_element).addClass('basket-active');
	},
	function() {
		if (display_timeout != 0) { clearTimeout(display_timeout); }
		var this_element = this;
		display_timeout = setTimeout(function() {
			display_timeout = 0;
			$(this_element).removeClass('basket-active');
		}, 500);
	}
	);
}

//Setup minibasket to use AJAX where script-enabled (falls back to postback).
function BasketAjax() {
	$('div.miniBasket a.remove').click(function() {
		$.get($(this).attr('href') + '&ajax=true', function(data) {
			$('div.miniBasket').html(data.MiniBasketHtml);
			$('div.miniBasket input').customInput();
			$("div.miniBasket input.spin-button").SpinButton({ min: 1 });
			setupIframePopups();
			BasketAjax();
		});
		return false;
	});
	$('#miniBasketForm').submit(function() {
		$.post($(this).attr('action') + '?ajax=true', $(this).serialize(), function(data) {
			$('div.miniBasket').html(data.MiniBasketHtml);
			$('div.miniBasket input').customInput();
			$("div.miniBasket input.spin-button").SpinButton({ min: 1 });
			setupIframePopups();
			BasketAjax();
		});
		return false;
	});
}

function SmoothScroll() {
	if ($(".scrollTo")) {
		var target = $(".scrollTo");
		if (target.length) {
			var offset = target.offset().top;
			$("html,body").animate({ scrollTop: offset }, 1000);
		}
	}


	$('.scroll').click(function() {
		if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
	  && location.hostname == this.hostname) {
			var $target = $(this.hash);
			$target = $target.length && $target
		|| $('[name=' + this.hash.slice(1) + ']');
			if ($target.length) {
				var targetOffset = $target.offset().top;
				$('html,body')
		  .animate({ scrollTop: targetOffset }, 1000);
				return false;
			}
		}
	});
}

function Accordian() {
	var togglers = $('');
	var elements = "";
	$(elements).hide();
	togglers.click(
	function() {
		var checkElement = $(this).next();
		if ((checkElement.is(elements)) && (checkElement.is(':visible'))) {
			checkElement.slideUp(500);
			return false;
		}
		if ((checkElement.is(elements)) && (!checkElement.is(':visible'))) {
			$(elements + ':visible').slideUp(500);
			checkElement.slideDown(500);
			return false;
		}
	});
}

function UpdatePostageOption(postageBandID) {
	$.ajax(
	{
		url: "/ShopPurchase/Checkout/UpdatePostageAjax/",
		type: "POST",
		data: { "PostageBandID": postageBandID },
		success: function(data) {
			if (data.PaymentSummaryHtml) {
				$('#paymentSummaryValues').replaceWith(data.PaymentSummaryHtml);
			}
		}
	});
}

$(document).ready(function() {

	//Set content Height
	var bannerHeight = $('#bannerWrap').outerHeight();
	$('#content').height($('#contentWrap').outerHeight() - $('#pageLinks').outerHeight() - $('#contentFoot').outerHeight() - 25 - bannerHeight);

	$("#ratingWrapper").stars({
		captionEl: $("#ratingCaption"),
		inputType: "select",
		split: 2
	});

	//Check postage options ajax
	if ($('#PostageBandID') && $('#setPostageBand')) {
		$('#setPostageBand').hide();

		$('#PostageBandID').change(function() {
			UpdatePostageOption($(this).val())
		});
	}

	//Accordian();

	/********************************************************************/
	/*                             Form stuff                           */
	/********************************************************************/

	$('input').customInput();
	$("input.spin-button").SpinButton({ min: 1 });

	var volatile = $("input[type='text'], textarea")
	volatile.focus(function(event) {
		if ($(this).val() == $(this).attr("title")) {
			$(this).val("");
		}
	}, volatile.blur(function(event) {
		if ($(this).val() == "") {
			$(this).val($(this).attr("title"));
		}
	}
    ));

	/********************************************************************/
	/*                            Dialog stuff                          */
	/********************************************************************/

	$(function() {
		$("#CompetitionTerms").dialog({
			zIndex: 9000,
			autoOpen: false,
			modal: true,
			width: 500,
			height: 500
		});

		$("a.termsOpener").click(function() {
			$("#CompetitionTerms").dialog("open");
			return false;
		});
	});

	$(function() {
		$("#addAddress").dialog({
			autoOpen: false,
			height: 500,
			width: 600,
			zIndex: 1000,
			modal: true
		});

		$(".addAddress").click(function() {
			$("#addAddress").dialog("open");
			return false;
		});
	});

	$(function() {
		$("#searchTips").dialog({
			zIndex: 9000,
			autoOpen: false,
			modal: true,
			resizable: false
		});

		$("#searchOpener").click(function() {
			$("#searchTips").dialog("open");
			return false;
		});
	});

	$(function() {
		$("#postTips").dialog({
			zIndex: 9000,
			autoOpen: false,
			width: 580,
			modal: true,
			resizable: false
		});

		$("#postOpener").click(function() {
			$("#postTips").dialog("open");
			return false;
		});
	});

	$(function() {
		$("#postageTips").dialog({
			zIndex: 9000,
			autoOpen: false,
			modal: true,
			resizable: false
		});

		$(".postageOpener").click(function() {
			$("#postageTips").dialog("open");
			return false;
		});
	});

	$(function() {
		$(".helpTips").dialog({
			zIndex: 9000,
			autoOpen: false,
			width: 700,
			modal: false
		});

		$(".helpOpener").click(function() {
			$(".helpTips").dialog("open");
			return false;
		});
	});

	$(function() {

		$("#basketTips").dialog({
			zIndex: 9000,
			autoOpen: false,
			modal: true,
			buttons: {
				"Continue Shopping": function() {
					$(this).dialog("close");
				},
				"Go to basket": function() {
					window.location.href = "/basket/";
				}
			}
		});

		$(".basketOpener").click(function() {
			$("#basketTips").dialog("open");
			return false;
		});
	});

	$(function() {
		$(".productImage").dialog({
			zIndex: 9000,
			autoOpen: false,
			modal: true,
			width: 800
		});
		$(".productVideo").dialog({
			zIndex: 9000,
			autoOpen: false,
			modal: true,
			width: 640
		});
		$(".wishlistHelp").dialog({
			zIndex: 9000,
			autoOpen: false,
			modal: true,
			width: 300,
			resizable: false,
			title: 'Add to Wishlist'
		});
		$(".reminderHelp").dialog({
			zIndex: 9000,
			autoOpen: false,
			modal: true,
			width: 300,
			resizable: false,
			title: 'Add to a Reminder'
		});
		$(".sendToFriendHelp").dialog({
			zIndex: 9000,
			autoOpen: false,
			modal: true,
			width: 300,
			resizable: false,
			title: 'Send to a Friend'
		});
		$(".wishlistHelpOpener").click(function() {
			$(".wishlistHelp").dialog("open");
			return false;
		});
		$(".reminderHelpOpener").click(function() {
			$(".reminderHelp").dialog("open");
			return false;
		});
		$(".sendToFriendHelpOpener").click(function() {
			$(".sendToFriendHelp").dialog("open");
			return false;
		});

	});

	UserDetailFormAccordion();

	//Iframe
	setupIframePopups();

	SmoothScroll();
	ShareDropDown();
	miniBasketInit();
	DropDownMenu();
	DropDownBasket();

	BasketAjax();
	setupChooseSetFormAjax()
	
	$(".withoutJavascript").css("display", "none");
	$(".withJavascript").css("display", "block");
	$(".selectLanguage .monoBasic, .selectLanguage label").css("position", "absolute");
	$(".selectLanguage .monoBasic, .selectLanguage label").css("margin-left", "-9999px");

	$("a[rel*='external']").attr({ target: "_blank" });

	/********************************************************************/
	/*                     Banners and Carousels stuff                  */
	/********************************************************************/

	$('#bannerSlider').codaSlider({
		autoSlide: true,
		autoSlideInterval: 5000,
		dynamicArrows: false,
		dynamicTabs: false
	});

	$('#homeCarousel').hoverscroll({
		vertical: false,
		width: 770,
		height: 150,
		arrows: true,
		arrowsOpacity: 1,
		debug: false
	});

	$('#contentCarousel').hoverscroll({
		vertical: false,
		width: 730,
		height: 150,
		arrows: true,
		arrowsOpacity: 1,
		debug: false
	});

	$('.productCarousel').hoverscroll({
		vertical: true,
		width: 340,
		height: 380,
		arrows: true,
		arrowsOpacity: 1,
		debug: false
	});

	$('.slideShow').cycle({
		delay: 2000,
		speed: 1000,
		pager: '#SliderNav ul',
		pagerAnchorBuilder: paginate,
		slideExpr: 'li',
		pause: 1
	})

	function paginate(ind, el) {
		var bannerLength = $('.slideShow li').size();
		var percWidth = 760 / bannerLength;
		var lastWidth = 100 / bannerLength;

		//lastWidth = 760 / lastWidth

		if (ind == 0) {
			return '<li class="first" style="width:' + percWidth + 'px"><a href="#">Slide ' + (ind + 1) + ' of ' + bannerLength + '</a></li>'
		} else if (ind + 1 == bannerLength) {
			return '<li class="last" style="width:' + (percWidth - 1) + 'px"><a href="#">Slide ' + (ind + 1) + ' of ' + bannerLength + '</a></li>'
		} else {
			return '<li style="width:' + percWidth + 'px"><a href="#">Slide ' + (ind + 1) + ' of ' + bannerLength + '</a></li>'
		}
	}

	/* Maps */
	var location = $('#stockistMap').attr('title');
	$('#stockistMap').flash({
		src: '/_images/flash/stockists/map.swf',
		width: 500,
		height: 340,
		WMODE: 'transparent',
		flashvars: { defaultColor: '0xe8262d', hoverColor: '0xff9a18', selected: location }
	})

	/*Lightbox*/

	$(".lightbox").each(function() {
		$(this).ariaLightbox({
			pos: "auto",
			em: false,
			zIndex: "9999",
			titleText: getLightboxTitle(this),
			makeHover: false,
			descText: function() {
				return $(this).find("img").attr("alt");
			}
		});
	});

	function getLightboxTitle(link) {
		var img = $(link);
		return (img.attr("title")) ? img.attr("title") : '&nbsp;';
	}

	$('ul.additionalImages li a').click(function(e) {

		e.preventDefault();

		var MainImage = $('#contentOpener')

		var newImage = $(this).attr('rev');
		var newThumb = $(this).attr('href');
		var newTitle = $(this).attr('title');

		if ($(this).hasClass('video')) {
			MainImage.removeClass('image');
			MainImage.addClass('video');
		} else {
			MainImage.removeClass('video');
			MainImage.addClass('image');
		}

		MainImage.children('img').attr('src', newThumb);

		MainImage.attr('href', newImage);
		MainImage.attr('title', newTitle);

	});

	$("#contentOpener").click(function(e) {

		e.preventDefault();

		if ($(this).hasClass("video")) {
			displayProductVideo($(this));
		} else {
			displayProductImage($(this));
		}

	});

	function displayProductImage(el) {

		var width = 820;
		var height = 560;
		var title = el.attr("title") + ' - Use your mouse wheel to zoom.';
		var url = el.attr("href");

		displayProductGalleryPopup(url, title, width, height);

	}

	function displayProductVideo(el) {

		var width = 641;
		var height = 423;
		var title = el.attr("title");
		var url = el.attr("href");

		displayProductGalleryPopup(url, title, width, height);

	}

	function displayProductGalleryPopup(url, title, width, height) {

		$('<div id="ProductGalleryDialog"><iframe class="externalSite" width="100%" height="100%" frameborder="0" src="' + url + '" /></div>').dialog({
			title: title,
			width: width,
			height: height,
			zIndex: 2000,
			close: function(event, ui) {
				$(".ui-widget-overlay").remove();
				$(this).dialog("destroy");
				$(".externalSite").remove();
			},
			resizable: false
		});

		$(".ui-dialog").has('iframe').before('<div class="ui-widget-overlay"></div>');

		function dialogOverlayResize() { $(".ui-widget-overlay").css("height", $(document.body).height() + "px").css("width", $(document.body).width() + "px").css("z-index", "1001"); }

		$(window).resize(function() { dialogOverlayResize(); });
		dialogOverlayResize();

	}

	//the select box will ajax update the product price instead
	$("a#UpdateProductPrice").hide();

	$("select#SkuID").change(function(e) {
		updateProductPrice();
	});

	function updateProductPrice() {

		var skuID = $("#SkuID").val();

		$.getJSON('/shops/getskuprice/?SkuID=' + skuID, function(data) {

			if (data.Status = "Successful") {
				$(".price .current .value").html(data.Prices.PriceInc);
			}


		});
	}

	$(".addToBasketForm").submit(function(e) {

		e.preventDefault();

		$.ajax({
			url: $(this).attr("action") + "?ajax=true",
			type: "post",
			data: $(this).serialize(),
			dataType: "json",
			success: function(data) {
				$(".miniBasket").html(data.MiniBasketHtml);
				//$("#basketTips").dialog("open");
				$("div.miniBasket input.spin-button").SpinButton({ min: 1 });
				displayBasketBubble(data.BasketErrors);
				BasketAjax();
			}
		});

	});

	$("a.addToBasket").click(function(e) {

		e.preventDefault();

		$.ajax({
			url: $(this).attr("href") + "&ajax=true",
			type: "post",
			data: $(this).serialize(),
			dataType: "json",
			success: function(data) {

				$(".miniBasket").html(data.MiniBasketHtml);
				//$("#basketTips").dialog("open");
				displayBasketBubble(data.BasketErrors);
				BasketAjax();
			}
		});

	});

	$("#basketBubble .hide").live("click", function() {
		$("#basketBubble").hide();
	});

	InitAutocompleteForms();

	$(".stockistsByArea select").change(function(e) {

		$(".stockistsByArea").submit();

	});

	$("form.checkoutForm div.address a").click(function(e) {
		e.preventDefault();
		var anchor = $(this);
		var parentFieldset = anchor.parents("fieldset.club");
		saveClubMembershipDetails(parentFieldset, anchor.attr("href"));
	});

	$(".collectorsClub tbody tr").each(function() {

		var trEl = $(this);

		var optionType = $("select", trEl);

		optionType.change(function(e) {
			toggleClubMembershipType($(this).val(), trEl);
		});

		toggleClubMembershipType(optionType.val(), trEl);

	});

	$(".club .membershipFor select").change(toggleClubMembershipFor);
	toggleClubMembershipFor();

	PreviewFields();
	ProductInformationTabs();

	$("#homeCarousel li img").each(function() {

		var title = $(this).parent().attr("title");
		var price = $("span.price", $(this).parents("li")).text();
		var code = $("span.code", $(this).parents("li")).text();
		var content = "<div><div class='tool-title'><span>" + title + "</span></div><div class='tool-text'><span>" + code + "<br/>" + price + "</span></div></div>";

		$(this).simpletip({ content: content, fixed: false, offset: [10, 10], position: "right" });

		$(this).parent().attr("title", "");

	});

	$("#CreateGiftVoucher .field .help").each(function() {

		var title = $(this).siblings('label').text();
		var body = $(this).attr('title');
		var content = "<div><div class='tool-title'><span>" + title + "</span></div><div class='tool-text'><span>" + body + "</span></div></div>";

		$(this).simpletip({ content: content, fixed: false, offset: [10, 10], position: "right" });

		$(this).attr("title", "");

	});
	if (mySettings) {
		$("textarea.bbcode").markItUp(mySettings);
	}

	$(".helpfulReview").each(function() {

		var hrSection = $(this);

		var reviewId = hrSection.attr("rel");

		$("a.yes", hrSection).click(function(e) {
			e.preventDefault();
			makeHelpfulReviewSelection(reviewId, true, hrSection);
		});

		$("a.no", hrSection).click(function(e) {
			e.preventDefault();
			makeHelpfulReviewSelection(reviewId, false, hrSection);
		});

	});

	function makeHelpfulReviewSelection(reviewId, isUseful, hrSection) {

		var urlData = {
			"ProductReviewID": reviewId
		};

		if (isUseful) {
			urlData.IsUseful = "1";
		} else {
			urlData.IsUseful = "0";
		}

		$.ajax({
			url: "/ProductReviews/MakeUsefulSelection/",
			dataType: "json",
			type: "get",
			data: urlData,
			success: function(data) {
				updateHelpfulReviewCounts(parseInt(data.HelpfulCount), parseInt(data.NotHelpfulCount), hrSection);
			}
		});

	}

	function updateHelpfulReviewCounts(helpfulCount, notHelpfulCount, hrSection) {

		$(".helpfulSummary", hrSection).css("display", "inline");

		$(".helpful", hrSection).html(helpfulCount);
		$(".notHelpful", hrSection).html(notHelpfulCount + helpfulCount);

	}

	$("#CreateGiftVoucher #DeliveryType").change(toggleGiftVoucherType);

	function toggleGiftVoucherType() {

		var deliveryType = $("#CreateGiftVoucher #DeliveryType").val();

		if (deliveryType == "Email") {
			$("#fieldwrapper_RecipientsEmail").show();
			$("#fieldwrapper_ConfirmRecipientsEmail").show();
			$("#fieldwrapper_DispatchDate").show();
		} else {
			$("#fieldwrapper_RecipientsEmail").hide();
			$("#fieldwrapper_ConfirmRecipientsEmail").hide();
			$("#fieldwrapper_DispatchDate").hide();
		}

	}

	toggleGiftVoucherType();

	$("#CreateGiftVoucher .voucherPreview a").click(function(e) {

		e.preventDefault();

		var formData = $("#CreateGiftVoucher").serialize();

		$.ajax({
			url: "/giftvouchers/preview/",
			type: "POST",
			data: formData,
			success: function(html) {

				DisplayDialog(html, 700, 550, "Gift Voucher Preview");

			}
		});

	});

	$(".characterCount").each(function() {

		var charCount = $(this);
		var fieldId = charCount.attr("rel");
		var maxChars = charCount.attr("rev");

		$("#" + fieldId).keypress(function() {
			updateCharacterCount(charCount, $(this), maxChars);
		});

		updateCharacterCount(charCount, $("#" + fieldId), maxChars);

	});

	function updateCharacterCount(counter, field, maxChars) {

		var currentLength = field.val().length;
		var remaining = maxChars - currentLength;

		counter.html("<strong>" + remaining + "</strong> characters remaining");

	}
	
	if ($("#trackselector")) {

		$("#trackselector").flash({
			src: '/_images/flash/track-selector.swf',
			width: 610,
			height: 609,
			WMODE: 'transparent',
			flashvars: { trackselector: 'false' }
		});

	}

	initializePrettyDropBoxes();
	initializeHornbyVariantToggle();

});

function initializeHornbyVariantToggle() {

	$("#changeHornbyVariant").change(function(e) {

		var uri = $(this).val();

		window.location.href = uri;

	});

}

function initializePrettyDropBoxes() {

	$('#masthead .select select').selectmenu({
		style: 'dropdown',
		width: '128px',
		icons: [
			{ find: '.english' },
			{ find: '.french' },
			{ find: '.german' },
			{ find: '.italian' }
		]
	});

	var selectBoxWidth;

	if ($('#content .searchForumCategory .select select').size() > 0) {
		selectBoxWidth = '150px';
	} else {
		selectBoxWidth = '298px';
	}

	$('#content .checkoutForm .select select').selectmenu({
		style: 'dropdown',
		width: '350px',
		maxHeight: 200
	});

//	$('#content .contact:not(#CompetitionEntry) .select:not(.rating) select').selectmenu({
	$('#content .contact .select:not(.rating) select').selectmenu({
		style: 'dropdown',
		width: selectBoxWidth,
		maxHeight: 200
	});

	$('#content .sortBy .select select, .productDetailsForm .select select, .refine .select select').selectmenu({
		style: 'dropdown',
		width: '200px',
		maxHeight: 200
	});

	$('#content .productOptions select, .productDetailsForm .quantity select').selectmenu({
		style: 'dropdown',
		width: '50px',
		maxHeight: 200
	});

	$('.dateSelect select').selectmenu({ style: 'dropdown', width: '75px', maxHeight: 200 });

	$('.dateSelectWide select').selectmenu({ style: 'dropdown', width: '75px', maxHeight: 200 });

	$('.chooseASet select').selectmenu({ style: 'dropdown', width: '180px', maxHeight: 200 });

	$('.collectorsClub select').selectmenu({ style: 'dropdown', width: '80px', maxHeight: 200 });

	$('.stockistsByArea select').selectmenu({ style: 'dropdown', width: '200px', maxHeight: 200 });

	$('.membershipFor select').selectmenu({ style: 'dropdown', width: '239px', maxHeight: 200 });

	$('.manage select').selectmenu({ style: 'dropdown', width: '160px', maxHeight: 200 });

}

function DisplayDialog(html, width, height, title) {

	$('<div>' + html + '</div>').dialog({
		title: title,
		width: width + 'px',
		height: height,
		resizable: false,
		zIndex: 2000,
		close: function(event, ui) {
			$(".ui-widget-overlay").remove();
			$(this).dialog("destroy");
		}
	});

	$(".ui-dialog").before('<div class="ui-widget-overlay"></div>');

	function dialogOverlayResize() { $(".ui-widget-overlay").css("height", $(document.body).height() + "px").css("width", $(document.body).width() + "px").css("z-index", "1001"); }

	$(window).resize(function() { dialogOverlayResize(); });
	dialogOverlayResize();

}

function InitAutocompleteForms() {
	if ($('form.autocomplete').length > 0) {

		$.getJSON('/formautocomplete/formautocomplete/memberinfo/', function(data) {
			if (data != null && data.Status == "Success") {
				$('form.autocomplete').each(function() {
					var form = $(this);
					form.find('input[name=FirstName]').val(data.FirstName);
					form.find('input[name=LastName]').val(data.LastName);
					form.find('input[name=EmailAddress]').val(data.EmailAddress);
					form.find('input[name=TelephoneNumber]').val(data.TelephoneNumber);
					form.find('textarea[name=Address]').val(data.Address);
				});
			}
		});
	}

}

function toggleClubMembershipType(optionType, tableRow) {

	var addButton = $(".clubAdd", tableRow);
	var addWithMembershipButton = $(".clubAddMembershipNumber", tableRow);

	if (optionType == "Renew") {
		addButton.hide();
		addWithMembershipButton.show();
	} else {
		addButton.show();
		addWithMembershipButton.hide();
	}

}

function toggleClubMembershipFor() {

	var membershipFor = $(".club .membershipFor select").val();
	var emailHolder = $(".club #ClubDetailsEmail").parent();

	if (membershipFor == "Myself") {
		emailHolder.hide();
	} else {
		emailHolder.show();
	}

}

function PreviewFields() {

	$("a.previewDelete").click(function(e) {
		e.preventDefault();
		var preview = $(this).parents("ul.previewPhoto");
		preview.hide();
		$("input[type=hidden]:first", preview).val("");
	});

}

function ProductInformationTabs() {

	var tabs = $("#productTabs .tabs a");
	var tabContents = $(".tabContent");

	tabContents.css("display", "none");

	$(".tabContent.selected").css("display", "block");

	tabs.click(function(e) {

		if ((!$(this).parent().hasClass("noReviews") && !$(this).parent().hasClass("reviews")) || $(".tabContent.reviews").length > 0) {

			e.preventDefault();

			var index = $.inArray(this, tabs);

			tabContents.css("display", "none");
			$(tabContents.get(index)).css("display", "block");

			tabs.each(function() {
				$(this).parent().removeClass("selected");
			});

			$(this).parent().addClass("selected");

		}

	});

}

function displayBasketBubble(errors) {
	var basketBubble = $("#basketBubble");
	var message = basketBubble.children('p.message');
	var errorMessage = basketBubble.children('p.error');

	if (errors) {
		if (errors.length > 0) {
			message.hide();
			errorMessage.text(errors[0]);
			errorMessage.show();
		}
		else {
			message.show();
			errorMessage.hide();
		}
	}
	else {
		message.show();
		errorMessage.hide();
	}

	basketBubble.show();
	var miniBasket = $(".miniBasket");
	if (miniBasket.length > 0) {
		var targetOffset = miniBasket[0].offsetTop;
		$('html,body').animate({ scrollTop: targetOffset }, 500);
	}
}

function setupIframePopups() {
	$('.iframe').click(function(e) {
		e.preventDefault();
		var $this = $(this);
		if ($this.attr('rel')) {
			var dialogDimensions = $this.attr('rel').split("x");
			var dialogWidth = dialogDimensions[0]
			var dialogHeight = dialogDimensions[1]
		}
		else {
			var dialogWidth = 728
			var dialogHeight = 500
		}
		if ($('.productLists').length > 0) { dialogWidth = 590; }
		var href = this.href;
		if (href.indexOf('popup=true') < 0) {
			if (href.indexOf('?') < 0)
				href += '?popup=True';
			else
				href += '&popup=True';
		}
		$('<div><iframe class="externalSite" width="100%" height="100%" frameborder="0" src="' + href + '" /></div>').dialog({
			title: ($this.attr('title')) ? $this.attr('title') : 'External Site',
			width: dialogWidth + 'px',
			height: dialogHeight,
			resizable: !($this.hasClass('noresize')),
			zIndex: 2000,
			close: function(event, ui) {
				$(".ui-widget-overlay").remove();
				$(this).dialog("destroy");
				$(".externalSite").remove();
			}
		});
		$(".ui-dialog").has('iframe').before('<div class="ui-widget-overlay"></div>');
		function dialogOverlayResize() { $(".ui-widget-overlay").css("height", $(document.body).height() + "px").css("width", $(document.body).width() + "px").css("z-index", "1001"); }
		$(window).resize(function() { dialogOverlayResize(); });
		dialogOverlayResize();
	});
}

function saveClubMembershipDetails(clubMembershipFieldset, redirectAfterUrl) {

	var clubDetailsFor = $("select#ClubDetailsFor", clubMembershipFieldset).val();
	var clubDetailsEmail = $("input#ClubDetailsEmail", clubMembershipFieldset).val();
	var clubDetailsTelephone = $("input#ClubDetailsTelephone", clubMembershipFieldset).val();
	var clubDetailsDOB_Day = $("select#ClubDetailsDOB_Day", clubMembershipFieldset).val();
	var clubDetailsDOB_Month = $("select#ClubDetailsDOB_Month", clubMembershipFieldset).val();
	var clubDetailsDOB_Year = $("select#ClubDetailsDOB_Year", clubMembershipFieldset).val();


	$.post("/ClubMembership/Ajax/AddClubDetailsToBasket/",
			{
				ClubDetailsFor: clubDetailsFor,
				ClubDetailsEmail: clubDetailsEmail,
				ClubDetailsTelephone: clubDetailsTelephone,
				ClubDetailsDOB_Day: clubDetailsDOB_Day,
				ClubDetailsDOB_Month: clubDetailsDOB_Month,
				ClubDetailsDOB_Year: clubDetailsDOB_Year
			}, function() {
				window.location = redirectAfterUrl;
			});

}

function setupChooseSetFormAjax() {
    var replaced = $('ul.productList');
    var theform = $('form.chooseASet');

    $.each(["#PriceTo", "#PriceFrom", "#AgeGroup", ".chooseASet input:checkbox"], function(index, selector) {
        $(selector).change(function(e) {
            $.ajax({
                type: 'POST',
                url: "/Shops/SetSearch/SetSearchResults/?ajax=true",
                data: theform.serialize(),
                success: function(postData) {
                    replaced.html(postData);
                }
            });
        });
    });

    theform.submit(function(e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: "/Shops/SetSearch/SetSearchResults/?ajax=true",
            data: theform.serialize(),
            success: function(postData) {
                replaced.html(postData);
                setupChooseSetFormAjax();
            }
        });
        return false;
    });
}
