// (jQuery)
$(document).ready(function(){

	// Bind facebox links
	$('a[rel*=facebox]').facebox() 


		// Change class on form field focus
		function fnFormFocus(){
			$("input,textarea").focus(function() {
				$(this).parent().addClass("fieldFocus")
			});
			
			$("input,textarea").blur(function() {
				$(this).parent().removeClass("fieldFocus")
			});
		}		

		// Function to remove any form messages that may have been generated
		function fnRemoveFormMessage() {
			$('#submissionResponse').remove();
		}
		
		// Function to show a form message
		function fnShowFormMessage(
			formID, 	// ID of form to add message to
			status, 	// success | error | info1 | info 2
			message		// Message text to display
		) {
			// Remove existing message
			fnRemoveFormMessage()
			// Display new message
			$(formID).before('<p id="submissionResponse" class="' + status + '">' + message + '</p>');
		}
		
		// Function to insert button links
		function fnInsertButtonLink(
			element, 	// Element immedaitely before buttons to be inserted
			title, 		// Title to use for button text
			linkurl, 	// URL to link to the button to
			linkClass	// Set to 'closeModal' to bind this button to the close modal function (for 'ok' or 'cancel' buttons)
		) {
			// First check to see if the element we've been passed contains a button paragraph - if not, we'll create one
			if ($(element + ' + p.buttons').length == 0) {
				// Create a paragraph to store our buttons
				$(element).after('<p class="buttons"></p>');
			}
			
			// Insert the new button 
			$(element + ' + p.buttons').append('<a class="' + linkClass + '" href="' + linkurl + '">' + title + '</a>');
			
			// Bind any closeModal buttons to the close modal function
			$(element + ' + p.buttons > a.closeModal').click(function () {
				$(".modal").colorbox.close();
				return false;
			});
		}

		// Function to replace content (handy for ajax calls)		
		function fnReplaceContent(data, element) {
				$(element).replaceWith(data);
		}		




	// Login form
		$("#loginLink").colorbox({
			overlayClose: false,
			opacity: 0.6,
			initialHeight: 0,
			initialWidth: 0,
			overflow: false,
			onComplete: function(){
				
				// Bind form focus function
				fnFormFocus();
				
				// Set up the ajax form
				$('#frmLogin').ajaxForm({
					url: '/_ajaxRequests/memberLogin.cfm',
					clearForm: true,
					beforeSubmit: fnRemoveFormMessage,
					success: function(responseText) {
						
						// Check to see if the login was successful
						if (responseText == 'Success') {
							
							// Login successful - Hide the login form and display success message
							fnShowFormMessage('#frmLogin', 'success', 'Login successful');
							$('#frmLogin').hide();
							
							// Insert links to the account page
							fnInsertButtonLink('#submissionResponse', 'Continue', '/', 'closeModal')
							fnInsertButtonLink('#submissionResponse', 'Your Account', '/members/')
							
							// Resize modal box to account for new message
							$('.modal').colorbox.resize();
							
							// change the account links at the top of the page, to reflect the 'logged in' status
							$.get('/members/_dspMember.cfm', function(data) { // Load member links
								fnReplaceContent(data, '#siteNavAccount'); // Replace content
							});
							
							// Search for the wishlist id and change it.
							$('#wishListLink').html("<button name='btnWishList' type='submit' value='Add to Wish List'>Add to wish list</button>");
							
						}
						
						else {
							// Login failed - display an error
							fnShowFormMessage('#frmLogin', 'error', 'Login details incorrect');
							// Resize modal box to account for new message
							$(".modal").colorbox.resize();
						}
					}
				});
			}
		})



	
	// Navigation dropdown menu
	if ( $("#navigation").length > 0 ) { 	
		$("#navigation ul").supersubs({ 
			minWidth:    18,
			maxWidth:    27,
            animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
            speed:       'fast',                          // faster animation speed 			
			extraWidth:  1  
		}).superfish();
	}

	if ( $("#fpPromoBlock").length > 0 ) {
		// Remove the 'noJS' class
		$('#fpPromoBlock').removeClass('noJS');
		// Wrap the block in a codaSlider div
		$('#fpPromoBlock').wrap('<div class="coda-slider-wrapper">')
		// Add class to the block
		$('#fpPromoBlock').addClass('coda-slider')
		// Create panel wrapper div
		$('#fpPromoBlock div.panel').wrapInner('<div class="pannel-wrapper">')
		// Attach codaSlider
		$('#fpPromoBlock').codaSlider({
			autoHeight: false,
			autoSlide: true,
		   	autoSlideInterval: 10000,
			slideEaseDuration: 2000,
		   	autoSlideStopWhenClicked: true,
			dynamicArrows: false,
        	dynamicTabs: true,
			dynamicTabsPosition: 'bottom',
			dynamicTabsAlign: 'left'
		});
	};	

	// Product Image Zoom
	if ( $("#productImageLink").length > 0 ) {
		$('#productImageLink').jqzoom({
			zoomWidth: 378,
			zoomHeight: 232,
			xOffset: 181,
			yOffset: -1
		});
	}


	// Alternative product photos (jQuery)
	$(".altPhoto").click(function() {

		// Set new image src
		var altImageSrc = $(this).attr("href");

		// Call function to replace image
		altImage(altImageSrc);

		return false;	
	});
	
	// Function: Show alternative product image
	function altImage(src) {

		// Remove the current image
		$('#productImage').fadeOut('fast', function () {
			// Load new image
			var img = new Image();
			$(img).load(function () {
				// Manipulate SRC to display image at size 2
				var newsrc = src.substring(0, src.length - 1) + '2';
				
				$('#productImage').attr("src", newsrc);
				$('#productImageLink').attr("href", src);								  
				$('#productImage').fadeIn();
			}).attr({
				src: src
			});
		});
	 }
	 
	// Category hover styling
	$('div.categoryGrid li ul')
	.css({'opacity' : 1})
	.hide();
	

		$('div.categoryGrid li').hover(
			function () {						   
				if ( $(this).children('ul').length > 0 ) {				// Check if this category has subcategories
					$(this).children('ul').fadeIn('fast');				// Display subcategories
				}
				else {													// If there are no subcategories, we want to stretch the link to fill the whole category space
					var linkWidth = $(this).find('h2 > a').width();		// Set the current width of the link, so we know how much to stretch by
					$(this).find('h2 > a').css(							// Pad the link out to fill the space
						{
							'padding-top' 		: '137px',
							'padding-bottom'	: '12px',
							'padding-right'		: Math.round(448 - linkWidth) + 'px',
							'z-index' 			: '3'
						}
					);
				}
			},
			function () {
				$(this).children('ul').fadeOut('fast');
			}
		);



	// Display shipping time
		// Hide current shipping text
		$('#shippingText').hide()	
	
		$("#iSizeID").change(function() {
	
			// Get new shipping text value from option title
			var shippingValue = $("#iSizeID option:selected").attr("title");
			$('#shippingText').html('Usually shipped within: <strong>' + shippingValue + '</strong>').hide();
									  
			// Only show shipping message if the shippingText variable contains a value
			if (shippingValue.length != 0) {
			
				// Fade shipping text in
				$('#shippingText').fadeIn('fast')
			}
			
			return false;	
		});
	
	// Add to cart validation
	$('#btnAddToCart').click(function() {

		// If there's an error, show a submission response and catch the click
		if ($("#iSizeID").val() < 0 || $("#iThicknessID").val() < 0) {
			// Remove existing response div
			$("#submissionResponse").remove();
			
			// Insert response div
			var response = $('<div id="submissionResponse" class="error">Sorry, there was a problem adding this item to your basket.<ul></ul></div>').hide();
			$("#productDetailsDiv").before(response);

			// Check to see if a Colour is required but not specified.
			if ($("#iThicknessID").val() < 0) {
	
				// Add error class to select
				$("#thicknesses").addClass("error")
				
				// Add error message to submission response
				$("#submissionResponse ul").append('<li id="error_iThicknessID">Please select a width for this item.</li>');
			}
			else {
				// Remove error class
				$("#thicknesses").removeClass("error")
				
				// Remove error message
				$("#error_iThicknessID").remove();
			}
	
			// Check to see if a Size is required but not specified.
			if ($("#iSizeID").val() < 0) {
							
				// Add error class to select
				$("#sizes").addClass("error")
	
				// Add error message to submission response
				$("#submissionResponse ul").append('<li id="error_iSizeID">Please select a size for this item.</li>');
			}
			
			else {
				// Remove error class
				$("#sizes").removeClass("error")
	
				// Remove error message
				$("#error_iSizeID").remove();
			}

			// Fade the response in
			response.fadeIn();

			return false;
		}
	});

	// Out of stock reminders (GUESTS)
		$("#outOfStockBtn").children('p').hide();
		// When the stock reminder button is clicked
		$("#btnStockReminder").click(function() {
			$("#outOfStockBtn").children('p').hide();
			// Poll the email validation script if a value has been entered.
			if ( $("#sStockEmailAddress").val().length > 0 ) {
				
				// Assign values to variables
				sEmailAddress = $("#sStockEmailAddress").val();
				iProductID = $("#iProductID").val();
				iMemberID = $("#iMemberID").val();
				
				// Add stock reminder
				$.post("/_ajaxRequests/addStockReminder.cfm", { sString: sEmailAddress, iProductID: iProductID, iMemberID: iMemberID },
				function(data){
					// If the response is an error, show message and stop form submission
					if ( (data) == "Error" ) {
						// Show message
						$("#outOfStockBtn").children('p').css('color','red').html('Please enter a valid email address.').fadeIn('slow');
						// Stop form submission
						return false;
					}

					if ( (data) == "Duplicate" ) {
						// Show message
						$("#outOfStockBtn").children('p').css('color','red').html('You have already submitted a request to be notified about this product.').fadeIn('slow');
						// Stop form submission
						return false;
					}

					if ( (data) == "Success" ) {
						// Show message
						$("#outOfStockBtn").children('p').css('color','green').html('Thanks! A confirmation email has been sent to your address. Please click the link in this email to activate your stock notification.').fadeIn('slow');
						// Stop form submission
						return false;
					}
				});
			return false;
			}
			return false;	
		});

	// Out of stock reminders (MEMBERS)
		$("#membersOutOfStockBtn").children('p').hide();
		// When the stock reminder button is clicked
		$("#btnMembersStockReminder").click(function() {
			// Hide AJAX reponse
			$("#membersOutOfStockBtn").children('p').hide();
			// Assign values to variables
			iMemberID = $("#iMemberID").val();
			iProductID = $("#iProductID").val();
			sEmailAddress = "";

			// Add stock reminder
			$.post("/_ajaxRequests/addStockReminder.cfm", { sString: sEmailAddress, iProductID: iProductID, iMemberID: iMemberID },
			function(data){
				// If the response is an error, show message and stop form submission
				if ( (data) == "Duplicate" ) {
					// Show message
					$("#membersOutOfStockBtn").children('p').css('color','red').html('You have already submitted a request to be notified about this product').fadeIn('slow');
					// Stop form submission
					return false;
				}

				if ( (data) == "Success" ) {
					// Change page to show the notification has been set.
					$("#outOfStock").html('<p><strong>This item is currently out of stock.</strong></p><p class="smallText">You have asked to be notified when this item is available.<br /><a href="/members/myAccount/stockReminders.cfm" title="Manage your product notifications">Manage your product notifications</a></p>');
					// Remove notification button.
					$("#membersOutOfStockBtn").remove();
					// Stop form submission
					return false;
				}
			});
			return false;
		});
	
	// Use the 'example' plugin on the search box
		$("#frmSearch #sSearchString").example('Product search...');	

	// Carousels
		// Recently viewed
		if ( $("#recentlyViewed").length > 0 ) { 		
			// Insert previous and next links
			$('#recentlyViewed').before('<a class="prev">Previous</a>');
			$('#recentlyViewed').after('<a class="next">Next</a>');
			
			$('#recentlyViewed').addClass('enhanced');
			
			// Attach carousel to list
			$("#recentlyViewed").jCarouselLite({
				btnNext: ".next",
				btnPrev: ".prev"
			});
		}
		
		// Featured Products
		if ( $("#featuredProducts").length > 0 ) { 		
			// Insert previous and next links
			$('#featuredProducts ul').before('<a class="prev">Previous</a>');
			$('#featuredProducts ul').after('<a class="next">Next</a>');
		
			// Wrap UL in new div
			$('#featuredProducts ul').wrap('<div>');
			
			// Add enhanced class and remove itemGrid class
			$('#featuredProducts').addClass('enhanced').removeClass('itemGrid');
			
			// Attach carousel to list
			$("#featuredProducts div").jCarouselLite({
				visible: 5,
				btnNext: ".next",
				btnPrev: ".prev"
			});
		}


	// Addresses: State selector
		if ( $("#stateSelector").length > 0 ) { 
			// Define function to check state and show/hide accordingly
			function showStates() {
				// Get contents of country field
				sCountry = $('#iCountryID :selected').text()
			
				if (sCountry.match('United States')){
					$("#stateSelector").show('fast');
				}
				
				else if (sCountry.match('Canada')){
					$("#stateSelector").show('fast');
				}
										
				else {
					$("#stateSelector").hide('fast');
				}
			}
			
			// Run showStates function upon any interaction with the country field
			$('#iCountryID').bind("change keypress focus blur", function() {
				showStates();
			});
			
			// Run showStates function once on load
			showStates();
		}
	
		

	// Sort order display
		// Hide the list of display orders
			$('#sortOrder ul').hide();
		
		// Remove the 'noJS' class
			$('#sortOrder').removeClass('noJS');
	
		// Toggle view of display order list
			$('#sortOrder').hover(
				function() { $('#sortOrder ul').show(); },
				function() { $('#sortOrder ul').hide(); }
			);


	// Subscription form - Check it exists first
		if ( $("#frmSubscribeToList").length > 0 ) { 
	
			// Hide subscription response 
			$('#subscribeResponse').hide();
			
			// bind form using ajaxForm 
			$('#frmSubscribeToList').ajaxForm({ 
				// target identifies the element(s) to update with the server response 
				target: '#subscribeResponse', 
		
				beforeSubmit: function() {
					// Hide subscription response 
					$('#subscribeResponse').hide();
				},
					
				// success identifies the function to invoke when the server response 
				// has been received; here we apply a fade-in effect to the new content 
				success: function() { 
					// Show response
					$('#subscribeResponse').fadeIn('slow'); 
				}
			}); 
		}
	

	// Facebox login form
		$('#facebox').livequery(function() {
			// Hook up the login form with livequery, as it's pulled in via the facebox ajax function
			$(this).find('#frmLogin').livequery(function() {
				// This'll set up the ajax form
				$(this).ajaxForm({
					success: function(html) {
						// Now, when the form's submitted, send the response to the facebox div				
						$('#facebox').find('.facebox').html(html);
						// Now, if the login was successful, we need to change some elements on the page.
						$('#loginSuccess').livequery(function() {
							// Search for the wishlist id and change it.
							$('#wishListLink').html("<button name='btnWishList' type='submit' value='Add to Wish List'><img src='/img/structure/buttons/btnWishList.gif' alt='Add to wish list' />Add to wish list</button>");
							// Search for the member block and change this.
							$('#memberPanel').load("/members/_dspMember.cfm" + '?nocache=' + Math.random());
						});
					}
				});
			});
		});
	
	// Facebox Tell a Friend form
		$('#facebox').livequery(function() {
			// Hook up the login form with livequery, as it's pulled in via the facebox ajax function
			$(this).find('#frmTellAFriend').livequery(function() {
				// This'll set up the ajax form
				$(this).ajaxForm({
					success: function(html) {
						// Now, when the form's submitted, send the response to the facebox div				
						$('#facebox').find('.facebox').html(html);

					}
				});
			});
		});	
	
	// WishList Move to cart link
		$('.moveToCart').click(function() {
			$(this).closest('.wishListRow').fadeOut('fast');
		});


	// Tell a friend form - Check it exists first
		if ( $("#frmTellAFriend").length > 0 ) { 
	
			// Hide form 
			$('#frmTellAFriend').hide();
	
			// Toggle view of form
			$('#tellAFriend').click(function() {
				$('#frmTellAFriend').toggle('fade');
				return false;
			});
	
			// bind form using ajaxForm 
			$('#frmTellAFriend').ajaxForm({ 
				// target identifies the element(s) to update with the server response 
				target: '#frmTellAFriendContent', 
	
					
				// success identifies the function to invoke when the server response 
				// has been received; here we apply a fade-in effect to the new content 
				success: function() { 
					// Show response
					$('#frmTellAFriendContent').fadeIn('slow'); 
				}
			}); 
		}

	// Guest checkout:
		// Email check
			// Check for 'blurring' of the email field
			$("#guestBillingAdress #sEmailAddress").blur(function() {
				// Only poll the search engine friendly script if a value has been entered
				if ( $(this).val().length > 0 ) {
					// Assign the value of the email field to a variable
					sStringData = $("#guestBillingAdress #sEmailAddress").val();
					
					// Remove any error message that may already be there
					$("#emailError").remove();
					
					// Insert the standard ajaxy "I'm thinking about it" graphic. Lovely.
					$("#guestBillingAdress #sEmailAddress").after('<img src="/img/elements/loadingSml.gif" title="Please wait..." id="ajaxThinking" class="floatRight" />');
					
					// Hit the email checking script with the contents of the email variable
					$.post("/_ajaxRequests/checkMemberEmail.cfm", { sString: sStringData },
					function(data){
						// Remove the thinking graphic
						$("#ajaxThinking").remove();
							
						// If there's an error, show the appropriate message:
						if ((data) == "error_notUnique,error" ) {
							// Set error class on email list item
							$("#emailAddress").removeClass('success');
							$("#emailAddress").addClass('error');
							// Show error message							
							$("#guestBillingAdress #sEmailAddress").after("<p id='emailError'>We recognise that email address - it seems that you're already registered as a member with us. Please <a href='/members/login' title='Login to your account'>login to your member account</a> to continue.</p>");
							// Disable the rest of the form
						}
						else if ((data) == "error" ) {
							// Set error class on email list item
							$("#emailAddress").removeClass('success');
							$("#emailAddress").addClass('error');
							// Show error message
							$("#guestBillingAdress #sEmailAddress").after("<p id='emailError'>That email address doesn't appear to be valid. We need a valid email address to send your order confirmation. Please try again.</p>");
							// Disable the rest of the form
						}
						else {
							// Remove error class on email list item
							$("#emailAddress").removeClass('error');
							$("#emailAddress").addClass('success');
						}
					});
				}
			});



	// Checkout
		// Toggle display of delivery details if box ticked
			$('#bBillingAsDelivery').click(function() {
				$('#form_delivery').toggle('fade');
			});		

		// on selecting a shipping method, run CF include page to set shipping method and return total
			$('input[name=iShippingMethodBandID]').click(function() { 
			
				iShippingMethodBandID = $("input[name=iShippingMethodBandID]:checked").val();
	
	
				<!--- Insert 'loading' image into div, whilst waiting for the ajax call to load. --->
				$("#cartTotal").html("<p class='bigText center'><img src='/img/elements/loading.gif' alt='Loading: please wait' style='border:0px; display:inline;'><br>Please wait...</p>");
	
				<!--- Use ajax to update shipping band and get back the cart total --->
				$("#cartTotal").load("/cart/_incGetCartTotal.cfm?iShippingMethodBandID=" + iShippingMethodBandID + '&nocache=' + Math.random());
											
			}); 

	// Promotions feature
		// Check the promo code form exists on this page
			if ( $("#frmPromoCode").length > 0 ) { 	
				// bind 'frmPromoCode' to ajax form function
				$('#frmPromoCode').ajaxForm(function() { 
		
					<!--- Insert 'loading' image into div, whilst waiting for the ajax call to load. --->
					$("#promoCodeButton").html("<img src='/img/elements/loading.gif' alt='Loading: please wait'> checking code");
		
					<!--- Ajax call to display promotion details --->
					$("#promoCode").load("/cart/dspPromo.cfm");
												
				}); 
			}
		

});


