/**
 * Check Availability v2.3
 *
 * This version 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 onmouseup (onchange wasn't workign in
		IEx) event and then trigger it to initialse the form element by triggering
		an onchange event.
	*/
	$(".uc_inventory_ajax_form .ProductOption").change(function() {
		onAttributesChange(this);
	}).trigger("change");
});

function onAttributesChange(input) {

	var form = $(input).parents("form").get(0);

	// 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 = 0; i < item.length; i++) {	// if its radio buttons then it could be a list of items
				if(item[i].checked != undefined && 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");
}

/**
 * Debugging function for looking at object propertys
 */
function showme(obj, obj_name) {
   var result = ""
   var null_list = "";
   obj_name = (obj_name != '')? obj_name: 'obj';
   for (var i in obj) {
		if(obj[i] != null && obj[i] != '')
			result += obj_name + "." + i + " = " + obj[i] + "\n";
		else
			null_list += i + ", ";
   }
   return result + "\n NULL propertys: \n" + null_list;
}

