jQuery( "document" ).ready( function()
{
	if(location.hostname.indexOf('powakaddy.com') != -1)
	{
		document.domain = 'powakaddy.com';
	}

	PowaKaddy.setup();
	tb_loadImage();
});

var PowaKaddy = (function PowaKaddy()
{
	return {
		setup : function setup()
		{
			this.setupGeneral();
			this.setupSpecific();
		},
		
		// general functionality used across the site
		setupGeneral : function setupGeneral()
		{
			this.SITE_URL = INCLUDES_PATH.replace(/(.+)\/skin\/.*/, '$1')+'/';
			
			// hide class="noscript" items
			try	{
				jQuery(".noscript").hide();
			} catch(ex){}
			
			// open "class="new-window" links in new window
			try	{
				this.newWindows();
			} catch(ex){}
			
			// add form hints to text boxes
			try	{
				jQuery('input[type="text"][title!=""]').hint();
			} catch(ex){}
		},
		
		// feature-specific functionality
		setupSpecific : function setupSpecific()
		{
			// styling warranty page
			try	{
				this.warrantyListStyle();
			} catch(ex){}
			
			// news sign-up sliding area in header
			try	{
				this.headerSignup();
			} catch(ex){}
			
			// sign up forms
			try	{
				this.signupFormHandler();
			} catch(ex){}
			
			// Trolley interaction slide-downs/flash
			try	{
				this.setupTrolleyInteraction();
			} catch(ex){}
			
			// Share This dropdown
			try	{
				this.shareThis();
			} catch(ex){}
			
			// product listing interaction
			try	{
				this.productList();
			} catch(ex){}
			
			// product details interaction
			try	{
				this.productDetails();
			} catch(ex){}
			
			// internet retailer interaction
			try	{
				this.internetRetailers();
			} catch(ex){}
			
			// location search interaction
			try	{
				this.locationSearches();
			} catch(ex){}
			
			// form validation
			try	{
				this.formValidation();
			} catch(ex){}
		},
		
		/* functionality starts */
		// open links in new windows, reuse windows for domains, etc.
		newWindows : function newWindows()
		{
			var scope = this;
	
			jQuery("a.new-window").live("click", function (e)
			{
				e.preventDefault();
				scope.openNewWindow(this.href);
			});
		},
		openNewWindow : function openNewWindow(href)
		{
			var windowname = href.replace(/https?:\/\/(.*)\/.*/, '$1');
			var windowname = windowname.replace(/[^A-Za-z0-9_]/gi, '_');
			
			window.open(href, windowname);
		},
		
		// signup form animation in header
		headerSignup : function headerSignup()
		{
			var scope = this;
	
			var form = jQuery("#head-signup-form");
			form.css("top", "-"+ form.find("fieldset").outerHeight() +"px");
			
			form.find("p").removeClass("no-js");
			
			form.find("p a").click( function(e)
			{
				e.preventDefault();
				scope.headerSignupScroll( form );
			});
		},
		headerSignupScroll : function headerSignupScroll( form )
		{
			var trigger = form.find("p");
	
			if(trigger.hasClass("open"))
			{
				form.animate({"top" : "-"+ form.find("fieldset").outerHeight() +"px"}, 300, 'swing');
				this.headerSignupFade(trigger, 'close');
			}
			else
			{
				form.animate({"top" : "0px"}, 300, 'swing');
				this.headerSignupFade(trigger, 'open');
			}
		},
		headerSignupFade : function headerSignupFade( trigger, action )
		{
			var trigger_link = jQuery(trigger.find("a")[0]);
			
			// default to opening
			if(action!=null && action=='close')
			{
				trigger_link.fadeOut(150, function()
				{
					trigger.removeClass("open");
					trigger_link.text("Sign up for news & offers");
					trigger_link.fadeIn(150);
				});
			}
			else
			{
				trigger_link.fadeOut(150, function()
				{
					trigger.addClass("open");
					trigger_link.text("Close");
					trigger_link.fadeIn(150);
				});
			}
		},
		
		// handle functionality of signup forms wherever they are on the site
		signupFormHandler : function signupFormHandler()
		{
			var scope = this;
			
			var messages = jQuery('ul.messages')
			// if there are messages about the newsletter (hidden on the page)
			if(messages.length>0 && messages.text().match(/subscription/i))
			{
				if(messages.text().match(/thank you for your subscription/i) || messages.text().match(/request has been sent/i))
				{
					tb_show('Thank you for joining PowaKaddy!', BASE_URL+'services/message/newslettersuccess?height=250&width=550');
				}
				else if(messages.text().match(/valid email/i))
				{
					tb_show('There seems to have been a problem', BASE_URL+'services/message/newsletterinvalidemail?height=250&width=550');
				}
				else if(messages.text().match(/already in use/i))
				{
					tb_show('There seems to have been a problem', BASE_URL+'services/message/newsletterexists?height=250&width=550');
				}
			}
		},
		
		// style up the warranty terms page with funky ordered lists
		warrantyListStyle : function warrantyListStyle()
		{
			var warranty_lists = jQuery("#page-copy #tandc-content ol:not(#page-copy #tandc-content ol ol)");
			
			warranty_lists.each( function()
			{
				var list = jQuery(this)
				list.css("list-style-type", "none");
				list.find("> li").each( function( index )
				{
					jQuery(this).prepend('<span class="numbering">'+ (index+1) +'.</span>');
				});
			});
		},
		
		// "Share this" button widgets
		shareThis : function shareThis()
		{
			var share_widgets = this.shareWidgets();
		},
		shareWidgets : function shareWidgets()
		{
			var share_widget = function()
			{
				return {
				tigger : null,
				overlay : null,
				close_timer : null,
				
				setup : function( share_el )
				{
					var scope = this;
					
					this.trigger = share_el.find(".trigger");
					this.overlay = share_el.find("dl");
					this.close_timer = null;
					this.coords = this.trigger.find("img").position();
					
					// immediate open/close
					this.trigger.click( function(e)
					{
						e.preventDefault();
						
						scope.overlay.show();
					});
					this.overlay.find("dt a").click( function(e)
					{
						e.preventDefault();
						
						scope.overlay.hide();
					});
					this.overlay.find("dd a").click( function(e)
					{
						scope.overlay.hide();
					});
					
					// timed auto-close
					this.overlay.mouseleave( function()
					{
						scope.close_timer = setTimeout( function() { scope.overlay.hide(); }, 600);
					});
					this.overlay.mouseenter( function()
					{
						clearTimeout(scope.close_timer);
					});
				}
				};
			}
			
			var share_objs = [];
			var share_els = jQuery('.share-this');
			
			for(i=0, maxi=share_els.length; i<maxi; i++)
			{
				widget = share_widget();
				widget.setup( jQuery(share_els[i]) );
				share_objs.push( widget );
			}
			
			return share_objs;
		},
		shareFacebookTouch : function shareFacebookTouch()
		{
			this.shareFacebook(touch_share_properties);
		},
		shareFacebookSport : function shareFacebookSport()
		{
			this.shareFacebook(sport_share_properties);
		},
		shareFacebook : function shareFacebook(share_properties)
		{
			var facebook_props = {
			 app_id: 102665383152762,
			 method: 'feed',
			 display: 'popup',
			 redirect_url: BASE_URL
			}
			for(prop in share_properties)
			{
				facebook_props[prop] = share_properties[prop];
			}

			FB.ui( facebook_props, function(response) {
				 if (response && response.post_id) {
					 tb_show('Thank you for sharing', BASE_URL+'services/message/facebookthanks?height=250&width=550');
				 }
			});
		},
		
		shareTwitterTouch : function shareTwitterTouch()
		{
			this.shareTwitter(touch_share_properties);
		},
		shareTwitterSport : function shareTwitterSport()
		{
			this.shareTwitter(sport_share_properties);
		},
		shareTwitter : function shareTwitter(share_properties)
		{
			var window_height = 300;
			var window_width = 450;
			var window_top = (jQuery(window).height-window_height)/2;
			var window_left = (jQuery(window).width-window_width)/2;

			var twitter_window = window.open('http://twitter.com/share?text='+ encodeURIComponent(share_properties.message) +'&url='+ encodeURIComponent(share_properties.link) +'&counturl='+ encodeURIComponent(share_properties.link) +'&related=PowaKaddy_Golf', 'twitter_window', 'width=400,height=300,top='+ window_top +',left='+ window_left );

// there's no callback from Twitter after posting, and cross-domain policy means we can't track window closing on the Twitter site
// so the stuff below is there as a final example of what was being attempted.
/*
			jQuery(twitter_window).unload( function(e)
			{
				var tweet_window = jQuery(this);
				window.setTimeout( function()
				{
					if(tweet_window.length == 0)
					{
						tb_show('Thank you for sharing', 'includes/thanks-twitter.php?height=250&width=550');
					}
				}, 200);
			});
*/
		},
		shareEmailTouch : function shareEmailTouch()
		{
			this.shareEmail(touch_share_properties);
		},
		shareEmailSport : function shareEmailSport()
		{
			this.shareEmail(sport_share_properties);
		},
		shareEmail : function shareEmail(share_properties)
		{
			document.location.href = "mailto:?subject="+escape(share_properties['name'])+"&body="+escape(share_properties['message']+" - "+share_properties['link']);
		},

		// trolley interaction
		setupTrolleyInteraction : function setupTrolleyInteraction()
		{
			// if the homepage Flash fails, build the JS fallback.
			if( this.flashEnabled() )
			{
				this.interactionFlash();
			}
			else
			{
				this.interactionFallback();
			}
		},
		interactionFlash : function interactionFlash()
		{
			if( jQuery("#hp-touch-movie").length > 0 )
			{
				swfobject.embedSWF(INCLUDES_PATH+"swf/swf_preloader.swf?movie="+ INCLUDES_PATH +"swf/touch-interaction.swf", "hp-touch-movie", "940", "466", "8.0.0", "expressInstall.swf", {}, {}, {});
			}
			if( jQuery("#hp-sport-movie").length > 0 )
			{
				swfobject.embedSWF(INCLUDES_PATH +"swf/sport-interaction.swf", "hp-sport-movie", "940", "466", "8.0.0", "expressInstall.swf", {}, {}, {});
			}
		},
		interactionFallback : function interactionFallback()
		{
			var scope = this;
			
			jQuery("#hp-interaction-container .interaction a.close").live("click", function(e)
			{
				e.preventDefault();
				
				scope.hideInteraction();
			});
			
			if( jQuery("#hp-interaction-container #hp-sport .onionskin") )
			{
				var scope = this;
				this.onionskin = jQuery("#hp-interaction-container #hp-sport .onionskin");
				this.description = jQuery("#hp-interaction-container #hp-sport .description");
				this.overlay = jQuery(this.onionskin.find(".overlay"));
				this.highlights = this.onionskin.find("area");
				
				this.highlights.mouseover(function()
				{
					var bg_pos = jQuery(this).attr("href").replace("#", "");
					scope.overlay.css("background-position", "0 -"+ parseInt(bg_pos) +"px");
					
					scope.description.find("#desc-sport-"+bg_pos).css({"position":"absolute", "top":"0"});
				});
				this.highlights.mouseout(function()
				{
					var bg_pos = 1000;
					scope.overlay.css("background-position", "0 "+ parseInt(bg_pos) +"px");
					scope.description.find(".copy").css({"position":"relative"});
				});
				this.highlights.click(function(e)
				{
					e.preventDefault();
				});
			}
		},
		//scroll downs for trolle interaction
		showInteractionSport : function showInteractionSport()
		{
			this.current_interaction = 'sport';
			this.showInteraction(this.current_interaction);
			
			return false;
		},
		showInteractionTouch : function showInteractionTouch()
		{
			this.current_interaction = 'touch';
			this.showInteraction(this.current_interaction);
			
			return false;
		},
		showInteraction : function showInteraction(item_name)
		{
			this.current_interaction = item_name;

			jQuery("#hp-interaction-container").css("display", "block");
			jQuery("#hp-"+item_name).css("display", "block");
			jQuery("#hp-"+item_name+" .interaction").fadeOut(0);
			jQuery("#hp-"+item_name).animate({"margin-top":"0"}, 650, function()
			{
				jQuery("#hp-"+item_name+" .interaction").fadeIn(350);
			});
		},
		hideInteraction : function hideInteraction()
		{
			var scope = this;
			jQuery("#hp-"+scope.current_interaction+' .interaction').fadeOut(250, function()
			{
				jQuery("#hp-"+scope.current_interaction).animate({"margin-top":"-"+jQuery("#hp-interaction-container").css("height")}, 500, function()
				{
					jQuery("#hp-interaction-container").css("display", "none");
					jQuery("#hp-"+scope.current_interaction).css("display", "none");
				});
			});
		},
		//go to stockist page
		openStockists : function openStockists()
		{
			location.href = BASE_URL + 'stockists';
			
			return false;
		},
		//go to TOUCH trolley page
		openTouch : function openTouch()
		{
			location.href = BASE_URL + 'electric-trolleys/sport.html';
			
			return false;
		},
		//go to SPORT trolley page
		openSport : function openSport()
		{
			location.href = BASE_URL + 'electric-trolleys/sport.html';
			
			return false;
		},
		//go to FREEWAY trolley page
		openFreeway : function openFreeway()
		{
			location.href = BASE_URL + 'electric-trolleys/freeway.html';
			
			return false;
		},
		
		// simple check for Flash player
		flashEnabled : function flashEnabled()
		{
			var flash_version = swfobject.getFlashPlayerVersion();
			var flash_enabled = (flash_version.major > 0);
			
			return flash_enabled ;
		},
		
		// product listing interaction
		productList : function productList()
		{
			// hover over listing column items
			jQuery("#product-list .list-item a, #product-list .illustration").hover(
				function() {
					jQuery("#product-list .active").removeClass("active");
					jQuery(jQuery(this).parents(".list-item")[0]).addClass("active");
				},
				function() {
					jQuery(jQuery(this).parents(".list-item")[0]).removeClass("active");
					jQuery("#product-list .selected").addClass("active");
				}
			);
			
			// change sub-category selection in listing column
			jQuery("#list-form select").change(
				function()
				{
					location.href = this.value;
				}
			);
			
			// click on items in listing column
			jQuery("#product-list .list-item a").click(
				function(e)
				{
					e.preventDefault();
					
					var selection = jQuery(jQuery(this).parents(".list-item")[0]).attr("class").replace(/^.*(item-\d+).*$/, "$1");
					if(selection != '')
					{
						// highlight in the nav
						jQuery("#product-list .selected").removeClass("selected");
						jQuery("#product-list ."+selection).addClass("selected");
						
						// display the details
						jQuery("#product-overview .active").removeClass("active");
						jQuery("#product-overview ."+selection).addClass("active");
					}
				}
			);
		},
		
		// product details page interaction
		productDetails : function productDetails()
		{
			var images_per_window = 5;
			var thumb_window_width = 385;
				
			// content swapper
			jQuery("#product-description .sub-content-tabs a").click(function(e)
			{
				e.preventDefault();
				
				var content_id = jQuery(jQuery(this).parent()).attr("id").replace("-tab-", "-copy-");

				// hide all content
				jQuery("#product-description .sub-content-tabs li").removeClass("active");
				jQuery("#product-description .tabbed-content .copy").removeClass("active");
				
				// show new active content
				jQuery(this).parent().addClass("active");
				jQuery("#" + content_id).addClass("active");
			});
			
			//media gallery swapper
			jQuery("#product-media-nav a").click(function(e)
			{
				e.preventDefault();
				
				var media_type = jQuery(this).attr("class");

				// hide all content
				jQuery("#product-media-nav li").removeClass("active");
				jQuery("#product-media-content .media").removeClass("active");
				
				// show all active content
				jQuery(this).parent().addClass("active");
				jQuery("#product-media-content ." + media_type).addClass("active");
			});
			
			// thumbnail gallery display
			jQuery('#product-media .product-thumbnail-link').live('click', function(e)
			{
				var thumb_src = jQuery(this).attr('href');
				var main_img = jQuery('#product-media .product-image img')
				main_img.fadeOut( function(){
					if (thumb_src) {
							main_img.attr('src',thumb_src);		
							main_img.load(function () {
									jQuery(this).fadeIn();
								});
					};
				});
				return false;
			});
			
			// thumbnail gallery scrolling
			jQuery('#product-media .more-views .thumbnail-right').live('click', function(e)
			{
				e.preventDefault();
				
				var image_count = jQuery('#product-media .thumbnail-navigation li').length;
				var thumb_navigation = jQuery('#product-media .thumbnail-navigation ul');
				
				thumb_pos_right = parseInt(thumb_navigation.css('left'));
				var screens_to_the_left = Math.abs(thumb_pos_right/thumb_window_width);
				var available_screens = Math.ceil(image_count/images_per_window);

				if(screens_to_the_left < available_screens-1) {
					if(!thumb_navigation.is(':animated')){
						jQuery('#product-media .more-views ul').stop(true, true).animate({ left: '-='+thumb_window_width+'px'}, { queue: false, duration: 200 });
					}
				}
			});
			jQuery('#product-media .more-views .thumbnail-left').live('click', function(e)
			{
				e.preventDefault();
				
				var thumb_navigation = jQuery('#product-media .thumbnail-navigation ul');
				
				thumb_pos_left = thumb_navigation.css('right');
				thumb_pos_right = thumb_navigation.css('left');
				if(parseInt(thumb_pos_right) != 0) {
					if(!thumb_navigation.is(':animated')){
						jQuery('#product-media .more-views ul').stop(true, true).animate({ left:  '+='+thumb_window_width+'px'}, { queue: false, duration: 200 });
					}
				}
			});
			
			// image/colour switching
			jQuery('#product-styles select').change(function()
			{
				var new_colour = jQuery("#product-styles select").val();
				var gallery_nav = jQuery("#product-media .thumbnail-navigation ul");
				var new_gallery_nav = '';
				
				var generic_count = product_images[0].length;

				// add generic images first
				for(i=0, maxi=generic_count; i<maxi; i++)
				{
					new_gallery_nav += product_images[0][i];
				}
				// add specific images second
				for(i=0, maxi=product_images[new_colour].length; i<maxi; i++)
				{
					new_gallery_nav += product_images[new_colour][i];
				}
				gallery_nav.html(new_gallery_nav);
				
				var generic_thumb_set = Math.floor(generic_count / images_per_window);

				gallery_nav.animate({ left:  -1 * generic_thumb_set * thumb_window_width+'px'}, { queue: false, duration: 400 });
				
				jQuery(jQuery('#product-media .product-thumbnail-link')[generic_count]).click();
			});
		},
		
		// internet retailers page interaction
		internetRetailers : function internetRetailers()
		{
			jQuery("#internet-retailers .retailer a").live('mouseover', function()
			{
				jQuery(this).addClass('active');
			});

			jQuery("#internet-retailers .retailer a").live('mouseout', function()
			{
				jQuery(this).removeClass('active');
			});
		},
		
		// location search interaction on "nearest XYZ" pages
		locationSearches : function locationSearches()
		{
			var searchTimer = null;
			var scope = this;

			jQuery("#location-search #location-search-postcode").keyup(function()
			{
				if( jQuery("#location-search #location-search-postcode").val() != '' )
				{
					scope.searchTimer = setTimeout(function()
					{
						scope.sendLocationSearch();
					}, 400);
				}
			});
			jQuery("#location-search #location-search-radius").change(function()
			{
				if( jQuery("#location-search #location-search-postcode").val() != '' )
				{
					scope.sendLocationSearch();
				}
			});
			jQuery("#location-search #location-search-postcode").keydown(function()
			{
				clearTimeout(scope.searchTimer);
			});
			jQuery("#location-search").submit(function(e)
			{
				e.preventDefault();
			});
		},
		sendLocationSearch : function sendLocationSearch()
		{
			var scope = this;

			jQuery.get(jQuery("#location-search #location-search-service").val(),
								jQuery("#location-search").serialize(),
								function(data)
								{
									scope.showLocationSearchResults(data);
								},
								'html');
		},
		showLocationSearchResults : function showLocationSearchResults(results_html)
		{
			jQuery("#location-search-results").html(results_html);
		},
		
		// form validation
		formValidation : function formValidation()
		{
			/* contact form is standard validation */
			var contactForm = new VarienForm('contact-form');

			/* brochure form has extra validation to check matching emails */
			var brochureForm = new VarienForm('brochure-form');
			if(jQuery('#brochure-form').length > 0)
			{
				jQuery('#brochure-form').submit(function(e)
				{
					jQuery('#advice-matching-entry-brochure-form-email-confirmation').remove();
					if(jQuery('#brochure-form-email').val() != jQuery('#brochure-form-email-confirmation').val() && jQuery('#brochure-form-email-confirmation').val() != '')
					{
						jQuery('#brochure-form-email, #brochure-form-email-confirmation').addClass('validation-failed');
						jQuery('#brochure-form-email-confirmation').after('<div style="" id="advice-matching-entry-brochure-form-email-confirmation" class="validation-advice">The two emails entered do not match.</div>');
						
						e.preventDefault();
					}
				});
			}
			
			/* product registration form has extra validation to check matching emails */
			var registrationForm = new VarienForm('warranty-registration-form');
			if(jQuery('#warranty-registration-form').length > 0)
			{
				jQuery('#warranty-registration-form').submit(function(e)
				{
					// matching emails
					jQuery('#advice-matching-entry-reg-confirm-email').remove();

					if(jQuery('#reg-email').val() != jQuery('#reg-confirm-email').val())
					{
						jQuery('#reg-email, #reg-confirm-email').addClass('validation-failed');
						jQuery('#reg-confirm-email').after('<div style="" id="advice-matching-entry-reg-confirm-email" class="validation-advice">The two emails entered do not match.</div>');
						
						e.preventDefault();
					}
					
					// at least one serial number filled in
					jQuery('#reg-trolley-serial, #reg-battery-serial, #reg-charger-serial').removeClass('validation-failed');
					jQuery('#advice-required-entry-reg-trolley-serial, #advice-required-entry-reg-battery-serial, #advice-required-entry-reg-charger-serial').remove();
					
					if(jQuery('#reg-trolley-serial').val()=='' && jQuery('#reg-battery-serial').val()=='' && jQuery('#reg-charger-serial').val()=='')
					{
						jQuery('#reg-trolley-serial, #reg-battery-serial, #reg-charger-serial').addClass('validation-failed');
						jQuery('#reg-trolley-serial').after('<div style="" id="advice-required-entry-reg-trolley-serial" class="validation-advice">Please enter the serial number of your product</div>');
						jQuery('#reg-battery-serial').after('<div style="" id="advice-required-entry-reg-battery-serial" class="validation-advice">Please enter the serial number of your product</div>');
						jQuery('#reg-charger-serial').after('<div style="" id="advice-required-entry-reg-charger-serial" class="validation-advice">Please enter the serial number of your product</div>');
						
						e.preventDefault();
					}
				});
			}
		},

		resizeIframe : function resizeIframe(content_height)
		{
  	  var iframes = jQuery('iframe');
			if(iframes.length)
			{
				jQuery(iframes[0]).height(parseInt(content_height));
			}
		}
	};
})();


// fix for modulus of negative number
Number.prototype.mod = function(n)
{
	return ((this%n)+n)%n;
}
