/**
 * Check Availability v2
 *
 * This verion tries to make it input control independant so as to work with the
 * uc_atribute_image module
 */

$(document).ready(function() {
	// Add the onAttributesChange() to the onChange event and then trigger
	// it to initialse the form element by triggering an onchange event.
	$(".uc_inventory_ajax_form form").change(function() {
		onAttributesChange(this);
	}).trigger("change");
});

function onAttributesChange(form) {

	// Build the array of paramaters to pass via Ajax.

	var params = new Array();

	// Pass node ID

	params.push("nid:" + form["uc_inventory_nid"].value);

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

	attrs_list = form["uc_inventory_aids"].value.split(',');

	for (var i in attrs_list) {

		var aid = attrs_list[i];

		var item = form["attributes["+aid+"]"];	// get around the nasty square brackets in the name

		if(item.value != undefined)
			params.push( aid + ":" + item.value );
		else
			for(var i in item)	// if its radio buttons then it could be a list of items
				if(item[i].checked)
					params.push( aid + ":" + item[i].value );
	}

	// 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");
}
