// Add event function
function addEvent(elm, evType, fn, useCapture) {
	if(elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
		}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
		}
	else {
		elm['on' + evType] = fn;
		}
	}

// (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;		
	});		

	// Check the promotional image exists on this page
	if ( $("#fpPromotionImage").length > 0 ) { 	
		// Slideshow - Front page promotion images
		$(function() {
			$('#fpPromotionImage').cycle({
				speed: 	500,
				fit:	1
			});
		});	
	}

	// 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: 300,
				viewportHeight: 300,
				topX: 150,
				topY: 150,
				bottomX: 450,
				bottomY: 450,
				loading: '/img/elements/loading.gif'
			});
		});
		
		$("#productImageDragtext").fadeIn();
		
		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();

		// 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;	
	});
	
	// 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, search for the wishlist id and change it.
					$('#loginSuccess').livequery(function() {
						$('#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>");
					});
				}
			});
		});
	});
	
	// WishList Move to cart link
	$('.moveToCart').click(function() {
		$(this).closest('.wishListRow').fadeOut('fast');
		});


	// 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;
		});

	
	// 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'); 
			}
		}); 
	}
	
	// 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");
											
			}); 
		}
});

// 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";
	  }
	}

