// returns array of elements whose 'prop' property is 'value'
function filterByProperty(arr, prop, value) {
    return $.grep(arr, function (item) { return item[prop] == value });
}

// populates select list from array of items given as objects: { name: 'text', value: 'value' }
function populateSelect(el, items) {
    el.options.length = 0;
    if (items.length > 0)
    	el.options[0] = new Option('select', '');

    $.each(items, function () {
    	el.options[el.options.length] = new Option(this.name, this.value);
    });
}

// initialization
$(document).ready(function () {
    // populating 1st select list
    populateSelect($('#size').get(0), $.map(productSizes, function(size) { return { name: size.name, value: size.name} }));

    // populating 2nd select list
    $('#size').bind('change', function() {
    	var sizeName = this.value,
    		productSize = filterByProperty(productSizes, 'name', sizeName),
    		colours = [];

    	if (productSize.length > 0)
    		colours = $.map(productSize[0].colours, function(colour) { return { name: colour.name, value: sizeName + '.' + colour.name} });

    	populateSelect($('#colour').get(0), colours);
    	$('#colour').trigger('change');
    });

    // populating 3rd select list
    $('#colour').bind('change', function () {
    	var nameAndcolour = this.value.split('.'),
    		widths = [];

    	if (2 == nameAndcolour.length) {
    		var sizeName = nameAndcolour[0], 
    			productcolour = nameAndcolour[1],
    			productSize = filterByProperty(productSizes, 'name', sizeName);

    		if (productSize.length > 0) {
    			var colour = filterByProperty(productSize[0].colours, 'name', productcolour)

    			if (colour.length > 0)
    				widths = $.map(colour[0].widths, function(feature) { return { name: feature, value: sizeName + '.' + productcolour + '.' + feature} })
    		}
    	}

    	populateSelect($('#feature').get(0), widths);
    })

    // do something on 3rd select list change
    $('#wfeature').bind('change', function () { 
    })
});

