var category = function(selection) {
    var products = [];
    var infoSelector = '.gallery_info';
    var thumbSelector = '.gallery_thumbs';

    return {
	parse: function(xml) {
	    var categoryCount = 0;
	    $(xml).find('category').each(function() {
		categoryCount++;
		if (categoryCount > 1)
		    return;
		var category = $(this);
		category.find('range').each(function() {
		    var range = $(this);
		    // Add product range heading.
		    $(thumbSelector, selection)
			.append('<h2>' + range.attr('name') + '</h2>');
		    range.find('product').each(function() {
			var product = {
			    name: $(this).attr('name'),
			    description: $(this).children(
				'description').text(),
			    thumb: '',
			    price: $(this).find('price').text(),
			    images: []
			};
			$(this).find('image').each(function() {
			    var image = {
				path: $(this).find('path').text(),
				thumb: $(this).find('thumb').text(),
				detail_thumb: $(this).find(
				    'detail_thumb').text(),
				caption: $(this).find('caption').text(),
				description: $(this).find(
				    'description').text(),
			    };
			    product.images.push(image);
			});
			if (product.images[0]) {
			    product.thumb = product.images[0].thumb;
			}
			products.push(product);
			// Add product thumbnail.
			$(thumbSelector, selection)
			    .append('<img src="' + product.thumb + '" />');
		    });
		});
	    })},
	strEndsWith: function(str, s) {
	    return(str.length >= s.length &&
		   str.substr(str.length - s.length) == s);
	},
	getProduct: function(path) {
	    for (var p in products) {
		for (var t in products[p].images) {
		    if (this.strEndsWith(
			    path, products[p].images[t].thumb) ||
			this.strEndsWith(
			    path, products[p].images[t].detail_thumb)) {
			return(products[p]);
		    }
		}
	    }
	    return(null);
	},
	getFirstProduct: function() {
	    return(products[0]);
	},
	getImage: function(product, path) {
	    for (var i in product.images) {
		if (this.strEndsWith(path,
				     product.images[i].thumb) ||
		    this.strEndsWith(path,
				     product.images[i].detail_thumb)) {
		    return(product.images[i]);
		}
	    }
	    return(null);
	},
	clear: function() {
	    $(thumbSelector, selection).html('');
	    products = [];
	},
	load: function(filename, complete) {
	    var that = this;
	    this.clear();
	    $.ajax({url: filename,
		    dataType: 'xml',
		    error: function(request, textStatus, errorThrown) {
			$(infoSelector, selection).html(
			    '<p class="error">Error loading product' +
				' information. Please try again later.</p>');
		    },
		    success: function(xml) {
			that.parse(xml);
			complete();
		    }})
	}}
};
