function updateProductView () {

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

}


$(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 + '/';
		}
		
	});
	

var changeSearchTimeout;
var changeSearchLastValue;

	$('#search_within_results').keyup(function() {
		clearTimeout(changeSearchTimeout);
		changeSearchTimeout = setTimeout(changeSearchGo, 500);
	});

function changeSearchGo() {
	if ($('#search_within_results').val() != changeSearchLastValue) {
	
		updateProductView ();

		$('.searchwithin .busy').show();
		$.get('?', { ajax: true, search_within_results: $('#search_within_results').val() }, function (responseJson) {
			$(productView).html(responseJson[0]);
			$('.paging').html(responseJson[1]);
			$('.showing').html(responseJson[2]);
			$('.searchwithin .busy').hide();
		}, "json");
		changeSearchLastValue = $('#search_within_results').val();
	}
}


	
	$('#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) {
				if (responseJson == 'toomanycompares') {
					alert('You may compare up to 5 products.');
					$('li[id$=item'+itemId+'] a.compare.selected').fadeOut(500);
				} else {
					toggleCompareSelected(responseJson);
				}
			}, 'json');
		}
	});
	
	if ($('#productwindow').is(':visible')) {
		$('#productwindow_data').width($('#productwindow_data > li').length * 351);
		$('#pane1').jScrollHorizontalPane({showArrows:true,resize:false});
	};

	$('img.rolloverLayout:not(.active)').livequery(function() {
	$(this).hover(
		function () {
			if ($(this).attr('src').indexOf('_on.gif') == -1)
			{
				$(this).attr('src', $(this).attr('src').replace(/\.gif/, '_on.gif'));
			}
		},
		function() {
			if ($(this).attr('src').indexOf('_on.gif') != -1)
			{
				$(this).attr('src', $(this).attr('src').replace(/_on\.gif/, '.gif'));
			}
		}
		);
	});
	
	$('.layout a').livequery('click', function(e) {
		e.preventDefault();

        var type = '';
        var onOff = '';
        if ($(this).attr('id').indexOf('On') != -1)
        {
            onOff = 'off';
        }
        else
        {
            onOff = 'on';
        }

        if ($(this).attr('id').indexOf('grid') != -1)
        {
            type = 'grid';
        }
        else
        {
            type = 'list';
        }

		$('.paging-info').show();
        $(this).hide();

		if (type == 'grid')
        {
            if (onOff == 'on')
            {
                $('#gridOn').show();
                $('#listOn').hide();
                $('#listOff').show();
			    $.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
            {
                $('#gridOff').show();
                $('#listOff').hide();
                $('#listOn').show();
            }
		}
        else if (type == 'list')
        {
            if (onOff == 'on')
            {
                $('#listOn').show();
                $('#gridOn').hide();
                $('#gridOff').show();
			    $.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
            {
                $('#listOff').show();
                $('#gridOff').hide();
                $('#gridOn').show();
            }
		}
	});
	
	$('.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 });
		
		$('#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();

    /**
     * special offer banner rotation
     */
    $('ul.bannerRotator').find('a').mouseover(function()
    {
        $('div.landing_left').find('img').attr('src', $(this).attr('rel'));
        return false;
    });
});

$(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(); 
		}
	});
}

