// NON-FUN
var off = 'OFF_'; // TODO: use it

// Return the minimal enclosing row, if el is in a table.
// In all other cases, return a null.
function get_row (el)
{
	if ('object' != typeof el || !el) return null;
	
	var elUp, elTr, count;
	var notFound;
	var txt;
	
	// Are we in a table? Find the closest row, too.
	elTr = null;
	notFound = true;
	for (elUp = el, count = 0; 
		notFound && elUp && elUp.nodeType != 9 && count < 10; // count cap is arbitrary
		elUp = elUp.parentNode, count++
	) {
//		alert ('node name ['+ elUp.nodeName +']\ntag name ['+ elUp.tagName +']');
//		alert (elUp.nodeName.toLowerCase() );
		switch (elUp.nodeName.toLowerCase() ) {
		case 'table':
			notFound = false;
			continue;
		case 'tr':
			elTr = elUp;
			continue;
		default:
			break;
		}
	}
	if (notFound || !elTr) return null;
	
	return elTr;
}

// Also returns if successfully deteled.
function delete_row (el)
{
	if ('object' != typeof el || !el) return false;
	
	// TODO: which one?
	// return turnoff_input_row (el);

	var elTr = get_row (el);	
	if ('object' != typeof elTr || !elTr) return false;

	if ('string' == typeof el.name && el.name.substr (0,4) != 'OFF_') {
		el.name = 'OFF_'+ el.name;
	}	
//	alert (elTr);
	
	// elTr.style.display = 'none'; // Would work, in fact.
	elTr.parentNode.removeChild (elTr);
	return true;
}

// First, make sure the input row is not visible on the page.
// Second, make sure there is no duplication of input values.
// Also returns if successfully turned off.
function turnoff_input_row (param)
{
// if ('cc' == param) alert ('off...['+ param +']');
	var el = getElement (param);
// if ('cc' == param) alert (param +'-->'+ el);	
	if (!el) return false;
	
	var elTr, elH;
	
	var elTr = get_row (el);
	if ('object' != typeof elTr || !elTr) return false;
	
	// Hide the row
	elTr.style.display = 'none';
	
// if ('cc' == param) alert ('el id=['+ el.id +'] name=['+ el.name +']');	

	// This is for cases where we force rows off
	// (w/o specifying input fields).	
	if ('undefined' == typeof el.name || !el.name) return false;
	
	// Avoid input field name duplication:
	// the hidden field is on...
	if ('OFF_' == el.name.substr (0, 4)) {
		el.name = el.name.slice (4);
// alert ('Corrected: el id=['+ el.id +'] name=['+ el.name +']');	
	}

	elH = document.getElementById ('hidden_'+ el.name);
// if ('cc' == param) alert ('elH='+ elH);
	if ('object' != typeof elH || !elH) {
		alert ('***No element (hidden) with id ['+ 'hidden_'+ el.name +']');
		
		// /*
		var inputs = document.getElementsByTagName ('input');
		var ii;
		var txt;
		for (ii = 0; ii < inputs.length; ++ii) {
			 txt += (inputs [ii].id +'<br />');
		}
		document.write (txt);
		// */
		
		return false;
	}
// document.write (whatIsInside (elH));	
// alert ('['+ elH.name.substr (0, 4) + ']\n['+ elH.name.slice (4) +']');
	if ('OFF_' == elH.name.substr (0, 4)) {
		elH.name = elH.name.slice (4);
	}
	// ...and the local field is OFF.
	el.name = 'OFF_'+ el.name;
	
	return true;
}

// First, make sure the input row is visible on the page.
// Second, make sure there is no duplication of input values.
// Also returns if successfully turned on.
function turnon_input_row (param)
{
	var el = getElement (param);
	if (!el) return false;
	
	var elTr = get_row (el);
	if ('object' != typeof elTr || !elTr) return false;

	// Show the row
	elTr.style.display = '';
	
	// This is for cases where we force rows on
	// (w/o specifying input fields).	
	if ('undefined' == typeof el.name || !el.name) return false;
	
	// Avoid input field name duplication:
	// the local field is on...
	if ('OFF_' == el.name.substr (0, 4)) {
		el.name = el.name.slice (4);
	}
	// ...and the hidden field is OFF.
	elH = document.getElementById ('hidden_'+ el.name);
	elH.name = 'OFF_'+ elH.name;
	
	return true;
}

function mark_off (ee)
{
	ee.name = 'OFF_' + ee.name;
/*
	if ('undefined' == typeof ee || !ee) return;
	if ('hidden' == ee.type) {
	} else {
	}
*/
}

// Remove hidden input fields which have non-hidden copies on the current page.
// Use objects window.inputLocal and window.inputHidden as hashes with
// a key as input field name (not id!) and
// the value as the element reference (TODO: or a list of references?).
function squashHidden () {
	if ('undefined' == typeof inputLocal || null == inputLocal) {
		inputLocal = new Object ();
	}
	if ('undefined' == typeof inputHidden || null == inputHidden) {
		inputHidden = new Object ();
	}

	var ar, ee, ii, hh, yy;
	
	// Consider all input elements.
	ar = unite (
		document.getElementsByTagName ('textarea'), 
		document.getElementsByTagName ('select'), 
		document.getElementsByTagName ('input') 
	);
	for (ii = 0; ii < ar.length; ++ii) {
		ee = ar [ii];
		switch (ee.type) {
		case 'checkbox': case 'password':
		case 'textarea': case 'text': case 'radio': 
		case 'select': case 'select-one':
			// This is a local input field
			inputLocal [ee.name] = ee;
			// Remove a corresponsing hidden field
			hh = inputHidden [ee.name];
			if ('undefined' == typeof hh || !hh) continue;
			mark_off (hh);
			break;
		case 'hidden':
			inputHidden [ee.name] = ee;
			// Remove itself if a duplicate
			yy = inputLocal [ee.name];
			if ('undefined' == yy || !yy) continue;
			mark_off (ee);
			break;
		default:
			break;
		}
	}
}

function fillCheckboxes () 
{
	// All checkboxes are type of input fields.
	var boxes = document.getElementsByTagName ('input');
	var ii, box, hh;
	
	for (ii = 0; ii < boxes.length; ++ii) {
		box = boxes [ii];
		if (box.type != 'checkbox') continue;

// alert ('Found a check box name=['+ box.name +'] value=['+ box.value +']');

		// Make the box's value remember its state.
		// NOTE: if the checkbox controls page behavior,
		// this function will likely be overridden.
		box.onclick = function () {
			this.value = this.checked.toString();
// alert (box.checked +'\nvalue=['+ box.value +'] of ['+ typeof box.value +']');
		}
		
		// Initialize if necessary.
		if ('true' == box.value) {
			box.checked = true;
		} else if ('false' == box.value) {
			box.checked = false;
		}
	}
}

function stretchForm ()
{
	var elF = document.getElementById ('signupFooter');
	if ('undefined' == typeof (elF) || !elF) return;
	
	var elB = document.getElementById ('signupFooter');
	if ('undefined' == typeof (elB) || !elB) return;
	
	// TODO: make elB at least as wide as elF.
	// Later. Needed?
}

// Select menus may need special processing.
// If the number N is positive, crop the left N characters.
var select_menus = {
	'homeState':2, 'billingState':2, 'companyState':2, 'payState':2
	,'payExpiresMonth':-1
};

function processSelectMenus ()
{
	var el, ii, mm;
	
	for (mm in select_menus) {
		el = document.getElementById (mm);
		if ('undefined' == typeof el || !el) continue;
		if (el.id != mm) continue; // MSIE confuses names and ids?

//		alert (el.selectedIndex);
		if (el.selectedIndex < 0) {
			el.selectedIndex = 0;
		}

		var elHi = document.getElementById ('hidden_'+ mm );
		var hiva = elHi.value;
		if ('' != hiva) {
			if (select_menus [mm] > 0) {
				el.value = hiva.substring (0, 2); // ugly
			} else {
				el.value = hiva;
			}
//			elHi.value = hiva.substring (0, 2); // ugly
//			elHi.value = hiva;
		}
	}
}

// --[section]--
/* These are intended to fill in address fields from previously entered ones.
 * Add a checkbox to the body and set page variable the_prefix.
 * Call set_address_checkbox() when the body loads.
 * For examples, see PaymentOptions.asp and BillingContact.asp.
*/
// Fill in address values from the already entered ones.
var fill_address = function () {
	var prefix_from = 'hidden_company';
	
	var field_to, field_from, ff, ii;
	var fields_to_fill = [
		'Address', 'City', 'State', 'Zipcode'
	];
	
	if ('undefined' == typeof the_prefix || !the_prefix) return; // Internal error.
	for (ii in fields_to_fill) {
		ff = fields_to_fill [ii];
		field_to   = document.getElementById ('' + the_prefix  + ff );
		field_from = document.getElementById (     prefix_from + ff );
		if (!field_to || !field_from) {
			continue; // Internal error.
		}
		field_to.value = field_from.value;
	}

	var checkboxField = document.getElementById ('sameAddress');
	if (!checkboxField) {
		return; // Internal error.
	}
	checkboxField.style.display = 'none';
};

// Prepare the checkbox in case the applicant wants the fields filled in 
// from the previously entered values.
function set_address_checkbox (prefix)
{
	/* Fields:
	 * address, city, state, zipcode.
	*/
	var address, city, state, zipcode;
	var address_tofill, city_tofill, state_tofill, zipcode_tofill;
	
	/* Logic:
	 * If we have not been to this page before (mandatory fields are empty), add the checkbox to the page.
	*/
	address_tofill = document.getElementById (prefix +'Address');
	city_tofill = document.getElementById (prefix +'City');
	state_tofill = document.getElementById (prefix +'State');
	zipcode_tofill = document.getElementById (prefix +'Zipcode');
	if (!address_tofill || !city_tofill || !state_tofill || !zipcode_tofill) {
		return; // No such element on the page. Internal error.
	}

	address_tofill = address_tofill.value;
	city_tofill    = city_tofill   .value;
	state_tofill   = state_tofill  .value;
	zipcode_tofill = zipcode_tofill.value;
	if ('' != address_tofill || '' != city_tofill 
		/* || '' != state_tofill */
		|| '' != zipcode_tofill
	) {
		return; // Some of the (mandatory) address fields are non-empty: no need to fill in the address.
	}
	
	var checkboxField = document.getElementById ('sameAddress');
	if (!checkboxField) {
		return; // Internal error.
	}
	var checkbox = document.getElementById ('checkSameAddress');
	if (!checkbox) return; // Internal error.

	checkbox.checked = false;
	checkboxField.style.display = '';
}
// --[end]--

// Run this whenever the window loads.
// IMPORTANT:
// - This function needs to be called from the body.onload
//   if the latter is defined
//   (because in this case it overrides window.onload).
window_onload = function () {
	// Remove duplicate (hidden) input fields.
	squashHidden (); 
	
	// Check off checked checkboxes
	// and make them remember their value when (un)checked.
	fillCheckboxes ();
	
	// Initialize all select menus.
	processSelectMenus ();
	
	// Try and make the form look wide enough.
	// stretchForm ();
	
}

// This sets it to run when the window has loaded 
// wherever the page has no body.onload defined.
window.onload = window_onload;
