j(document).ready(function($) {

	$('.fabricOption').each(function() {

		$(this).click(function() {
			
			var form = $('.fabricOption').parents('.wishListForm')
			
			$('#' + $(form).attr('id') + ' .fabricOption').removeClass('imgSelected');
			$(this).addClass('imgSelected');

			chooseVersionAndOption(form, $(form).attr('id'), $(this).attr('id'));

			return false;

		});
	});

});

var chooseVersionAndOption = function(form, formId, selectedFabric) {

	// GET all of the form fields for the querystring
	var url = '/actions/chooseversionandoption_sensory.asp';
	var qs = $(form).serialize();

	var Model = $('Model').value;
	var FOG_ID = $('FOG_ID').value;

	var request = url + '?Model=' + Model + '&FOG_ID=' + FOG_ID + '&FO_ID=' + selectedFabric;

	var ajax = new Ajax.Request(request, {

		method: 'get',
		requestHeaders: {Accept: 'application/json'},
		onSuccess: function(transport) {

			var response = transport.responseText.evalJSON(true);
			var V_ID = response.result.v_id;

			var iLoopA = 0;
			var strVOG = '';
			var strVOG_JSON = '';
			var iVOGPrice = 0;

			// Calculate the price, including all options and fabric types
			var iPrice = 0;
			iPrice = parseFloat(response.result.v_price) + parseFloat(iVOGPrice);

			if (response.result.fabric != null) iPrice = iPrice + parseFloat(response.result.fabric.fabric_item[0].fog_price);

			$('spaChosenModelPrice').update(iPrice.toFixed(2));

			if (response.result.fabric != null)
				if (strVOG_JSON != '')
					$('ModelInfo').value = '{ "model": "' + response.result.v_id + '", "fabric": "' + response.result.fabric.fabric_item[0].fo_id + '", "vog": { "vog_item": [ ' + strVOG_JSON + ' ] } } ';
				else
					$('ModelInfo').value = '{ "model": "' + response.result.v_id + '", "fabric": "' + response.result.fabric.fabric_item[0].fo_id + '", "vog": { "vog_item": [ { "vo_id": "null" } ] } } ';
			else
				if (strVOG_JSON != '')
					$('ModelInfo').value = '{ "model": "' + response.result.v_id + '", "fabric": "null", "vog": { "vog_item": [ ' + strVOG_JSON + ' ] } } ';
				else
					$('ModelInfo').value = '{ "model": "' + response.result.v_id + '", "fabric": "null", "vog": { "vog_item": [ { "vo_id": "null" } ] } } ';

			$(formId).getElementsByClassName('fabricSelection')[0].update(response.result.fabric.fabric_item[0].fog_name + ': ' + response.result.fabric.fabric_item[0].fo_name);
		},

		onException: function(req,exception) {
			alert('The request had a fatal exception thrown.\n\n' + req + '\n\n' + exception);
			return false;
		},

	  	onFailure: function(transport){ alert('There was an error returning the data : chooseVersionAndOption') }

	});
	
}