// Globals that this script uses. Declare once here and then add to them for
// each node instance that needs them inline

var node_id_list = new Array();
var attrs_list = new Object();

// Hook into the form onChange event...

$(document).ready(function() {

		// Add the onAttributesChange() to the onChange event and then trigger
		// it to initialse the form element by triggering an onchange event.
	for(var i = 0; i < node_id_list; i++)
	{
		$("#uc-product-add-to-cart-form-"+node_id_list[i]+" .form-select").change(function() {
			onAttributesChange(this);
		}).trigger("change");
	}
});

// When the attributes are changed ask the server via Ajax if its available to
// add to cart.

function onAttributesChange(selector)
{
	// Get the node ID

	var form_id = "#" + $(selector).parents('form').attr('id');

	var myRex = /[0-9]+/.exec(form_id);	// Not very good, but can't see another way to get the node ID from an 'add to cart' form :(

	var node_id = myRex[0];

	// Get figure out which attributes are selected for the given node ID

	var params = new Array();

	params.push("nid:" + node_id);

	for (var i = 0; i < attrs_list[node_id].length; i++)
	{
		var aid = attrs_list[node_id][i];
		params.push( aid + ":" + $(form_id + " #edit-attributes-" + aid).val() );
	}

	// Ask Drupal if current selection is availible with AJAX post...

	var submit_id = form_id + " .form-submit";

	$(submit_id).val(lang_checking).attr({disabled: "disabled"});

	$.post(
		base_path + '?q=uc_inventory_api/ajax/can_add',
		eval("({"+params.join(",")+"})"),
		function(data){ toggle_submit(data, submit_id); }
	);
}

// Change the state of the Submit button for this product.

function toggle_submit(data, submit_button_id)
{
	// data should be a string, ether "true" or "false"
	if(!eval(data))
		$(submit_button_id).val(lang_not_available).attr({disabled: "disabled"});
	else
		$(submit_button_id).val(lang_add_to_cart).removeAttr("disabled");
}
