// (jQuery)
$(document).ready(function(){

	// Bind facebox links
	$('a[rel*=facebox]').facebox() 
	
	// Open / Close help panel 						   
	$(".helpButton").click(function() {
		$("#content").addClass("helpPanel")
		$('#helpPanel').show('slow')
		return false;
	});

	$("#helpPanelTitle").click(function() {
		$('#helpPanel').hide('slow');
		$("#content").removeClass("helpPanel")
		return false;		
	});		
	
	// Member dropdown menu
	if ( $("#memberPanel").length > 0 ) { 	
		$('#memberPanel ul.loggedIn').superfish();
	}
	
	// Product Zoom (jQuery)
	$("#productZoom").click(function() {

		$('#productImage').remove();
		$('#productImageDiv').html('<img src="" id="productImage">');

		// Set new image src
		var imageSrc = $("#productZoom").attr("href");
		$("#productImage").attr('src', imageSrc);	

		// Run the imagetool plugin on the image
		$(function() {
			$("#productImage").imagetool({
				viewportWidth: 440,
				viewportHeight: 440,
				topX: 150,
				topY: 150,
				bottomX: 440,
				bottomY: 440,
				loading: '/img/elements/loading.gif'
			});
		});
		
		// Fade in the zoom instructions
		$("#productImageDragtext").fadeIn(500);
		
		// Move the zoom button up to accomodate the zoom instructions
		$("#productZoom").css("margin-top", "-5.5em");

		// Move the alternate image div down
		$("#alternatePhotos").css("margin-top", "3.25em");
		
		return false;
	});

	// 'Unzoom' a product image
	$(".closeZoom").click(function() {
	
		// Set smaller image src (from the ID... is that messy?)
		var altSmallImage = $(this).attr("id");

		// Call function to replace image
		altImage(altSmallImage);

		return false;		
    });								   


	// Alternative product photos (jQuery)
	$(".altPhoto").click(function() {

		// Set new image src
		var altImageSrc = $(this).attr("href");

		// Set new image Zoom link (from the ID... is that messy?)
		var altZoomLink = $(this).attr("id");

		// Call function to replace image
		altImage(altImageSrc, altZoomLink);

		return false;	
	});
	
	// Function: Show alternative product image
	function altImage(src, zoomLink) {

		// Fade out the zooming instructions if they're visable
		$("#productImageDragtext").fadeOut(300, function() {
			// Move the zoom button
			$("#productZoom").css("margin-top", "-4em");
			// Move the alternate image div
			$("#alternatePhotos").css("margin-top", "1.5em");
		});

		// Remove the Zoom viewport div if it exists
		$('#productImageDiv div.viewport').remove();
		
		// Remove the current image
		$('#productImage').remove();

		// Set the new image Zoom link
		$("#productZoom").attr('href', zoomLink);

		// Set the new image 'Close Zoom' link
		$(".closeZoom").attr('id', src);

		// Load new image
		var img = new Image();
        $(img).load(function () {
			$(this).hide();
            $('#productImageDiv').append(this);
            $(this).fadeIn();
        }).attr({
			src: src,
			id: "productImage"
			});
	 }

	// Display shipping time (jQuery)
	$("#iSizeID").change(function() {
		// Hide current shipping text
		$('#shippingText').hide()
		
		// Get new shipping text value from option title
		var shippingText = $("#iSizeID option:selected").attr("title");
		
		// Only show shipping message if the shippingText variable contains a value
		if (shippingText.length != 0) {
		
			// Set full shipping text
			$("#shippingText").html('Usually shipped within: <strong>' + shippingText + '</strong>')
			
			// Fade shipping text in
			$('#shippingText').fadeIn('slow')
		}
		
		return false;	
	});
	
	// Add to cart validation
	$('#btnAddToCart').click(function() {
		// Check to see if a Colour is required but not specified.
		if ($("#iColourID").val() < 0) {
			
			// Hide errors
			$("#colours label strong").remove();
						
			// Show an error.
			$("#colours").addClass("error")
			$("#colours label").hide().append('<strong>Please select a colour</strong>').fadeIn();
		}
		else {
			// Hide errors
			$("#colours label strong").remove();
			$("#colours").removeClass("error")
		}

		// Check to see if a Size is required but not specified.
		if ($("#iSizeID").val() < 0) {
			
			// Hide errors
			$("#sizes label strong").remove();
						
			// Show an error.
			$("#sizes").addClass("error")
			$("#sizes label").hide().append('<strong>Please select a size</strong>').fadeIn();
		}
		else {
			// Hide errors
			$("#sizes label strong").remove();
			$("#sizes").removeClass("error")
		}

		// Catch the click
		if ($("#iSizeID").val() < 0 || $("#iColourID").val() < 0)
			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...');	

	// Display sale price field on product admin, only when sale item box is ticked (jQuery)
		// Hide the sale price field if the item is not on sale
		$('#iSalePriceField.hidden').hide();
		
		// Toggle view of sale price field
		$('#bSaleItem').click(function() {
			$('#iSalePriceField').toggle('fast');
		});
	
	// Display wholesale price field on product admin, only when wholesale item box is ticked (jQuery)
		// Hide the wholesale price field if the item is not on sale
		$('#iWholesalePriceField.hidden').hide();
		
		// Toggle view of wholesale price field
		$('#bWholesaleItem').click(function() {
			$('#iWholesalePriceField').toggle('fast');
		});	

	// Display categories checkbox menu in reports only when clicked
		// Hide the categories checkboxes
		$('#l_iCategoryIDDiv.hidden').hide();
		
		// Toggle view of categories
		$('#l_iCategoryID').click(function() {
			$('#l_iCategoryIDDiv').toggle('fast');
		});	


	// Sort order display
	// Hide the list of display orders
		$('#sortOrder ul').hide();

	// Toggle view of display order list
		$('#sortOrder p').click(function() {
			$('#sortOrder ul').toggle('fast');
		});

	// 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').change(function() {
				$('#form_delivery').toggle('fade');
				return false;
			});		

		// 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");
												
				}); 
			}
			
	if ( $("#fpPromotionImage").length > 0 ) { 					
	   $('#fpPromotionImage').codaSlider({
		   	autoSlide: true,
		   	autoSlideInterval: 6000,
			slideEaseDuration: 2500,
		   	autoSlideStopWhenClicked: true,
			dynamicArrows: false,
        	dynamicTabs: false		   
	   });
	};			

	// Wordpress JS hooks
	// Check the comments form exists on this page
	if ( $("#commentform").length > 0 ) { 		
		$("#commentform").validate({
		  highlight: function(element, errorClass) {
			 $(element).addClass(errorClass);
			 $(element.form).find("label[for=" + element.id + "]")
							.addClass(errorClass);
		  },
		  unhighlight: function(element, errorClass) {
			 $(element).removeClass(errorClass);
			 $(element.form).find("label[for=" + element.id + "]")
							.removeClass(errorClass);
		  },

		  errorElement: "strong"
		});
	};

});

// Horrid legacy javascript
	// Show / Hide Content (Simple Version)
	function toggleContentSimple(el) {
	
	  var myelement = document.getElementById(el);
	  var myimg = document.getElementById("btn-" + el);
	
	  if( !myelement.style.display || myelement.style.display == "none" ) {
		myelement.style.display = "inline";
	  } else {
		myelement.style.display = "none";
	  }
	}
	
	// Show / Hide Content
	function toggleContent(el) {
	
	  var myelement = document.getElementById(el);
	  var myimg = document.getElementById("btn-" + el);
	
	  if( !myelement.style.display || myelement.style.display == "none" ) {
		myelement.style.display = "inline";
		myimg.src= "/img/icons/btnContract.gif";
	  } else {
		myelement.style.display = "none";
		myimg.src= "/img/icons/btnExpand.gif";
	  }
	}

