/*
 * This code ensures that at least one of the delivery options is selected.
 * 
 * This looks at the checkboxes on a delivery form and searches for
 * input fields with an attribute that starts with one of
 *   POSTHANDLE
 *   DELS
 *   DELB
 *   PICK
 * 
 * These represent the delivery options and exactly one must be selected.
 */

// Set of delivery choice prefixes
var selectChoices = ["POSTHANDLE","DELS","DELB","PICK"];

// Set the option that must be initially be selected.
var selectInitial = selectChoices[0];

// helper function
function left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

// helper function
function right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

// Finds an input field that has the itemNo prefix.
// The itemNo variable is something like "DELS"
function findByItemNo(itemNo) {
	var o;
	// Find all input fields
	$("input").each(function(){
		// Get the full actual item number, such as "DELSMORI12"
		var fullItemNo = $(this).attr("itemno");
		// Check if the the prefix of the fullItemNo matches the itemNo variable.
		if (left(fullItemNo,itemNo.length) == itemNo) {
			// Found! So exit loop.
			o = this;
			return false;
		}
	});
	return o;
}

// Set the click event handler to each of the delivery option fields.
function initSelectChoices() {
	$(selectChoices).each(function(){
		var o = findByItemNo(this);
		if (o) {
			$(o).click(handleSelectClick);
		}
	});
}

// If a delivery option is clicked, then ensure this is the only
// option selected.
function handleSelectClick() {
	deselectAll();
	this.checked = true;
}

// Deselects all of the delivery options.
function deselectAll() {
	$(selectChoices).each(function(){
		var o = findByItemNo(this);
		if (o) {
			o.checked = false;
		}
	});
}

// Returns the currently selected delivery option.
function getCurrentChoice() {
	var current;
	$(selectChoices).each(function(){
		var o = findByItemNo(this);
		if (o && o.checked) {
			current = o;
			return false;
		}
	});
	return current;
}

// Set the click event handlers
// Select the initial delivery checkbox
$(document).ready(function(){
	initSelectChoices();
	// In IE6, this $(document).ready() function is called each time the page
	// is visited (such as when clicking "back").
	// So only select the initial item if no other item is selected.
	if (!getCurrentChoice()) {
		var item = findByItemNo(selectInitial);
		if (item) {
			item.checked = true;
		}	
	}
});

