var addthis_pub = "";

var FancyTips = new Class({
	initialize: function (elements, options) {
		this.setOptions({
			"tipcontents": ".tipcontents"
		},options);
		
		elements.each(function (element) {
			contents_element = element.getElement(this.options.tipcontents);
			if (contents_element) {
				var currentTitle = element.getProperty("title");
				element.setProperty("title", currentTitle + " :: " + contents_element.innerHTML);
			}
		}, this);
		
		this.tips = new Tips(elements, options);
	}
});
FancyTips.implement(new Options);

window.addEvent("domready", function(){
  			 
	new SmoothScroll({"links": $$(".scroll")});
	
	new FancyTips($$(".homeaccordian ul a, .productspec li, ul.productaccordian ul.icons li, .productspec .car, .productspec .code, .productspec .gear, .helptip a, ul.selectoptions li a"), {
		"tipcontents":"span",
		"maxTitleChars": 100,
		"offsets":{ "x":15, "y":-70 }
	});
	
	var blogLink = $("blogLink");

	if(blogLink) {
		var customLink = new Fx.Slide("blogcommentlist",{ "duration":800, "transition": Fx.Transitions.Expo.easeOut });
		customLink.hide();
		blogLink.addEvent("click", function(e){
			new Event(e).stop();
			customLink.toggle();

			if(blogLink.hasClass("expand")){
				blogLink.removeClass("expand").addClass("collapse");
			} else {
				blogLink.removeClass("collapse").addClass("expand");
			}
			
		});
	}



	$$(".purchaseproduct .pricespinner").each(function(fs){
		var spinner = fs.getElement(".spinner");
		if(spinner){
			new MooSpinner(spinner,{
				"increment": fs.getElement(".add"),
				"decrement": fs.getElement(".subtract"),
				"minimum": 1,
				"maximum": 999
			});
		}
	});

	$$("#guidedsearch .pricespinner").each(function(fs){
		var spinner = fs.getElement(".spinner");
		if(spinner){
			new MooSpinner(spinner,{
				"increment": fs.getElement(".add"),
				"decrement": fs.getElement(".subtract"),
				"minimum": 0,
				"maximum": 300,
				"incrementAmount": 10
			});
		}
	});

	$$(".associatedoffers .groups").each(function(el){
		var toggler = el.getElement(".expand");
		if(toggler){
			var slide = new Fx.Slide(el.getElement("div"),{"duration":350, "wait": false}).hide();
			toggler.addEvent("click", function(e){
				new Event(e).stop();
				if(this.hasClass("expand")){
					this.removeClass("expand").addClass("collapse");
					slide.slideIn();
				} else {
					this.removeClass("collapse").addClass("expand");
					slide.slideOut();
				}
			});
			
		}
	});

});

var Scalextric = {
	
	initialize: function(){
		
		Scalextric.initializeExternalLinks();
		Scalextric.initializeVolatileFields();
		Scalextric.setSearch.initialize();
		Scalextric.navigation.configure();
		Scalextric.initializeMessageWindow();
		Scalextric.initializeAddToBasket();
		Scalextric.initializeAddToWishList();
		Scalextric.initializeAddThisLinks();
		Scalextric.initializeProductInfo();		
		Scalextric.initializeGenericCarousel();	
		Scalextric.initializeSortBy();
		Scalextric.initializeProductGallery();
		Scalextric.initializeMiniBasket(true);
		Scalextric.initializePredictiveSearch();
		Scalextric.initializeCheckoutSummary();
		
	},
	
	setSearch: {
		
		// Function which initializes the set search, will be called after AJAX to reinitialize the new HTML
		initialize: function() {
			
			// Configure the track selector flash
			if ($("trackselector")) {
				window.addEvent("domready", function(){
					var fo2 = new FlashObject("/_flash/track-selector.swf", "viewer", "610", "609", "8");
					fo2.addParam("trackselector","false");
					fo2.addParam("quality","high");
					fo2.addParam("WMODE","transparent");
					fo2.write("trackselector");
				});
			}
			
			// Configure the guided set search
			if ($("guidedsearch")){
				
				$$("#guidedsearch select").each(function(el){
					el.addEvent("change", Scalextric.setSearch.refresh);
				});
				
				$$("#guidedsearch input").each(function(el){
					el.addEvent("click", Scalextric.setSearch.refresh);
				});
				
				$("resetPriceRange").addEvent("click", Scalextric.setSearch.resetPriceRange);
				
			}
			
		},
		
		// Function which posts the set search via AJAX and updates the results
		refresh: function(){
		
			var stopForm = new MessageWindow();
			
			stopForm.show("Processing...");
			
			new Ajax("/product-directory/ajax-set-search/",{
				data: $("guidedsearch"),
				onComplete: function(response){
					$("ajax-wrapper").setHTML(response);
					Scalextric.setSearch.initialize();
					stopForm.hide();
				}
			}).request();
			
			return false;
			
		},
		
		resetPriceRange: function(){
			
			$("LowerPrice").selectedIndex = 0;
			$("UpperPrice").selectedIndex = 0;
			
			Scalextric.setSearch.refresh();
			
		}
		
	},
	
	initializeVolatileFields: function() {
			
		$$(".volatile").each(function(el){
			$(el).addEvent("focus", function(){
				if(this.getValue() == this.getProperty("title")) {
					this.value = "";
				}
			});
		});
		
	},
	
	initializeExternalLinks: function() {
		
		$$("a[rel*='external']").each(function(a){ 
			a.setProperty("target", "_blank");
		});
		
	},
	
	initializeCheckoutSummary: function() {
		
		$$(".addressbooksmall .smalladdresses").each(function(el){
			var toggler = el.getElement(".expand");
			if(toggler){
				var slide = new Fx.Slide(el.getElement("div"),{"duration":350, "wait": false}).hide();
				toggler.addEvent("click", function(e){
					new Event(e).stop();
					if(this.hasClass("expand")){
						this.removeClass("expand").addClass("collapse");
						slide.slideIn();
					} else {
						this.removeClass("collapse").addClass("expand");
						slide.slideOut();
					}
				});
				
			}
		});
		
	},
	
	initializeMessageWindow: function() {
		
		this.basketMessage = new MessageWindow({
			"timeout": 2500,
			"onShow": function(){ Scalextric.basketMessage.modalShow() },
			"onHide": function(){ Scalextric.basketMessage.modalHide() }
		});
		
	},
	
	initializeAddToBasket: function() {
		
		$$(".addtobasket").each(function(el){
			el.addEvent("click", function(e){
			
				new Event(e).stop();
				
				var productID = el.getProperty("id").substring(el.getProperty("id").indexOf("_") + 1);
				var quantity = $("ProductQuantity_" + productID).getProperty("value");
				
				new Ajax("/basket/ajax-add/",{
					data: {
						"ProductID": productID,
						"Quantity": quantity
					},
					onError: function(){
						Scalextric.basketMessage.show("There was a problem adding to your basket. Please try again.");
					},
					onComplete: function(response){
						$("minibasketcontainer").setHTML(response);
						Scalextric.basketMessage.show("Items were successfully added to your basket.");
						Scalextric.initializeMiniBasket(true);
					}
				}).request();
				
			});
		});
		
	},
	
	initializeAddToWishList: function() {
		
		$$(".addtowishlist").each(function(el){
			el.addEvent("click", function(e){
			
				new Event(e).stop();
				
				var productID = el.getProperty("id").substring(el.getProperty("id").indexOf("_") + 1);
				
				new Ajax("/members/wishlist-ajax-add/",{
					data: {
						"ProductID": productID
					},
					onError: function(){
						Scalextric.basketMessage.show("There was a problem adding to your wishlist.");
					},
					onComplete: function(response){
						Scalextric.basketMessage.show(response);
					}
				}).request();
				
			});
		});
		
	},
	
	initializeAddThisLinks: function() {
		
		// Configure all socialize links
		$$(".socialize").addEvent("click", function(e){
			new Event(e).stop();
			addthis_url = location.href;
			addthis_title = document.title;
			addthis_click(this);
		});
		
	},
	
	initializeProductInfo: function() {
		
		if($("productinfo")){
		
			var togglers = $$("#productinfo .tabs a");
			var elements = $$("#productinfo .productaccordian .section");
		
			togglers.addEvent("click", function(e){ 
				new Event(e).stop();
			});
			
			var productTabs = new Accordion(togglers, elements,{
				"onActive": function(tab){
					tab.addClass("selected");
					$$('.section').setStyle('overflow', 'auto');
				},
				"onBackground": function(tab){
					tab.removeClass("selected");
				},
				"alwaysHide": false,
				"transition": null,
				"duration": 0,
				"fixedHeight": 285
			});
			
			productTabs.display(0);
		
			$$('.section').setStyle('overflow', 'auto');
			
		}
		
	},
	
	initializeGenericCarousel: function() {
		
		// Generic code for carousels
		$$(".genericCarousel").each(function(el){
			
			var togglers = $ES(".toggler", el);
			
			togglers.addEvent("click", function(e){ 
				new Event(e).stop();
			});
			
			var carouselID = el.id;
			
			if (carouselID == "productcarousel") {
				var visibleItems = 2;
				var scrollAmount = 150;
			}
			
			if (carouselID == "genericcarousel") {
				var visibleItems = 2;
				var scrollAmount = 150;
			}
			
			if (carouselID == "imgGallery") {
				var visibleItems = 2;
				var scrollAmount = 210;
			}
			
			$ES(".items ul", el).each(function(elItem){
				new Carousel(elItem,{
					"autoStyle": true,
					"idPrevious": $ES(".prev", el)[0],
					"idNext": $ES(".next", el)[0],
					"visibleItems": visibleItems,
					"scrollAmount": scrollAmount,
					"scrollInterval": 350
				});
			});
			
		});
		
	},
	
	initializeSortBy: function() {
		
		$$(".sortby .formbutton").each(function(el){
		
			el.addEvent("mouseover", function(e){
		
			new Event(e).stop();
				this.setAttribute("src", "/_images/buttons/hover/go.gif");
			});
			
			el.addEvent("mouseout", function(e){
				new Event(e).stop();
				this.setAttribute("src", "/_images/buttons/go.gif");
			});
			
		});
		
	},
	
	initializeProductGallery: function() {
		
		$$(".productImgThumb").each(function(el){
			
			el.addEvent("click", function(e){
				
				new Event(e).stop();
				
				var selImage = el.getFirst();
				var largeLink = $("productImgMain");
				var largeImage = $ES(".mainproductimage", largeLink);
				var largeSpan = $ES("span", largeLink);
				
				var selImageSrc = selImage.getProperty("src");
				
				var selFilename = selImageSrc.substring(selImageSrc.lastIndexOf("/") + 1);
				var selName = selImage.getProperty("alt");
				
				// Set the large image properties
				largeImage.setProperty("src", "/_images/assets/product-directory/product-medium/" + selFilename);
				largeSpan.setStyle("background-image", "url('/_images/assets/product-directory/product-medium/" + selFilename + "')");
				largeImage.setProperty("alt", selName);
				
				// Set the large link properties
				largeLink.setProperty("href", "/_images/assets/product-directory/product-large/" + selFilename);
				largeLink.setProperty("title", selName);
				largeLink.setProperty("rel", "lightbox");
				
				Lightbox.init();
				
			});
			
		});
		
	},
	
	initializePredictiveSearch: function(){
		
		if($("q")){
			var mm = new MysticMeg($("q"), {
				"ajaxUrl":"/product-directory/predictive-search/",
				"listClass":"predictive",
				"leftOffset":-2,
				"topOffset": 25,
				"highlight":false,
				"multipleSelect":false,
				"onSelect": function(v, f, o){
					o.flush();
					o.hideResults();
					if(v.url != ""){
						window.location.href = v.url;
					}
				}				
			});
		}
		
	},
	
	initializeMiniBasket: function(boolClose){
		
		var viewMiniBasket = $("viewMiniBasket"); 
		
		if(viewMiniBasket) {
			
			var customLink = new Fx.Slide("miniBasketContent",{
				"duration": 1200, 
				"transition": Fx.Transitions.Bounce.easeOut,
				"onStart": function(){
					
					var miniBasketToggle = $("minibasket_toggle");
				
					if (miniBasketToggle.hasClass("expanded")) {
						
						miniBasketToggle.setAttribute("src", "/_images/buttons/view-all-items.gif");
						miniBasketToggle.removeClass("expanded")
						
					} else {
						
						miniBasketToggle.setAttribute("src", "/_images/buttons/close.gif");
						miniBasketToggle.addClass("expanded")
						
					}
					
				}
			});
			
			if(!$("ajaxreturn") && boolClose) {
				customLink.hide();
			}
			
			viewMiniBasket.addEvent("click", function(e){
				
				new Event(e).stop();
				customLink.toggle();
				
			});
			
			$$("a.removefrombasket").each(function(el){
				
				el.addEvent("click", function(e){
					
					new Event(e).stop();
				
					var productID = el.getProperty("id").substring(el.getProperty("id").indexOf("_") + 1);
					
					new Ajax("/basket/ajax-remove/",{
						data: {
							"ProductID": productID
						},
						onError: function(){
							Scalextric.basketMessage.show("There was a problem removing the item from your basket.");
						},
						onComplete: function(response){
							$("minibasketcontainer").setHTML(response);
							Scalextric.basketMessage.show("Items were successfully removed from your basket.");
							Scalextric.initializeMiniBasket(false);
						}
					}).request();
				
				});
				
			});
			
		}
		
		// Create a new multibox and assign it to the Scalextric object
		this.multibox = new MultiBox('multibox', {
			showControls:false,
			useOverlay:true
		});
		
		// Catch the close links for multibox popups
		$$(".multiboxClose").each(function(el){
			el.addEvent("click", function(e){
				new Event(e).stop();
				window.parent.Scalextric.multibox.close();
			});
		});		
	
		$$("#miniBasketContent fieldset").each(function(fs){
			var spinner = fs.getElement(".spinner");
			if(spinner){
				new MooSpinner(spinner,{
					"increment": fs.getElement(".add"),
					"decrement": fs.getElement(".subtract"),
					"minimum": 0,
					"maximum": 999
				});
			}
		});
		
		$$(".club-type-selector").each(function(el){
			
			el.addEvent("change", function(e){
				
				var pid = el.getProperty("id").substring(el.getProperty("id").indexOf("_") + 1);
				
				if (el.value == 'Renew') {
					$("MembershipDetails_" + pid).setStyle("display", "block");
					$("AddToBasket_" + pid).setStyle("display", "none");
				} else {
					$("AddToBasket_" + pid).setStyle("display", "block");
					$("MembershipDetails_" + pid).setStyle("display", "none");
				}
				
			});
			
		});
		
		var miniUpdate = $("miniupdate");
		
		if (miniUpdate) {
			miniUpdate.addEvent("click", function(e){
			
				new Event(e).stop();
				
				var miniForm = this;
				
				new Ajax("/basket/ajax-update/",{
					data: $("miniBasketForm"),
					onError: function(){
						Scalextric.basketMessage.show("There was a problem updating your basket. Please try again.");
					},
					onComplete: function(response){
						$("minibasketcontainer").setHTML(response);
						Scalextric.basketMessage.show("Your basket has been updated.");
						Scalextric.initializeMiniBasket(false);
					}
				}).request();
				
			});
		}
		
	},
	
	// Represents the navigation at the top of the Scalextric site
	navigation: {
		
		// Initial configuration of the navigation, must be called on DOM ready
		configure: function() {
			
			// Preload the hover images
			var images = [
				"/_images/template-backgrounds/masthead.jpg",
				"/_images/template-backgrounds/masthead-cars.jpg",
				"/_images/template-backgrounds/masthead-micro.jpg",
				"/_images/template-backgrounds/masthead-pit-lane.jpg", 
				"/_images/template-backgrounds/masthead-sets.jpg", 
				"/_images/template-backgrounds/masthead-track.jpg"
			];  
			
			var loader = new Asset.images(images);
			
			this.items = $$("#mastheadnav li");
			
			// Itterate all items in the navigation
			Scalextric.navigation.items.each(function(li){
				
				// Add the mouseover and mouseout events to the current item
				li.addEvents({
					"mouseover":function(){ Scalextric.navigation.beginHover(li); },
					"mouseout":function(){ Scalextric.navigation.endHover(li); }
				});
				
			});
			
			var templateColumns = $("templatecolumns");
			if (templateColumns) {
				templateColumns.addEvent("mouseout", function(){ Scalextric.navigation.hideAll() });
			}
			
		},
		
		// Method called when starting the hover event
		beginHover: function(li) {

			Scalextric.navigation.hideAll();
			
			li.addClass("sfhover");
			
			var mastheadOverlay = $("mastheadoverlay");
			
			if (li.hasClass("masthead_sets")) {
				mastheadOverlay.setStyle("background-image", "url(/_images/template-backgrounds/masthead-sets.jpg)");
			} else if (li.hasClass("masthead_cars")) {
				mastheadOverlay.setStyle("background-image", "url(/_images/template-backgrounds/masthead-cars.jpg)");
			} else if (li.hasClass("masthead_track")) {
				mastheadOverlay.setStyle("background-image", "url(/_images/template-backgrounds/masthead-track.jpg)");
			} else if (li.hasClass("masthead_pitlane")) {
				mastheadOverlay.setStyle("background-image", "url(/_images/template-backgrounds/masthead-pit-lane.jpg)");
			} else if (li.hasClass("masthead_micro")) {
				mastheadOverlay.setStyle("background-image", "url(/_images/template-backgrounds/masthead-micro.jpg)");
			}
			
		},
		
		// Method called when stopping the hover event
		endHover: function(li) {
			
			li.removeClass("sfhover");
			
			$("mastheadoverlay").setStyle("background-image", "");
			
		},
		
		hideAll: function() {
			
			// Make sure the hover class is removed from the previous item
			Scalextric.navigation.items.each(function(li){
				li.removeClass("sfhover");
			});
			
		}
		
	}
	
}

// Configure the scalextric website object
window.addEvent("domready", function(){
	Scalextric.initialize();
	//new AlphaPng();
});
