	/* FUNCTION TO ENABLE THE BUYING PANEL */
/* This function came from jQuery UI documentation and I haven't gone through and figured it out yet comments to come soon */
(function( $ ) {
	$.widget( "ui.combobox", {
		_create: function() {
			var self = this,
				select = this.element.hide(),
				selected = select.children( ":selected" ),
				value = selected.val() ? selected.text() : "";
			var input = this.input = $( "<input disabled=\"disabled\">" )
				.insertAfter( select )
				.val( value )
				.autocomplete({
					delay: 0,
					minLength: 0,
					source: function( request, response ) {
						var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
						response( select.children( "option" ).map(function() {
							var text = $( this ).text();
							if ( this.value && ( !request.term || matcher.test(text) ) )
								return {
									label: text.replace(
										new RegExp(
											"(?![^&;]+;)(?!<[^<>]*)(" +
											$.ui.autocomplete.escapeRegex(request.term) +
											")(?![^<>]*>)(?![^&;]+;)", "gi"
										), "<strong>$1</strong>" ),
									value: text,
									option: this
								};
						}) );
					},
					select: function( event, ui ) {
						ui.item.option.selected = true;
						self._trigger( "selected", event, {
							item: ui.item.option
						});
						updatePrices(this);
					},
					change: function( event, ui ) {
						if ( !ui.item ) {
							var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
								valid = false;
							select.children( "option" ).each(function() {
								if ( $( this ).text().match( matcher ) ) {
									this.selected = valid = true;
									return false;
								}
							});
							if ( !valid ) {
								// remove invalid value, as it didn't match anything
								$( this ).val( "" );
								select.val( "" );
								input.data( "autocomplete" ).term = "";
								return false;
							}
						}
					}
				})
				.addClass( "ui-widget ui-widget-content ui-corner-left" );

			input.data( "autocomplete" )._renderItem = function( ul, item ) {
				return $( "<li></li>" )
					.data( "item.autocomplete", item )
					.append( "<a>" + item.label + "</a>" )
					.appendTo( ul );
			};

			this.button = $( "<button type='button'>&nbsp;</button>" )
				.attr( "tabIndex", -1 )
				.attr( "title", "Select a different option" )
				.insertAfter( input )
				.button({
					icons: {
						primary: "ui-icon-triangle-1-s"
					},
					text: false
				})
				.removeClass( "ui-corner-all" )
				.addClass( "ui-corner-right ui-button-icon" )
				.click(function() {
					// close if already visible
					if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
						input.autocomplete( "close" );
						return;
					}

					// pass empty string as value to search for, displaying all results
					input.autocomplete( "search", "" );
					input.focus();
				});
		},

		destroy: function() {
			this.input.remove();
			this.button.remove();
			this.element.show();
			$.Widget.prototype.destroy.call( this );
		}
	});
})( jQuery );

$(function() {
	enableBoxes();
});

function enableBoxes(){
	$( ".jsFormatOption" ).combobox();
	$( ".jsTreatmentOption" ).combobox();
	updatePrices();
	enableQtyBoxes();
	enableBuyButtons();
	enableMiniBasket();	// This is in clicksale.js
	smallBasketActions();	// This is in clicksale.js
}


function updatePrices(item){
	// Ajaxform needed here
	var options = {
			target: $(item).parents('.buyingPanelWrapper'),
			replaceTarget: true,
			url:	"/ajax/buying-panel/",
			success: enableBoxes
	};
	
	// Apply this to the form
	$(item).parents('form.buyingPanelForm').ajaxForm(options).submit();
}


function fetchPrice(item){
	// Ajaxform needed!
	var options = {
			target: $(item).parents('.buyingPanelWrapper').find('p.totalPrice'),
			replaceTarget: true,
			url:	"/ajax/bulk-price/"
	};
	// Setup and send the form
	$(item).parents('form.buyingPanelForm').ajaxForm(options).submit();
}

$(function(){
	basketQuantityUpdates();
});

function basketQuantityUpdates(){
	
	// Unbind to prevent memory issue
	$('.basketQtyShow').unbind('blur').unbind('keyup');
	
	// Need to add a blur event to the qtyShows
	$('.basketQtyShow').blur(function(){
		
		// Get the value
		var showQty = $(this).val();
		
		// Get the value of the select box
		var qtyMulti = $(this).parents('div.basket-qty-form').find('select[name=basketWeightSelector]').val();
		
		// Work out the actual quantity
		var qty = showQty / qtyMulti;
		
		// Now update the hidden quantity box
		$(this).parents('div.basket-qty-form').find('input.basketQty').val(qty);
		
	});
	
	// Now to the keyup
	$('.basketQtyShow').keyup(function(){
		
		// Get the value
		var showQty = $(this).val();
		
		// Get the value of the select box
		var qtyMulti = $(this).parents('div.basket-qty-form').find('select[name=basketWeightSelector]').val();
		
		// Work out the actual quantity
		var qty = showQty / qtyMulti;
		
		// Now update the hidden quantity box
		$(this).parents('div.basket-qty-form').find('input.basketQty').val(qty);
		
	});
	
	// Now we need to do the quantity box selector
	$('.basketWeightSelector').change(function(){
		
		// Store the quantity multiplier to show
		var qtyMulti = $(this).val();
				
		// Now we need to grab the qtyShow Item
		var qtyShowItem = $(this).parents('div.basket-qty-form').find('input.basketQtyShow');
		
		// Get the qty Item
		var qtyItem = $(this).parents('div.basket-qty-form').find('input.basketQty');
		
		// Now the value of the box is the value of the box * multiplier
		$(qtyShowItem).val($(qtyItem).val()*qtyMulti);
		
	});
}

function enableQtyBoxes()
{
	// Unbind to prevent memory leak
	$('.qty').unbind('keyup')
			 .unbind('blur');
	
	// Unbind the qtyShow bit too
	$('.qtyShow').unbind('keyup').unbind('blur');
	
	// Add an event to the keyup on qtyShow
	$('.qtyShow').keyup(function(){
		
		// Get this value 
		var showQty = $(this).val();
		
		// make sure it's not blank
		if(showQty!="" && showQty!=0){
			
			// Now we need to check the select box
			var qtyMulti = $(this).parents('.buyingPanelWrapper').find('select[name=weightSelector]').val();
			
			// Now multiply showQty * the quantityMulti
			var qty = showQty / qtyMulti;
			
			// Update the value of the quantity field
			$(this).parents('.buyingPanelWrapper').find('input[name=qty]').val(qty);
			
			// Find the multiplier
			var multiplierItem = $(this).parents('.buyingPanelWrapper').find('input[name=multiple]');
			
			// Now fetch the multiplier
			var multiplier = $(multiplierItem).val();
			
			// Does division return an integer?
			if(isInt((qty*1000)/(multiplier*1000)))
			{
				// Have removed the attribute to do with disabled here and am firing off a class switch instead
				$(this).parents('.buyingPanelWrapper').find('input[type=image]').attr('src','/images/buttons/addToBasket.gif').removeClass('disabled');
				// yes Fetch the price
				fetchPrice(this);
			}
			else 
			{
				// Have removed the attribute to do with disabled here and am firing off a class switch instead
				$(this).parents('.buyingPanelWrapper').find('input[type=image]').attr('src','/images/buttons/addToBasket.gif').addClass('disabled');
			}
		}
		
	});
	
	// Add an event to the blur on qtyShow
	$('.qtyShow').blur(function(){
		
		// Get this value 
		var showQty = $(this).val();
		
		// make sure it's not blank
		if(showQty!="" && showQty!=0){
			
			// Now we need to check the select box
			var qtyMulti = $(this).parents('.buyingPanelWrapper').find('select[name=weightSelector]').val();
			
			// Now multiply showQty * the quantityMulti
			var qty = showQty / qtyMulti;
			
			// Update the value of the quantity field
			$(this).parents('.buyingPanelWrapper').find('input[name=qty]').val(qty);
			
			// Find the multiplier
			var multiplierItem = $(this).parents('.buyingPanelWrapper').find('input[name=multiple]');
			
			// Now fetch the multiplier
			var multiplier = $(multiplierItem).val();
			
			// Does division return an integer?
			if(isInt((qty*1000)/(multiplier*1000)))
			{
				// Have removed the attribute to do with disabled here and am firing off a class switch instead
				$(this).parents('.buyingPanelWrapper').find('input[type=image]').attr('src','/images/buttons/addToBasket.gif').removeClass('disabled');
				// yes Fetch the price
				fetchPrice(this);
			}
			else 
			{
				// Have removed the attribute to do with disabled here and am firing off a class switch instead
				$(this).parents('.buyingPanelWrapper').find('input[type=image]').attr('src','/images/buttons/addToBasket.gif').addClass('disabled');
			}
		}
		
	});
	
	// Add a change event to the weight selector
	$('.weightSelector').change(function(){
		
		// Store the quantity multiplier to show
		var qtyMulti = $(this).val();
				
		// Now we need to grab the qtyShow Item
		var qtyShowItem = $(this).parents('.buyingPanelWrapper').find('input[name=qtyShow]');
		
		// Get the qty Item
		var qtyItem = $(this).parents('.buyingPanelWrapper').find('input[name=qty]');
		
		// Now the value of the box is the value of the box * multiplier
		$(qtyShowItem).val($(qtyItem).val()*qtyMulti);
		
		
	});
	
	// Standard quantity box keyup
	$('.qty').keyup(function()
	{
		// Store this qty
		var qty = $(this).val();
		
		// Ensure it's not blank
		if(qty!="" && qty!=0)
		{
			// Find the multiplier
			var multiplierItem = $(this).parents('.buyingPanelWrapper').find('input[name=multiple]');
			
			// Now fetch the multiplier
			var multiplier = $(multiplierItem).val();
			
			// Does division return an integer?
			if(isInt((qty*1000)/(multiplier*1000)))
			{
				// Have removed the attribute to do with disabled here and am firing off a class switch instead
				$(this).parents('.buyingPanelWrapper').find('input[type=image]').attr('src','/images/buttons/addToBasket.gif').removeClass('disabled');
				// yes Fetch the price
				fetchPrice(this);
			}
			else 
			{
				// Have removed the attribute to do with disabled here and am firing off a class switch instead
				$(this).parents('.buyingPanelWrapper').find('input[type=image]').attr('src','/images/buttons/addToBasket.gif').addClass('disabled');
			}
		}
	});
	
	
	// Standard quantity box unfocus
	$('.qty').blur(function()
	{
		// Store this qty
		var qty = $(this).val();
		
		// Ensure it's not blank
		if(qty!="" && qty!=0)
		{
			// Find the multiplier
			var multiplierItem = $(this).parents('.buyingPanelWrapper').find('input[name=multiple]');
			
			// Now fetch the multiplier
			var multiplier = $(multiplierItem).val();
			
			// Does division return an integer?
			if(isInt((qty*1000)/(multiplier*1000)))
			{
				// Have removed the attribute to do with disabled here and am firing off a class switch instead
				$(this).parents('.buyingPanelWrapper').find('input[type=image]').attr('src','/images/buttons/addToBasket.gif').removeClass('disabled');
				
				// yes Fetch the price
				fetchPrice(this);
				
			} 
			else 
			{
				// Have removed the attribute to do with disabled here and am firing off a class switch instead
				$(this).parents('.buyingPanelWrapper').find('input[type=image]').attr('src','/images/buttons/addToBasket.gif').addClass('disabled');
			}
		}
	});
}

$(function(){
	
	// enableArrowKeys();
});

function enableArrowKeys()
{
	$('.qty').keypress(function(event)
	{
		
		if(event.keyCode == 38)
		{
			var current 	= parseFloat($(this).val());
			var add 		= parseFloat($(this).attr('rel'));
			var newAmount 	= add+current;
			$(this).val(newAmount);
			event.preventDefault();
		}
		else if((event.keyCode == 40) && (parseFloat($(this).val()) > 0))
		{
			var current 	= parseFloat($(this).val());
			var multi 		= parseFloat($(this).attr('rel'));
			var newAmount 	= current-multi;
			$(this).val(newAmount);
			event.preventDefault();
		}
	});
}


function checkForm(array,$form,options){
	var form = $form[0];
}

function basketCallback(responseText, statusText, xhr, $form){
	// Turned off console.logs so this is empty
	$.get('/ajax/mini-basket/',function(data){
		if(data!=""){
			// Because IE Sucks we have to pullout the z-index here
			$('#miniBasketOuter').replaceWith(data);
			// Enable all the box stuff (refresh all buttons in other words)
			enableBoxes();
			// Run the zIndex Fixer
			zIndexHandler();
		}
	});
	
	
	// Clear the form values
	$($form).find('input[name=qty]').val('0');
	$($form).find('input[name=qtyShow]').val('0');
	$($form).next('.buyingPanelOption').find('p.totalPrice').html('&pound;0.00');
	
	// Add in the callback bit here
	// If we have a response text
	if(responseText != ""){
		$('#container').append(responseText);
		showFeedback();
	}
}

/**
 * jQuery function to show and then hide the basket feedback
 * 
 */
function showFeedback(){
	// 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,function(){
		// When finished, remove it from the DOM
		$(this).detach();
	});
	// $('#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, function(){
			// When finished remove it from the dom
			$(this).detach();
		});
		
		// And return false so that our fallback link isn't followed!
		return false;
	});
}

function enableBuyButtons()
{
	// Do a global unbind
	$('input.jsAddBasket').unbind('click');
	
	// Find jsAddBasket buttons
	$('input.jsAddBasket').click(function(){
		
		// Instead of using a disabled button we'll tag off the disabled class
		if($(this).hasClass('disabled')){
			
			// Pull the multiple in from the rel tag on the button (only way to do this without silly tree traversal
			var multiple = $(this).attr('rel');
			
			// Now alert that we need a quantity in mulitple of
			alert('Please enter a quantity in multiples of '+multiple);
			
			// now stop the form from submittig by returning a false
			return false;
		}
		else
		{
			// Run an unbind
			$('input.jsAddBasket').unbind('click');
			
			// Disable the button
			// $(this).attr('disabled','disabled').attr('src','/images/buttons/addToBasket.gif');
			
			// Add the disabled class to the button
			$(this).addClass('disabled');
			
			// Make some options
			var options = {
					url:"/ajax/add-to-basket/",
					beforeSubmit:checkForm,
					success:basketCallback
			}
			
			// This items parents, siblings, child form
			$(this).parents('.buyingPanelWrapper')		// Find the buying panel wrapper sibling
				   .find('form.buyingPanelForm')		// Now find the child form item with class of buyingPanelForm
				   .unbind('ajaxForm')					// Remove the quantity box ajaxform otherwise nothing happens
				   .ajaxForm(options)					// Add a new ajaxform with the basket submit code
				   .submit();							// now submit it!! (god finally)
		}
								
	});
}





/* Leave this alone please, found on another site to do a is int function THANKYOU!	 */
function isInt (str)
{
	var i = parseInt (str);

	if (isNaN (i))
		return false;

	i = i . toString ();
	if (i != str)
		return false;

	return true;
}
