
/*********************************************************
*
*          UTILITY FUNCTIONS
*

TABLE OF CONTENTS
    Enable buttons on various pages
    Helper functions
    Moved from signupwiz
        navigation
        shared functions

**********************************************************/



/* *******************************************************
*               Button-enabling functions
******************************************************* */

function setBackButtonEnabled(buttonId, enabled, imgPathOverride, buttonClassName) {
    if (typeof(imgPath) == 'undefined') {
        if (typeof(imgPathOverride) == 'undefined') {              
            var imgPathToUse = '/images/';
        } else {
            var imgPathToUse = imgPathOverride;
        }
    } else {
        var imgPathToUse = imgPath;
    }
    if (typeof(buttonClassName) == 'undefined') {
        var buttonClassName = 'button1'
    }
    var btnBack = document.getElementById(buttonId);
    if (enabled) {
        btnBack.className = buttonClassName;
    } else {
        btnBack.className = buttonClassName + 'G';
    }
    var imgs = btnBack.getElementsByTagName('IMG');
    if (imgs.length > 0) {
        // Assume only one button image
        if (!enabled)
            imgs[0].src = imgPathToUse + 'arrow1b-grey.gif';
        else
            imgs[0].src = imgPathToUse + 'arrow1b.gif';
    }
    btnBack.disabled = !enabled;
}

function setNextButtonEnabled(buttonId, enabled, imgPathOverride, buttonClassName) {
    if (typeof(imgPath) == 'undefined') {
        if (typeof(imgPathOverride) == 'undefined') {              
            var imgPathToUse = '/images/';
        } else {
            var imgPathToUse = imgPathOverride;
        }
    } else {
        var imgPathToUse = imgPath;
    }
    if (typeof(buttonClassName) == 'undefined') {
        var buttonClassName = 'button1'
    }
    var btnNext = document.getElementById(buttonId);
	if (enabled) {
		btnNext.className = buttonClassName;
	} else {
		btnNext.className = buttonClassName + 'G';
	}
	var imgs = btnNext.getElementsByTagName('IMG');
	if (imgs.length > 0) {
		// Assume only one button image
		if (!enabled)
            imgs[0].src = imgPathToUse + 'arrow1-grey.gif';
		else
            imgs[0].src = imgPathToUse + 'arrow1.gif';
	}
	btnNext.disabled = !enabled;
}







/* *******************************************************
*               Helper functions
******************************************************* */
// the price of an item retrieved from the db for display purposes
function setPrice(key, amount) {
	am_setInnerText('price_' + key, formatCurrency(amount,0));
}

// the monthly total (may be calculated) when an item is selected for purchase
function setSubtotal(key,amount) {
	am_setInnerText('tot_' + key, formatCurrency(amount,2));
}








/**
 * showColumns:
 *   Given a <TABLE> specified by tableID, shows selected columns.
 *
 *   showColIndex: -1 shows all columns, otherwise, shows column requested,
 *         indexed from 0 and hides all others.
 *   lastFrozenColumnIndex: last column that should be considered part of the
 *         "frozen pane" at the left.
 *
 *   All indexes are 0 indexed.
 */
function showColumns(tableID, showColIndex, lastFrozenColumnIndex) {
	var myTable = document.getElementById(tableID);
	if (showColIndex > -1) {
		for (col=lastFrozenColumnIndex+1; col < myTable.rows[0].cells.length; col++)
			showHideColumn(myTable,'hide',col);
		showHideColumn(myTable,'show', showColIndex);
	} else {
		for (col=lastFrozenColumnIndex+1; col < myTable.rows[0].cells.length; col++)
			showHideColumn(myTable, 'show', col);
	}
}

/**
 * showHideColumn
 *  table - table DOM object.
 *  action - either 'show' or 'hide'
 *  colIndex - column, 0 indexed, within the table.
 *
 * This uses the "display" attribute of the TD element,
 *  which means that the cells will collapse.  If you need
 *  non-collapsing, use visibility.
 */
function showHideColumn(table, action, colIndex) {
	var dispVal;
	var myRows = table.rows;
	if (action.indexOf('show') > -1) {
		dispVal = '';
	} else if (action.indexOf('hide') > -1) {
		dispVal = 'none';
	}
	for (row=0; row < myRows.length; row++) {
		if (myRows[row].cells[colIndex])
			myRows[row].cells[colIndex].style.display = dispVal;
	}
}



/* *******************************************************
*      Originally defined in signupwiz and moved here
******************************************************* */

/** Navigational functions **/
function goBack() {
	history.go(-1);
}

function gotoPage(page) {
	location.href = location.href.substring(0,location.href.lastIndexOf("/") + 1) + page;
	return false;
}

function gotoPlan(pkgcode) {
	window.location.href = location.href.substring(0,location.href.lastIndexOf("/") + 1) + "signup2.htm?pkgcode=" + pkgcode;
}

/***************************** SHARED FUNCTIONS *******************************/

/* Loads values into the UI based on 'isSelected', 'qty', and 'tierSelected' values in the
     server-written data.
    - Sets checkbox.checked based on whether they should be selected.
    - Sets quantitied items to the initial quantity.
	- Sets tiered items to the initial tier.
  If 'isRevert' is true, then gets info from 'wasBeforeBumpupSelected' instead.

  Assumes starting with everything blank.
 */
function loadServerGeneratedStartingValues(isRevert){

	// setup check box states only for SELECTED (not all) premiums
	var selPremiums = getPremiumsSelectedArr(isRevert);
	for (var i=0; i< selPremiums.length; i++) {
	    // the checked state of this element is set to true if it's in the array.
		premiumCheckboxes[selPremiums[i]].checked = true;
        h_premiumCheckboxes[selPremiums[i]].value = 'on';
	}
		
    // setup tier and qty states for ALL premiums regardless of selected state
    for (var premiumIndex=0; premiumIndex < getNumPremiums(); premiumIndex++) {
        if (isPremiumQuantitied(premiumIndex)) {
            document.getElementById('premium' + premiumIndex + 'qty').value = getSavedPremiumQuantity(premiumIndex, isRevert);
        }
        if (isPremiumTiered(premiumIndex)) {
            document.getElementById('premium' + premiumIndex + 'tier').selectedIndex = getSelectedTierOrdinalPosition(premiumIndex, isRevert);

            // JCR Added tier quantity price initialization
            var tierProductID = document.getElementById('premium' + premiumIndex + 'tier').value;
            if (hasQuantityByPremiumID(tierProductID)) {
                var quantityIndex = getQuantityByPremiumID(tierProductID);
                var quantityMonthly = getQuantityMonthly(tierProductID, quantityIndex);
                var quantitySetup = getQuantitySetup(tierProductID, quantityIndex);
                am_setInnerText('quantity'+ i +'_monthly', formatCurrency(quantityMonthly, 0));
                am_setInnerText('quantity'+ i +'_setup', formatCurrency(quantitySetup, 0));
            }
            // END JCR
		}
	}
	
	for (var i=0; i < getNumQuantity(); i++) {
        var elem = document.getElementById('quantity' + i)
        if (elem) {
    		elem.value = getSavedQuantityQuantity(i, isRevert);
    	}
	}

	// setup check box states only for SELECTED (not all) bundles
	var selBundles = getBundlesSelectedArr(isRevert);
	for (var i=0; i < selBundles.length; i++) {
		bundleCheckboxes[selBundles[i]].checked = true;
        h_bundleCheckboxes[selBundles[i]].value = 'on';
		// No need to check included premiums because of assumptions
		// for what the server provides.
	}

	// Setup discounts (for selected discounts) if they exist on this page.
	try {
		for (var i=0; i < getNumDiscounts(); i++) {
		  if (getDiscountIsMandatoryPromo(i)) { continue; } // JCR
		  if (isRevert) {
		    //alert("revert i " + i + getDiscountAttributeByIndex(i, 'wasSelected'));
            if (getProductAttribute(discounts.allAvailable[i], 'wasBeforeBumpupSelected')) {
			    discountCheckboxes[i].checked = true;
                h_discountCheckboxes[i].value = 'on';
            } else {
				discountCheckboxes[i].checked = false;
                h_discountCheckboxes[i].value = 'off';
            }
		  } else {
            if (getProductAttribute(discounts.allAvailable[i], 'isSelected')) {
			    discountCheckboxes[i].checked = true;
                h_discountCheckboxes[i].value = 'on';
            } else {
			    discountCheckboxes[i].checked = false;
                h_discountCheckboxes[i].value = 'off';
            }
		  }
		}
	} catch (exception) {
		// discountCheckboxes doesn't exist.  Ignore. On a step w/o discounts
	}


}

/* Forces discount checkboxes into a consistent state based on the 'excludes'
 *    verb.  Discounts that are incompatible with the discount defining the
 *    excludes are unchecked.
 */
function forceDiscountCheckboxes() {
	// Enable all discount checkboxes first.
	for (var discountIndex=0; discountIndex < getNumDiscounts(); discountIndex++) {
			if (getDiscountIsMandatoryPromo(discountIndex)) { continue; }  // JCR
			discountCheckboxes[discountIndex].disabled = false;
 	}
	/*
	// If any discount has the "excludes" verb, uncheck and disable the ones it excludes
	for (var discountIndex=0; discountIndex < getNumDiscounts(); discountIndex++) {
		if (discountCheckboxes[discountIndex].checked && hasAnyRelationship(discounts.allAvailable[discountIndex], 'excludes')) {
			var excludedDiscountIDs = objectsOf(discounts.allAvailable[discountIndex], 'excludes');
			//alert('excludes=' + excludedDiscountIDs);
			for (var j=0; j < excludedDiscountIDs.length; j++) {
				var discCheck = discountCheckboxes[discounts.allAvailable.indexOf(excludedDiscountIDs[j])];
				discCheck.checked = false;
                h_discCheck.value = 'off';
				discCheck.disabled = true;
			}
		}
	}
	*/
	// We are going to use excludedBy instead of excludes
	for (var discountIndex=0; discountIndex < getNumDiscounts(); discountIndex++) {
        if (getDiscountIsMandatoryPromo(discountIndex)) { continue; }  // JCR
		var myDiscount = discountCheckboxes[discountIndex];
        var h_myDiscount = h_discountCheckboxes[discountIndex];
		if (hasAnyRelationship(discounts.allAvailable[discountIndex], 'excludedBy')) {
			var excludedByDiscountIDs = objectsOf(discounts.allAvailable[discountIndex], 'excludedBy');
			for (var j=0; j < excludedByDiscountIDs.length; j++) {
				var discIndex = discounts.allAvailable.indexOf(excludedByDiscountIDs[j]);
			    if (discIndex < 0) { continue } // Skip excluding discounts that aren't actually available
				// If any of the excludedBy discounts are selected, uncheck *this* discount and disable it
				var excluderCheck = discountCheckboxes[discIndex];
				if (excluderCheck.checked) {
                    myDiscount.checked = false;
                    h_myDiscount.value = 'off';
					myDiscount.disabled = true;
				}
			}
		}
		// 7/16/04 JG - added to support forceDisabled
		myDiscount.disabled = (isDiscountForceDisabled(discountIndex))
								? true
								: myDiscount.disabled;
	}
	
}

/* Sets whether each Premium or Bundle checkbox is disabled or enabled, and checked or not
   based on what's *possible* for the pkgcode and any selected bundles.
   
   It does not affect any settings that are possible.
*/
function forceCheckboxesBySelectedBundlesForPackage(pkgcode) {
	// If no pkgcode has been selected yet, then don't touch any of the checkboxes.
	// Leave them all enabled.
	if (pkgcode == -1) {
		return;
	}

	// Set bundle checkboxes
	// RULE: bundle checkboxes are enabled if they are available but not bundled into a selected bundle.
	// RULE2: Force bundle checkboxes checked if the bundle is Available and part of the bundledBundles of 
	//           a selected bundle.
	//        Clear if it's not available.
	//        Leave it alone if available but not part of bundledBundles
	var bundleIndex;

    // Make one pass to eliminate any unavailable elements (i.e. user-checked bundles
    // from a different plan choice) that might affect the allowed bundles on this new plan
    for (bundleIndex=0; bundleIndex < getNumBundles(); bundleIndex++) {
        var bundleAvail = isBundleAvailable(pkgcode,bundleIndex);
        if (!bundleAvail) {
            bundleCheckboxes[bundleIndex].checked = false;
            h_bundleCheckboxes[bundleIndex].value = 'off';
        }
    }

    // After the cleaner above, we're safe to build the bundledBundles array
	var bundledBundles = buildBundledBundlesArray(pkgcode);
	for (bundleIndex=0; bundleIndex < getNumBundles(); bundleIndex++) {
		var bundleAvail = isBundleAvailable(pkgcode,bundleIndex);
		var bundleIncluded = isBundleIncluded(pkgcode,bundleIndex);

		bundleCheckboxes[bundleIndex].disabled = !bundleAvail
													|| (bundledBundles[bundleIndex] == 1)
													|| isBundleForceDisabled(bundleIndex);
	
		if (bundleIncluded) {
			bundleCheckboxes[bundleIndex].checked = true;
            h_bundleCheckboxes[bundleIndex].value = 'on';
		} else if (bundleAvail && bundledBundles[bundleIndex]==1) {
			bundleCheckboxes[bundleIndex].checked = false; // special handling for bundles.  Because we assume
			                                               // that server output will explicity set the 
														   // individual premiums within the bundle that are included.		
            h_bundleCheckboxes[bundleIndex].value = 'off';
		} else if (!bundleAvail) {
			bundleCheckboxes[bundleIndex].checked = false;
            h_bundleCheckboxes[bundleIndex].value = 'off';
		}
	}

	var bundledPremiums = buildBundledPremiumsArray(pkgcode);
	// Set premium checkboxes
	// RULE: premium checkboxes are enabled if the premium is Available
	//   (not included, not unavailable) for the package and is not bundled into
	//   a selected bundle
	// RULE2: Force premium checkboxes checked if the premium is Included or (Available
	//      and part of the bundledPremiums of a selected bundle).
	//        Clear it if it's not available.
	//        Leave it alone if it's available but not part of bundledPremiums.
	for (var premiumIndex=0; premiumIndex < getNumPremiums(); premiumIndex++) {
		var premiumAvail = isPremiumAvailable(pkgcode, premiumIndex);
		premiumCheckboxes[premiumIndex].disabled = !premiumAvail
														|| (bundledPremiums[premiumIndex] == 1)
														|| isPremiumForceDisabled(premiumIndex);

		if (isPremiumIncluded(pkgcode, premiumIndex) ||
		    (premiumAvail && (bundledPremiums[premiumIndex] == 1))) {
			premiumCheckboxes[premiumIndex].checked = true;
            h_premiumCheckboxes[premiumIndex].value = 'on';
		} else if (!premiumAvail) {
			premiumCheckboxes[premiumIndex].checked = false;
            h_premiumCheckboxes[premiumIndex].value = 'off';
		}
	}
}

/* Returns array representing all bundles that are bundled in
   given the user's current selections.  Array has numBundles elements.
   1 for every bundle that is bundled in, 0 if not bundled in.
 */
function buildBundledBundlesArray(packageIndex) {
	var bundledBundles = new Array(getNumBundles());
	for (var i=1; i < bundledBundles.length; i++) {
		bundledBundles[i] = 0;
	}
	
	for (var bundleIndex=0; bundleIndex< getNumBundles(); bundleIndex++) {
		if (bundleCheckboxes[bundleIndex].checked) {
			// If a bundle is selected, get the bundles included in it.
			// Iterate through and set the flag.
			var includedBundles = getBasePlanBundleIncludedBundlesArr(packageIndex,bundleIndex);
			for (var j=0; j < includedBundles.length; j++) {
				if (isBundleAvailable(packageIndex, includedBundles[j])) {
					bundledBundles[includedBundles[j]] = 1;
				}
			}
		} 
	}
	for (var bundleIndex=0; bundleIndex < getNumBundles(); bundleIndex++) {
	    // If a bundle is included in the BASE PLAN, set the flag
	    if (isBundleIncluded(packageIndex, bundleIndex)) {
	        bundledBundles[bundleIndex] = 1;
	    }
	}
	
	return bundledBundles;
}

/* Returns array representing all premiums that are bundled in
   given the user's current selections.  Array has numPremium elements.
   1 for every premium that is bundled in, 0 if not bundled in.
 */
function buildBundledPremiumsArray(packageIndex) {
	var bundledPremiums = new Array(getNumPremiums());
	for (var i=0; i < bundledPremiums.length; i++) {
		bundledPremiums[i] = 0;
	}

	for (var bundleIndex=0; bundleIndex< getNumBundles(); bundleIndex++) {
		if (bundleCheckboxes[bundleIndex].checked) {
			// If a bundle is selected, get the premiums included in it.
			// Iterate through and set the flag.
			var includedPremiums = getBasePlanBundleIncludedPremiumsArr(packageIndex,bundleIndex);
			for (var j=0; j < includedPremiums.length; j++) {
				if (isPremiumAvailable(packageIndex, includedPremiums[j]) ||
				    isPremiumIncluded(packageIndex, includedPremiums[j])) {
					bundledPremiums[includedPremiums[j]] = 1;
				}
			}
		}
	}
	return bundledPremiums;
}

/* 
	1. Fills all tier drop down boxes with appropriate options.
	2. Shows the tier drop down boxes where applicable for specified package   
	3. If the premium is not tiered for this particular pkgcode, also hides any
	   Additional Quantity textbox.
	Alex: This function ends up getting called twice upon initial page2 rendering
	      if a specific package is already selected via setupColumns - > chooseOption  
	      (2006-05-23 - fixed bug in returning after finding first tiered premium)
*/
function fillAndShowTierSelectors(pkgcode) {
	for (var premiumIndex=0; premiumIndex < getNumPremiums(); premiumIndex++) {
		//SELECT list.
		var myPremiumTier = document.getElementById('premium' + premiumIndex + 'tier');
		if (isPremiumTiered(premiumIndex)) {
			if (pkgcode == -1 || isBasePlanPremiumTiered(pkgcode, premiumIndex)) {
				// Cases:
				//  1. This premium is tiered for the baseplan.
				//  2. Special case of no package selected.  We need to find out if
				//     the premium is tiered at all for any baseplan.  If so, show the select..

				if (myPremiumTier.options.length == 0) {				
					// Add all of the tiers into the select box and then show it.
					var tierArr = getArrayOfPremiumIDsInTierset(premiumIndex);
					
					for (var i=0; i<tierArr.length; i++) {                        
						am_addSelectOption(myPremiumTier, tierArr[i], getLabelByID(tierArr[i]));
					}
				}
				myPremiumTier.style.display='';					
			}
		} else if (myPremiumTier) {
			myPremiumTier.style.display='none';			
		}		
	}
}


/* 
	Shows/Hides all quantitied premium textbox based on the specified package   
*/
function showQuantitiedPremiumBoxes(pkgcode) {
	for (var premiumIndex=0; premiumIndex < getNumPremiums(); premiumIndex++) {
		if (isPremiumQuantitied(premiumIndex)) {
			var myQuantitiedPremium = document.getElementById('premium' + premiumIndex + 'qty');
			if (pkgcode == -1 || isPremiumAvailable(pkgcode, premiumIndex)) {
				// Cases:
				//  1. This quantitied premium is available for the base plan.
				//  2. Special case of no package selected.
				myQuantitiedPremium.style.display='';
			} else {
				myQuantitiedPremium.style.display='none';			
			}
		}
	}
}

/* Shows/Hides "Additional Quantity"-type textbox and associated text (the div) if it exists.
 */
function showAdditionalQuantityDiv(quantityIndex) {
	//alert('showing:'+quantityIndex);
	am_show('quantity' + quantityIndex + '_div');
}

function hideAdditionalQuantityDiv(quantityIndex) {
	//alert('hiding:'+quantityIndex);
	am_hide('quantity' + quantityIndex + '_div');
}

function hideAllAdditionalQuantityDivs() {
	for (var i = 0; i < getNumQuantity(); i++) {
		am_hide('quantity' + i + '_div');
	}
}

/* Returns the quantity of the premium at the supplied index.
   If it's a quantitied item, returns the actual value in the field
   If non-integer or the box doesn't exist, returns 0

   For non-quantitied items, returns 1.
*/
function getPremiumQty(premiumIndex) {
	var qty;
	if (isPremiumQuantitied(premiumIndex)) {
		var qtytextbox = document.getElementById('premium' + premiumIndex + 'qty');
		if (qtytextbox) {
			qty = parseInt(qtytextbox.value);
			if (qty > -1)
				return qty;
			else
				return 0;
		} else {
			return 0;
		}
	} else {
		return 1;
	}
}

/* Returns the quantity of a 'quantity' type item at the supplied index.
   Returns the actual value of the field.  If non-integer or negative returns 0;
 */
function getQuantityQty(quantityIndex) {
	var qty;
	qty = parseInt(document.getElementById('quantity' + quantityIndex).value);
	if (qty > -1)
		return qty;
	else
		return 0;
}

