/**
 * Plugin dependent functions
 */
$(function(){
	// Enable the png transparency hack
	$('body').supersleight({shim: '/images/blank.gif'});
	
	enableTopMenu();
	
	zIndexHandler();
});



/**
 * Sorts out the z-index bug in ie
 */
function zIndexHandler(){
	var zIndexNumber = 1000;
	$('div, ul, li').each(function() {
		$(this).css('zIndex', zIndexNumber);
		zIndexNumber -= 1;
	});
}

/**
 * Enables the top pulldown menu (Requires HoverIntent)
 */
function enableTopMenu(){
	
	// First setup the hoverIntent options
	var $config = {
			over:	openTopNav,
			timeout:	300,
			out:	closeTopNav
	};
	
	// need to find all the a.depMain links
	$('li.depMain').hoverIntent($config);
}

/**
 * Top nav open action handler
 */
function openTopNav(){
	// Find the first a and add a class of active
	$(this).find('a:first').addClass('active');
	// Set the z-index of subnavs to 000 and slide them up
	$('div.subNav').css({zIndex:'999'}).slideUp('100');
	// Now make THIS subnav 1001 and slidedown
	$(this).find('div.subNav').css({zIndex:'1001'}).slideDown('fast');
}

/**
 * Top nav close action handler
 */
function closeTopNav(){
	// Remove the added class of active
	$(this).find('a:first').removeClass('active');
	// Slide up the subnav div
	$(this).find('div.subNav').slideUp('fast');
}

/**
 * jQuery function to show and then hide the basket feedback
 */
$(function(){
	// This will fade the feedback in and out if no mouse interaction
	$('#feedback-container').delay(500).fadeIn(500, enableMouseStop).delay(4000).fadeIn(1,disableMouseStop).fadeOut(500);
	// $('#feedback-container').delay(1000).fadeIn(1000); << USE THIS LINE TO STYLE UP THE BASKET FEEDBACK (won't dissapear)
	
	// Once we have rolled over this will handle the click on continue button
	$('#continue-button').click(function(){
		// FIRST unbind the mouseout (so it doesn't stop again)
		$('#mini-basket-feedback').unbind('mouseover');
		
		// Now fade out
		$('#feedback-container').fadeOut(200);
		
		// And return false so that our fallback link isn't followed!
		return false;
	});
});



/** THIS HANDLES THE PRODUCT PAGE TABS **/
$(function(){
	// Show the panel tabs
	// They would be hidden normally since we are gracefully degrading
	$('.infoTab').show();
	
	// Each infopanel
	$('.infoPanel').each(function(index){
		// Does it have a class of selected
		if($(this).hasClass('selected')){
			// yes, do nothing
		}else{
			// no hide it
			$(this).hide();
		}
	});
	
	$('.infoTab').click(function(){
		$('.infoTab').removeClass('selected');
		$(this).addClass('selected');
		
		var id = $(this).attr('id');
		id = id.replace("tab","panel");
		
		$('.infoPanel').hide();
		$('#'+id).show();
		$(this).focus();
		
	});
	
	
	// Create something that will fire tab 2 off should the review link be clicked.
	$('p.review-link').click(function(){
		$('#tab2').click();
		$('html, body').animate({scrollTop: $('#panel2').offset().top}, 500);
	});
});


$(function(){
	newImageHandler();
});

/**
 * Product Image Click Handler
 */
function newImageHandler(){
	$('p.jsProductImage').click(function(){							// Each a tag with class jsProductImage
		$('#productImageImg').attr('src',$(this).attr('rel'))		// Set the main image src to this images href
								.attr('alt',$(this).attr('title'));	// and set it's alt to this ones title
		
		$('#cloud-zoom').attr('href', $(this).attr('href')).attr('title', $(this).attr('title'));
		$('#cloud-zoom').data('zoom').destroy();
		$('#cloud-zoom').CloudZoom();
		return false;
	});
}


/**
 * Enables the mouseover event on the Basket Feedback
 *  
 * @return
 */
function enableMouseStop(){
	// Create a listener for the feedback on mouseover
	$('#mini-basket-feedback').mouseover(function(){
		
		/* need to handle a failed add to basket */
		if($(this).hasClass('closeAuto')){
			
			/* ignore the mouseover */
			
		}else{
			// Stop all animation, clear queue and do not jump to end
			$('#feedback-container').stop(true,false);
		}
		
	});
}

/**
 * Disables the mouseoever event on the basket feedback
 * 
 * @return
 */
function disableMouseStop(){
	$('#mini-basket-feedback').unbind('mouseover');
}

/**
 * jQuery function to clear searchbox on click and focus
 * Will automatically add 'search' to the box if it's clear on focusout
 * 
 */
$(function(){
	// When we focus on the searchterm
	$('#searchTerm').focusin(function(){
		// Store the search term
		var search = $('#searchTerm').val();
		
		// Is it search?
		if(search == "SEARCH THE SITE"){
			// Yes so blank it
			$('#searchTerm').val("");
		}
	});
	
	// When the search box loses focus
	$('#searchTerm').focusout(function(){
		// Store the search term
		var search = $('#searchTerm').val();
		
		// Is it blank
		if(search == ""){
			// Yes it is so stick search in it
			$('#searchTerm').val("SEARCH THE SITE");
		}
	});
	
	// When we click on the search box
	$('#searchTerm').click(function(){
		// Store the search value
		var search = $('#searchTerm').val();
		
		// Is it search?
		if(search == "SEARCH THE SITE"){
			// Yes so blank it
			$('#searchTerm').val("");
		}
	});
});

/* Product Section Functions */


/**
 * jQuery function to animate the swatch rollovers
 * 
 */
$(function(){
	// Anything with a class of .swatchtainer with a li inside has a hover event attached
	$(".swatchtainer li").hover(function(){
			// First animate the found li to make it taller and slide it up
			$(this).animate({height: "45px", top: "-28px"}, "fast");
			
			// Find Then animate out the inner span to show the swatch
			$(this).find("span").animate({width: "92px", opacity: "show", left: "0"}, "normal");
		},
		function(){	
			// First find then slide in the span to hide the swatch
			$(this).find("span").animate({width: "0px", opacity: "hide", left: "0"}, "fast");
			
			// Now slide down and reduce the height of the li
			$(this).animate({height: "17px", top: "0px"}, "normal");
		});// End of sub-functions
});



// Drop Down Style Product Options Handlers

$(function() {
	// Add on change to product option one.
	$("#ProductOptions1").change(function(){
			counter = $(this).attr("counter");
			
			// Hack attack
			if($(this).attr("attributeId" == 2)){
				// We need to use the opposite attribute to what we have already got
				attributeId = 3;
			}
			else{
				attributeId = 2;
			}
			productId = $(this).attr("productId");
			parentValue = $(this).val();
			
			loadProductMenu2(counter, attributeId, productId, parentValue);
		}
	);
});


function loadProductMenu2(counter, attributeId, productId, parentValue){
	// Load 
	$.ajax({url: "/ajax/options/?counter="+counter+"&attributeId="+attributeId+"&productId="+productId+"&parentValue="+parentValue,
		  	success: function(data){
		    			$('#ProductOptions2Wrapper').html(data);
		    			setupSecondAttributes();
		    			// loadPrice();
		  			}
			});
}

$(function(){
	
	setupSecondAttributes();
	
	// If the form item name attribute 1 changes run a function
	$('[name=attribute3]').change(function(){
		// Get the value of this option
		var option1 = $('[name=attribute3] option:selected').val();
		
		// We want the product id
		productId = $(this).attr("productId");
		
		// Chuck this to the updater only if we have a product Id
		if(productId){
			updatePrice(option1, productId);
		}
		
	});
	
	
	
});

function setupSecondAttributes(){
	// If the form item name attribute 2 changes run a function
	$('[name=attribute2]').change(function(){
		// Get the value of this option
		var option2 = $('[name=attribute2] option:selected').val();
		
		// We want the product id
		productId = $(this).attr("productId");
		
		// Chuck this to the updater only if we have a product Id
		if(productId){
			updatePrice(option2, productId);
		}
		
	});
}

// This will call in the ajax required to update the price shown on the site
function updatePrice(option, productId){
	// Load 
	$.ajax({url: "/ajax/prices/?skuOption="+option+"&productId="+productId,
		  success: function(data) {
		    $('p.priceBlack').replaceWith(data);
		  }
		});
}

/**
 * Will run the updater code on load
 * 
 * 
 */
$(function(){
	counter = $("#ProductOptions1").attr("counter");
	
	// Hack attack
	if($("#ProductOptions1").attr("attributeId" == 2)){
		// We need to use the opposite attribute to what we have already got
		attributeId = 3;
	}
	else{
		attributeId = 2;
	}
	productId = $("#ProductOptions1").attr("productId");
	parentValue = $("#ProductOptions1").val();

	loadProductMenu2(counter, attributeId, productId, parentValue);
});

/**
 * Will run the price call on load
 * 
 */
function loadPrice()
{
	// Check for an option 1
	var option1 = $('[name=attribute3] option:selected').val();
	
	// Check for a product Id
	var productId1 = $('[name=attribute3]').attr("productId");
	
	if(productId1){
		updatePrice(option1, productId1);
	}
	
	// Check for an option 2
	var option2 = $('[name=attribute2] option:selected').val();
	
	// Check for product Id
	var productId2 = $('[name=attribute2]').attr("productId");
	
	if(productId2){
		updatePrice(option2, productId2)
	}
}

/**
 * Handles clicks for the add to basket button
 * 
 */
$(function(){
	// On out basket button click
	$('#product-add-basket').click(function(){
		// Check the value of attribute 1
		if($('[name=attribute3]').val() == "Please select ->"){
			// Alert an error
			alert("Please select an option from the drop down menus to add an item to your basket.");
			
			// Return false so we can't post a nothing
			return false;
		}
		// Now check attribute 2
		else if($('[name=attribute2]').val() == "Please select ->"){
			// Alert an error
			alert("Please select an option from the drop down menus to add an item to your basket.");
			
			// Return false so we can't post a nothing
			return false;
		}
		else{
			// Else return true and good to go
			return true;
		}
		
	});
});

$(function(){
	$('#basket-show').click(showMiniBasket);
})

var basketMoving = false;

/**
 * Basket show handler
 * @returns {Boolean}
 */
function showMiniBasket(){
	
	// Is the basket moving now?
	if(basketMoving == false){
		// it is now!
		basketMoving = true;
		
		// Run an unbind
		$('#basket-show').unbind('click');
		
		// Hide Select boxes that are underneath if there are any
		$('#product-options').find('select').each(function(){
			$(this).hide();
		});
		
		// Display the hidden basket
		$('#hidden-basket').slideDown('400',function(){
			// Set moving to false
			basketMoving = false;
			// Now add a new click event
			$('#basket-show').click(hideMiniBasket);
			// Add a click to the body that will hide the basket
			$('body, html').one('click',hideMiniBasket);
			// Create a none-propagation link so that if we click the basket it won't dissapear!
			$('#small-basket').click(function(event){
				// Stop click propagation (to the body or html)
				event.stopPropagation();
			});
		});
	}
	// Return false
	return false;
}

/**
 * Basket hide handler
 * @returns {Boolean}
 */
function hideMiniBasket(){
	
	// Is the basket moving now?
	if(basketMoving == false){
		
		// it is now
		basketMoving = true;
		
		// Run an unbind
		$('body, html, #basket-show, #small-basket').unbind('click');
		// Slide up
		$('#hidden-basket').slideUp('400',function(){
			// Set moving to false
			basketMoving = false;
			// Now add new click event
			$('#basket-show').click(showMiniBasket);
			// Show Select boxes that are underneath if there are any
			$('#product-options').find('select').each(function(){
				$(this).show();
			});
		});
	}
	// Return false
	return false;
}


/* NEW CUSTOMER SCRIPTS */

// Ok add a listener to the form submit for new customers
$(function(){
	// When the document is ready
	$('#checkout').submit(function(){
		$('input').removeClass('error');
		
		// Assume all is good to go
		var valid = true;
		
		// Run through all fields and check
		if($('#firstname').val() == ""){			
			$('#firstname').addClass('error');
			
			valid = false;
			alert("Please enter your first name");
			$('html, body').animate({scrollTop: $('#firstname').offset().top}, 500);
			return false;
		}
		
		if($('#surname').val() == "")
		{
			$('#surname').addClass('error');
			
			valid = false;
			alert("Please enter your surname");
			$('html, body').animate({scrollTop: $('#surname').offset().top}, 500);
			return false;
		}
		
		if($('#telephone').val() == "")
		{
			$('#telephone').addClass('error');
			
			valid = false;
			alert("Please enter your telephone number");
			$('html, body').animate({scrollTop: $('#telephone').offset().top}, 500);
			return false;
		}
		
		if(($('#jsEmail1').val() == "") || ($('#jsEmail2').val() == ""))
		{
			$('#jsEmail1').addClass('error');
			$('#jsEmail2').addClass('error');
			
			valid = false;
			alert("Please enter your email address into both boxes");
			$('html, body').animate({scrollTop: $('#jsEmail1').offset().top}, 500);
			return false;
		}
		
		if($('#jsEmail1').val() != $('#jsEmail2').val())
		{
			$('#jsEmail1').addClass('error');
			$('#jsEmail2').addClass('error');
			
			valid = false;
			alert("Please enter the same email address into both boxes");
			$('html, body').animate({scrollTop: $('#jsEmail1').offset().top}, 500);
			return false;
		}
		
		if(checkValidEmail($('#jsEmail1').val()) == false)
		{
			$('#jsEmail1').addClass('error');
			$('html, body').animate({scrollTop: $('#jsEmail1').offset().top}, 500);
			valid = false;
			return false;
		}
				
		if(($('#password1').val() == "") || ($('#password2').val() == ""))
		{
			$('#password1').addClass('error');
			$('#password2').addClass('error');
			
			valid = false;
			alert("Please enter a password into both boxes");
			$('html, body').animate({scrollTop: $('#password1').offset().top}, 500);
			return false;
		}

		var password = $('#password1').val();
		
		if(password.length < 6)
		{
			$('#password1').addClass('error');
			$('#password2').addClass('error');
			
			valid = false;
			alert("Please enter a password which is as least 6 characters long");
			$('html, body').animate({scrollTop: $('#password1').offset().top}, 500);
			return false;
		}
		
		if($('#password1').val() != $('#password2').val())
		{
			$('#password1').addClass('error');
			$('#password2').addClass('error');
			
			valid = false;
			alert("Please enter the same password into both boxes");
			$('html, body').animate({scrollTop: $('#password1').offset().top}, 500);
			return false;
		}
		
		// Now on to the addresses!
		if($('#billing1').val() == "")
		{
			$('#billing1').addClass('error');
			
			valid = false;
			alert("Please enter the first line of your billing address");
			$('html, body').animate({scrollTop: $('#billing1').offset().top}, 500);
			return false;
		}
		
		if($('#billingTown').val() == "")
		{
			$('#billingTown').addClass('error');
			
			valid = false;
			alert("Please enter the town of your billing address");
			$('html, body').animate({scrollTop: $('#billingTown').offset().top}, 500);
			return false;
		}
		
		if($('#billingCounty').val() == "")
		{
			$('#billingCounty').addClass('error');
			
			valid = false;
			alert("Please enter the county of your billing address");
			$('html, body').animate({scrollTop: $('#billingCounty').offset().top}, 500);
			return false;
		}
		
		if($('#billingPostcode').val() == "")
		{
			$('#billingPostcode').addClass('error');
			
			valid = false;
			alert("Please enter the postcode of your billing address");
			$('html, body').animate({scrollTop: $('#billingPostcode').offset().top}, 500);
			return false;
		}
		
		if($('#delivery1').val() == "")
		{
			$('#delivery1').addClass('error');
			
			valid = false;
			alert("Please enter the first line of your delivery address");
			$('html, body').animate({scrollTop: $('#delivery1').offset().top}, 500);
			return false;
		}
		
		if($('#deliveryTown').val() == "")
		{
			$('#deliveryTown').addClass('error');
			
			valid = false;
			alert("Please enter the town of your delivery address");
			$('html, body').animate({scrollTop: $('#deliveryTown').offset().top}, 500);
			return false;
		}
		
		if($('#deliveryCounty').val() == "")
		{
			$('#deliveryCounty').addClass('error');
			
			valid = false;
			alert("Please enter the county of your delivery address");
			$('html, body').animate({scrollTop: $('#deliveryCounty').offset().top}, 500);
			return false;
		}
		
		if($('#deliveryPostcode').val() == "")
		{
			$('#deliveryPostcode').addClass('error');
			
			valid = false;
			alert("Please enter the postcode of your delivery address");
			$('html, body').animate({scrollTop: $('#deliveryPostcode').offset().top}, 500);
			return false;
		}
		
		// Now run a double check
		if(valid == true)
		{
			return true;
		}
		else
		{
			return false;
		}
			
	});
});

// Add event listener to the edit customer form
$(function()
{
	// When the document is ready
	$('#edit-customer').submit(function()
	{
		$('input').removeClass('error');
		
		// Assume all is good to go
		var valid = true;
		
		// Run through all fields and check
		if($('#firstname').val() == "")
		{			
			$('#firstname').addClass('error');
			
			valid = false;
			alert("Please enter your first name");
			$('html, body').animate({scrollTop: $('#firstname').offset().top}, 500);
			return false;
		}
		
		if($('#surname').val() == "")
		{
			$('#surname').addClass('error');
			
			valid = false;
			alert("Please enter your surname");
			$('html, body').animate({scrollTop: $('#surname').offset().top}, 500);
			return false;
		}
		
		if($('#telephone').val() == "")
		{
			$('#telephone').addClass('error');
			
			valid = false;
			alert("Please enter your telephone number");
			$('html, body').animate({scrollTop: $('#telephone').offset().top}, 500);
			return false;
		}
		
		if($('#jsEmail').val() == "")
		{
			$('#jsEmail').addClass('error');
			
			valid = false;
			alert("Please enter your email address");
			$('html, body').animate({scrollTop: $('#jsEmail').offset().top}, 500);
			return false;
		}
		
		if(checkValidEmail($('#jsEmail').val()) == false)
		{
			$('#jsEmail').addClass('error');
			$('html, body').animate({scrollTop: $('#jsEmail').offset().top}, 500);
			valid = false;
			return false;
		}
						
		// Now on to the addresses!
		if($('#billing1').val() == "")
		{
			$('#billing1').addClass('error');
			
			valid = false;
			alert("Please enter the first line of your billing address");
			$('html, body').animate({scrollTop: $('#billing1').offset().top}, 500);
			return false;
		}
		
		if($('#billingTown').val() == "")
		{
			$('#billingTown').addClass('error');
			
			valid = false;
			alert("Please enter the town of your billing address");
			$('html, body').animate({scrollTop: $('#billingTown').offset().top}, 500);
			return false;
		}
		
		if($('#billingCounty').val() == "")
		{
			$('#billingCounty').addClass('error');
			
			valid = false;
			alert("Please enter the county of your billing address");
			$('html, body').animate({scrollTop: $('#billingCounty').offset().top}, 500);
			return false;
		}
		
		if($('#billingPostcode').val() == "")
		{
			$('#billingPostcode').addClass('error');
			
			valid = false;
			alert("Please enter the postcode of your billing address");
			$('html, body').animate({scrollTop: $('#billingPostcode').offset().top}, 500);
			return false;
		}
		
		if($('#delivery1').val() == "")
		{
			$('#delivery1').addClass('error');
			
			valid = false;
			alert("Please enter the first line of your delivery address");
			$('html, body').animate({scrollTop: $('#delivery1').offset().top}, 500);
			return false;
		}
		
		if($('#deliveryTown').val() == "")
		{
			$('#deliveryTown').addClass('error');
			
			valid = false;
			alert("Please enter the town of your delivery address");
			$('html, body').animate({scrollTop: $('#deliveryTown').offset().top}, 500);
			return false;
		}
		
		if($('#deliveryCounty').val() == "")
		{
			$('#deliveryCounty').addClass('error');
			
			valid = false;
			alert("Please enter the county of your delivery address");
			$('html, body').animate({scrollTop: $('#deliveryCounty').offset().top}, 500);
			return false;
		}
		
		if($('#deliveryPostcode').val() == "")
		{
			$('#deliveryPostcode').addClass('error');
			
			valid = false;
			alert("Please enter the postcode of your delivery address");
			$('html, body').animate({scrollTop: $('#deliveryPostcode').offset().top}, 500);
			return false;
		}
		
		// Now run a double check
		if(valid == true)
		{
			return true;
		}
		else
		{
			return false;
		}
			
	});
});



//------------------------
//Billing and Delivery Address are the same so lets auto complete
//------------------------

$(function(){
	$('#jsAutoComplete').click(autoCompleteAddress);
});

/**
 * Auto Complete for the customer address fields
 * 
 * @return
 */
function autoCompleteAddress(){	
	$('#delivery1').val($('#billing1').val());
	$('#delivery2').val($('#billing2').val());
	$('#delivery3').val($('#billing3').val());
	$('#deliveryTown').val($('#billingTown').val());
	$('#deliveryCounty').val($('#billingCounty').val());
	$('#deliveryPostcode').val($('#billingPostcode').val());
	$('html, body').animate({scrollTop: $('#delivery1').offset().top}, 500);
	// Country Menu
	document.getElementById("form-deliveryCountry").selectedIndex = document.getElementById("form-billingCountry").selectedIndex;
	
	return false;
}

/* End of Customer Functions */


/* Basket Function */

// Update postage cookie
function submitBasket(){
	$('#full-basket').submit();
}

// Remove code and submit the basket
function removeBasketPromo(){
	document.basket.promoCode.value = "";
	$('#full-basket').submit();
}

// Update postage details on order confirmation page
function submitPostageChange(){
	document.postage.submit();
}


$(function(){
	$('#postageRegion').change(function(){
		$('#full-basket').submit();
	});
	
	$('#postageUpgrade').change(function(){
		$('#full-basket').submit();
	});
})

/* End of Basket Functions */


/* Account Functions */

/**
 * Validates the account profile form
 * 
 * @return
 */
function validateContactForm()
{
	// Assume we are okay unless otherwise
	var valid = true;
	
	$('input').removeClass('error');
	
	// $('#deliveryCounty').addClass('error');
	
	// valid = false;
	// alert("Please enter the county of your delivery address");
	// $('html, body').animate({scrollTop: $('#deliveryCounty').offset().top}, 500);
	// return false;
	
	if($('#firstname').val() == "")
	{
		$('#firstname').addClass('error');
		valid = false;
		alert("Please enter your firstname");
		$('html, body').animate({scrollTop: $('#firstname').offset().top}, 500);
		return false;
	}
	
	if($('#surname').val() == "")
	{
		$('#surname').addClass('error');
		valid = false;
		alert("Please enter your surname");
		$('html, body').animate({scrollTop: $('#surname').offset().top}, 500);
		return false;
	}
	
	if($('#telephone').val() == "")
	{
		$('#telephone').addClass('error');
		valid = false;
		alert("Please enter your telephone number");
		$('html, body').animate({scrollTop: $('#telephone').offset().top}, 500);
		return false;
	}
	
	if(valid == true)
	{
		$('#contact').submit();
	}
	else
	{
		return false;
	}
}

/**
 * Validates the new address form in accounts section
 * 
 * @return
 */
function validateNewAddress()
{
	// Assume we are okay unless otherwise
	var valid 	= true;
	
	$('input').removeClass('error');
	
	if($('#address1').val() == "")
	{
		$('#address1').addClass('error');
		valid = false;
		alert("Please enter your address");
		$('html, body').animate({scrollTop: $('#address1').offset().top}, 500);
		return false;
	}
	
	if($('#town').val() == "")
	{
		$('#town').addClass('error');
		valid = false;
		alert("Please enter your town");
		$('html, body').animate({scrollTop: $('#town').offset().top}, 500);
		return false;
	}
		
	if($('#county').val() == "")
	{
		$('#county').addClass('error');
		valid = false;
		alert("Please enter your county");
		$('html, body').animate({scrollTop: $('#county').offset().top}, 500);
		return false;
	}
	
	if($('#postcode').val() == "")
	{
		$('#postcode').addClass('error');
		valid = false;
		alert("Please enter your postcode");
		$('html, body').animate({scrollTop: $('#postcode').offset().top}, 500);
		return false;
	}
	
	if(valid == true)
	{
		$('#addressform').submit();
	}
	else
	{
		return false;
	}
}

/**
 * Checks the password values for the edit password part of accounts
 * 
 * @return
 */
function checkPassword()
{
	var valid   = true;
	var message = "";
	
	// Go through the password fields to ensure all is working
	if(document.security.password1.value == "")
	{
		valid = false;
		message = "Please enter a new password into both boxes";
		alert(message);
		return;
	}
	
	if(document.security.password2.value == "")
	{
		valid = false;
		message = "Please enter a new password into both boxes";
		alert(message);
		return;
	}
	
	if(document.security.password1.value.length < 6)
	{
		valid = false;
		message = "Please enter a new password which is at least 6 characters long";
		alert(message);
		return;
	}
	
	if(document.security.password2.value.length < 6)
	{
		valid = false;
		message = "Please enter a new password which is at least 6 characters long";
		alert(message);
		return;
	}
	
	if(document.security.password1.value != document.security.password2.value)
	{
		valid = false;
		message = "Please check that you have entered the same new password into both boxes";
		alert(message);
		return;
	}
	
	if(valid == true)
	{
		document.security.submit();
	}
	else
	{
		return false;
	}
}

/* End of Account Functions */

// GLOBALLY USED FUNCTIONS

/**
 * Email Validator Function
 * 
 * @param 	str
 * @return	boolean
 */
function checkValidEmail(str) 
{
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	
	if (str.indexOf(at)==-1)
	{
		alert("Please check that you have correctly entered your email address");
		return false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
	{
		alert("Please check that you have correctly entered your email address");
		return false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
	{
		alert("Please check that you have correctly entered your email address");
		return false;
	}

	if (str.indexOf(at,(lat+1))!=-1)
	{
		alert("Please check that you have correctly entered your email address");
		return false;
	}

	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
	{
		alert("Please check that you have correctly entered your email address");
		return false;
	}

	if (str.indexOf(dot,(lat+2))==-1)
	{
		alert("Please check that you have correctly entered your email address");
		return false;
	}
		
	if (str.indexOf(" ")!=-1)
	{
		alert("Please check that you have correctly entered your email address");
		return false;
	}

 	return true;				
}


// NEW FUNCTIONS IN HERE FOR PRODUCT IMAGE SLIDER
$(function(){
	setupProductImages('#productImages',83,500);
})

// This is a global variable so we can track it within 2 functions
var moving = false;

/**
 * Sets up the image up/down arrows on the product page
 * is self calling, and will pass it's own variables to
 * itself when it loops so that nothing is changed.
 * 
 * @param parent		Wrapping container, ul, div etc
 * @param distance		Distance in px that you want it to move (currently vertically)
 * @param speed			How fast in ms you want it to move
 */
function setupProductImages(parent,distance,speed){
	
	// First setup the image items
	var firstItem = $(parent).find('>:first');
	var lastItem  = $(parent).find('>:last');
	
	
	// Okay we have those, great, setup the clicks
	$('.jsDownArrow').unbind('click').one('click',function(){
		
		// Only activate if we are not already moving
		if(moving == false){
			
			// Set moving to true
			moving = true;
			
			// Start animating and fancyness
			$(firstItem).css({'marginTop':'0px'})
						.animate({'marginTop':'-'+distance+'px'},
						speed,
						function(){
							
							// Okay we're all done, set moving to false
							moving = false;
							
							// Reset margin and detach
							$(firstItem).css({'marginTop':''}).detach();
							
							// Now insert it after the last item
							$(firstItem).insertAfter(lastItem);
							
							// Recall ourselves
							setupProductImages(parent,distance,speed);
							
						});
		} else {
			// Do nothing since we're animating already
		}
		// Override default behaviour
		return false;
	});
	
	$('.jsUpArrow').unbind('click').one('click', function(){
		
		// Only activate if we are not already moving
		if(moving == false){
			
			// Set moving to true
			moving = true;
			
			// We need to grab the last item first by setting it's margin to negative and detaching it
			$(lastItem).css({'marginTop':'-'+distance+'px'}).detach();
			
			// Copy it into the space next to the first item
			$(lastItem).insertBefore(firstItem);
			
			// Now run the animation
			$(lastItem).animate({'marginTop':'0px'},
								speed,
								function(){
									
									// Okay all done now reset moving var
									moving = false;
									
									// Recall ourselves
									setupProductImages(parent,distance,speed);
								});
		} else {
			// Do nothing since we're animating already
		}
		// Override default behaviour
		return false;
	});
	
}





// Set a global variable here
var moving = false;
var timer = 0;
var firstItem = "";

/**
 * Sets Up our Image Animations
 * 
 * 
 * @param parent	The item containing the items to be moved
 * @param distance	The width of a single item so we know how far to animate
 */
function setupImageSwap(parent,distance,speed){
	
	/* We need to find the first and last items to begin with 
	by using direct descenders and first and last sudo classes
	*/
	
	firstItem 	= $(parent).find('>:first');
	var lastItem 	= $(parent).find('>:last');
	
	// Need to make sure the a doesn't do anything
	$(firstItem).find('a').click(function(event){
		$(firstItem).unbind('click');
	});
	
	// Okay great now we have those...
	
	// First the move left (right arrow)
	$(firstItem).unbind('click').one('click',function(){
		// First clear the timer
		clearTimeout(timer);
		// ONLY ACTIVATE ONCE WE HAVE DONE MOVING
		if(moving == false){
			
			// We're moving, set it to true
			moving = true;
			
			// Animate the first item
			$(firstItem).css({'marginleft':'0px'})			// First set margin to 0
							 .animate({'marginLeft': '-'+distance+'px'}, 
							 speed,	
							 function(){
								 
								 // Okay animation complete set moving to false
								 moving = false;
								 
								 // Reset margin and detach
								 $(firstItem).css({'marginLeft':''}).detach();
								 
								 // Now insert it after the last item
								 $(firstItem).insertAfter(lastItem);
								 
								 // Recall ourselves
								 setupImageSwap(parent,distance,speed);
								 
							});
		} else {
			// DO NOTHING WE'RE STILL ANIMATING
		}
		
	});
	
	// First clear the timer
	clearTimeout(timer);
	// Run a timer
	timer = setTimeout("$(firstItem).click()", 10000);
	
	
}
