function updateProductView () {

	if ($('#productgrid').is(':visible')) {
		productView = '#productgrid';
	} else if ($('#productlist').is(':visible')) {
		productView = '#productlist';
	} else if ($('#productwindow').is(':visible')) {
		productView = '#productwindow';
	}

}
var search_within_results_timeout;

function search_within_results() {
	updateProductView();
	$.get('?', { ajax: true, search_within_results: $('#search_within_results').val() }, function (responseJson) {
		$(productView).html(responseJson[0]);
		$('.paging').html(responseJson[1]);
		$('.showing').html(responseJson[2]);
	}, 'json');
}


$(function() {

	
	$('#price_filter_form').submit(function(e) {
		
		e.preventDefault();
		
		changeLocation = true;
		priceFrom = $('input[type=text][name=filter_price_from]').val();
		priceTo = $('input[type=text][name=filter_price_to]').val();
		
		if (!priceFrom.match(/^[0-9]+$/)) {
			alert('Please enter a digit for your price from');
			changeLocation = false;
		}
		
		if (!priceTo.match(/^[0-9]+$/)) {
			alert('Please enter a digit for your price to');
			changeLocation = false;
		}
		
		if (changeLocation) {
			window.location = './p:' + priceFrom + '-' + priceTo + '/';
		}
		
	});
	
	$('#search_within_results').keyup(function() {
		clearTimeout(search_within_results_timeout);
		search_within_results_timeout = setTimeout("search_within_results()", 250);
		
	});
	

	$('#itemsperpage').change(function() {
		initPopup('#loadingImage');
		updateProductView();

		$.get('?', { ajax: true, items_per_page: $('#itemsperpage').val(), page_number: '1' }, function (responseJson) {
			$(productView).html(responseJson[0]);
			// $('#productgrid').html(responseJson[0]);
			$('.paging').html(responseJson[1]);
			$('.showing').html(responseJson[2]);
			disablePopup('#loadingImage');
		}, 'json');
	});
	
	$('#sortby').change(function() {
		initPopup('#loadingImage');

		updateProductView();

		$.get('?', { ajax: true, order_by: $('#sortby').val() }, function (responseJson) {
			// $('#productgrid').html(responseJson[0]);
			$(productView).html(responseJson[0]);
			disablePopup('#loadingImage');
		}, 'json');
	});
	
	$('.compare').livequery('click', function(e) {
		e.preventDefault();
		
		var containerLi = $($(this).parents('li')[0]);
		var itemId = containerLi.attr('id').replace(/[^\d]*/,'');
		
		var toggleCompareSelected = function(count) {
			if(count > 1) {
				$('a.compareselected img').attr('src', '/templates/' + templates_dir + '/_images/buttons/compareselected_on.gif');
			} else {
				$('a.compareselected img').attr('src', '/templates/' + templates_dir + '/_images/buttons/compareselected.gif');
			}
		};
		
		if ($(this).is('.selected')) {
			$('li[id$=item'+itemId+'] a.compare.selected').fadeOut(500);
			$('li[id$=item'+itemId+']').animate({ backgroundColor: '#ffffff' }, 500);
			$.get('/products/compare/', { ajax: true, id: itemId, toggle: false }, function(responseJson) {
				toggleCompareSelected(responseJson);
			}, 'json');
		} else {
			$('li[id$=item'+itemId+'] a.compare.selected').fadeIn(500);
			$('li[id$=item'+itemId+']').animate({ backgroundColor: '#ffffff' }, 500);
			$.get('/products/compare/', { ajax: true, id: itemId, toggle: true }, function(responseJson) {
				toggleCompareSelected(responseJson);
			}, 'json');
		}
	});
	
	if ($('#productwindow').is(':visible')) {
		$('#productwindow_data').width($('#productwindow_data > li').length * 351);
		$('#pane1').jScrollHorizontalPane({showArrows:true,resize:false});
	};
	
	$('.layout a').click(function(e) {
		e.preventDefault();
		$('.layout a').removeClass('selected');
		$(this).addClass('selected');
		$('.paging-info').show();

		if ($(this).hasClass('grid')) {
			$.get('?', { ajax: true, view_type: 'grid' }, function (responseJson) {
				$('#productgrid, #productlist, #productwindow').hide();
				$('#productgrid').html(responseJson[0]);
				$('#productgrid').fadeIn();
				$('.swatches li:first-child a').click();
				setTimeout("preSelectAttributes();", 100);
			}, 'json');

		} else if ($(this).hasClass('list')) {
			$.get('?', { ajax: true, view_type: 'list' }, function (responseJson) {
				$('#productgrid, #productlist, #productwindow').hide();
				$('#productlist').html(responseJson[0]);
				$('#productlist').fadeIn();
				$('.swatches li:first-child a').click();
				setTimeout("preSelectAttributes();", 100);
			}, 'json');

		} else if ($(this).hasClass('window')) {
			$.get('?', { ajax: true, view_type: 'window' }, function (responseJson) {
				$('#productgrid, #productlist, #productwindow').hide();
				$('#productwindow_data').html(responseJson[0]);
				$('#productwindow').fadeIn();
				$('.paging-info').hide();
				$('#productwindow_data').width($('#productwindow_data').find('li').length * 240);
				
				$('#productwindow_data').width((
				    $('#productwindow_data > li').length * (
				        parseInt($('#productwindow_data li:first').css('width')) 
				        + parseInt($('#productwindow_data li:first').css('margin-right'))
				        + 2
				    )
				));
				
				$('#pane1').jScrollHorizontalPane({showArrows:true,resize:false});
				
				$('.swatches li:first-child a').click();
				
				setTimeout("preSelectAttributes();", 100);
			}, 'json');
		}

	});
	
	$('.swatches a').livequery('click', function(e) {
		e.preventDefault();
		$(this).parent().parent().closest('li').find('img.thumb').attr('src', $(this).attr('href'));
		$(this).parent().parent().find('img').removeClass('selected');
		$(this).find('img').addClass('selected');
	});
	
	
	
	initAttributes = function() {
		$('#attributes input[type=radio]').click(function() {
			$.post('?', { ajax: true, quick_view: curr_quick_look, updateattributes: true, name: $(this).attr('name'), value: $(this).val() }, function(responseJson) {
				$('#attributes').replaceWith(responseJson.attributes);
				$('#quicklookimages').replaceWith(responseJson.images);
				$('.tooltip').tooltip({ showURL: false });
				$("a[rel^='prettyPhoto']").prettyPhoto({theme: 'dark_rounded'});
				initAttributes();
			}, 'json');
		});
		$('.tooltip').tooltip({ showURL: false });
		$("a[rel^='prettyPhoto']").prettyPhoto({theme: 'dark_rounded'});
		
		$('#attributes .image').each(function() {
			$(this).append('<span class="image_text">' + $(this).find('input[type=radio]:checked').parent().text() + '</span>');
			var attribute_id = $(this).attr('id').replace(/[^\d]/g, '');
			$(this).find('label').each(function() {
				var radioButtonLabel = $(this);
				$('<a href="#" class="tooltip" rel="nofollow" title="' + $(this).text() + '"><img src="/images/ac_product_attributes_data/attribute_image/' + $(this).find('input[type=radio]').val() + '" alt="' + $(this).text() + '" /></a>').insertAfter(radioButtonLabel).click(function(e) {
					e.preventDefault();
					radioButtonLabel.find('input[type=radio]').attr('checked', 'checked').click();
				}).find('img').addClass(radioButtonLabel.find('input[type=radio]').is(':checked') ? 'selected' : '');
				radioButtonLabel.hide();
			});
		});
	}

	initAttributes();
	
	$('#quicklookimages a').livequery('click', function(e) {
		e.preventDefault();
		$('#quicklookimages img:first').attr('src', $(this).attr('href'));
	});
	
});

$(function() {
	$('a.viewmore').click(function(e) {
		e.preventDefault();
		$(this).closest('div').find('li.hiddenfilter').slideDown();
		$(this).closest('div').find('.viewmore').hide();
		$(this).closest('div').find('.viewless').show();
		});
	$('a.viewless').click(function(e) {
		e.preventDefault();
		$(this).closest('div').find('li.hiddenfilter').slideUp();
		$(this).closest('div').find('.viewmore').show();
		$(this).closest('div').find('.viewless').hide();
	});
	
	// CHANGE ATTRIBUE COLOUR
	$('ul.swatches li a').click(function(e) {
		e.preventDefault();
		var colour = $(this).attr('href').replace(/^#/,'');
		$(this).parent().parent().parent().parent().find('.image div').hide();
		$(this).parent().parent().parent().parent().find('.image .' + colour).show();
	});
	$('div.image div').not(':first-child').hide();
	
	setTimeout("preSelectAttributes()", 100);
	
});

function preSelectAttributes() {
	// preselect the first swatch colour.  this is set up to not change a setting that is already set.
	// if we change the swatch to store state in a cookie later on, then this will still work.
	// for some reason it needs to be in a setTimeout... annoying!
	$('.swatches li:first-child a').each(function() { 
		if ($(this).parent().parent().find('a img.selected').length == 0) { 
			$(this).click(); 
		}
	});
}

