$(document).ready( function() { 
	
	/* * Toggle status of initial fields * */
	toggleFields();

	/* * Listener on options if multiple sizes * */
	if ( $("select[name='sizeId']").attr("name") != undefined )
	{
		$("select[name='sizeId']").change( function() {
			loadOptions( $("input[name='productId']").val(), this.value );
		});
	} 
	else
	{
		//Load options
		loadOptions( $("input[name='productId']").val(), $('#sizeId').val() );
	}

	/* * Listener on quantity if multiple options * */
	if ( $("select[name='optionId']").attr("name") != undefined )
	{
		
		$("select[name='optionId']").change( function() {
			loadQuantity( $('#sizeId').val(), this.value );
		});
	}	
});


function toggleFields()
{
	//Toggle select boxes depending on stock
	$("select[name='optionId']").removeAttr("disabled");
	$("select[name='quantity']").removeAttr("disabled");
	$("#frmSubmit").attr("src", basketButtonDisabled.src );
	$("#frmSubmit").removeAttr("disabled");

	$("#optionId").attr("disabled","disabled");
	$("#quantity").attr("disabled","disabled");
	$("#frmSubmit").attr("disabled","disabled");
	
	if ( $("#sizeId").val() != "" )
	{
		$("#optionId").removeAttr("disabled");
	}

	if ( $("#optionId").val() != "" )
	{
		$("#quantity").removeAttr("disabled");
	}

	if ( $("#quantity").val() > 0 )
	{
		$("#frmSubmit").attr("src", basketButton.src );
		$("#frmSubmit").removeAttr("disabled");
	}
}


function loadOptions( productId, sizeId ) {
	
	$("select[name='optionId']").html("<option value=''>Loading...</option>");
	$("select[name='quantity']").html("<option value='0'>...</option>");

	$.getJSON(
		'~gateway/productDetail.cfc',
		{ method: 'getOptions', returnformat: 'json', productId: productId, sizeId: sizeId },
		function(data)
		{
			$("select[name='optionId']").html(data);
			loadQuantity( $('#sizeId').val(), $('#optionId').val() );
			toggleFields();
		}
	);
}


function loadQuantity( sizeId, optionId ) {
	
	$("select[name='quantity']").html("<option value='0'>...</option>");

	$.getJSON(
		'~gateway/productDetail.cfc',
		{ method: 'getMaxQuantity', returnformat: 'json', sizeId: sizeId, optionId: optionId },
		function(data)
		{
			$("select[name='quantity']").html(data);
			toggleFields();
		}
	);
}


function validate() {
	if ( $('#sizeId').val() == "" ) {
		alert( 'Please select a Size');
		return false;

	} else if ( $('#optionId').val() == "" ) {
		alert( 'Please select an Option');
		return false;

	} else if ( $('#quantity').val() == 0 ) {
		alert( 'Please select an Quantity');
		return false;
	}
	return true;
}