
/**
 * Update shipping location options
 */
function selectShippingLocation() {
	var addressEl = $("#shipping-address");
	var thisValue = addressEl.find("input[name='SHIPPINGS2B']:checked").val();

	if (thisValue == undefined) {
		addressEl.find("input[name='SHIPPINGS2B']:last").attr('checked', true);
		thisValue = addressEl.find("input[name='SHIPPINGS2B']:checked").val();
	}

	var checkedEl = addressEl.find("input[name='SHIPPINGS2B']:checked");
	checkedEl.parent().addClass('selected');
	checkedEl.parent().siblings().removeClass('selected');

	switch (thisValue) {
		case 'school':
			addressEl.find("ul.address-rows.shipping, ul.mbs-rows").fadeOut('fast', function(){
				addressEl.find("ul.school-rows").fadeIn('fast');
			});
			break;
		case 'store':
			addressEl.find("ul.address-rows.shipping, ul.school-rows").fadeOut('fast', function(){
				addressEl.find("ul.mbs-rows").fadeIn('fast');
			});
			break;
		case 'sameasbill':
			addressEl.find("ul.school-rows, ul.mbs-rows, ul.address-rows.shipping").fadeOut('fast');
			break;
		case 'unlikebill':
		default:
			if (addressEl.find("ul.school-rows, ul.mbs-rows").length) {
				addressEl.find("ul.school-rows, ul.mbs-rows").fadeOut('fast', function(){
					addressEl.find("ul.address-rows.shipping").fadeIn('fast');
				});
			}
			else
				addressEl.find("ul.address-rows.shipping").fadeIn('fast');
			break;
	}
}

/**
 * Was shipping_page_set_fillopt()
 */
function shippingSetFillOpt(){

	// get current fill option value
	if ($("#frmShippingMethod .fill-method input[name='FILLOPTION']").length) {
		var fillOption = $("#frmShippingMethod .fill-method input[name='FILLOPTION']:checked").val();
		if (fillOption == undefined)
			fillOption = 'A';
	}
	else
		var fillOption = 'O';

	// PDR: changed so that ALL options are written into tables id'd "options[fillOption]"
	// Algorithm: show the given table (remove "hide" from class), hide any other
	// table (add "hide" to class), and check radio buttons as associated
	// We ONLY do this for fillOption == A | D, so take that into account

	var e = $("#options" + fillOption);
	if (!e.length)
		return;
	var eOther = (fillOption == "D") ? "A" : "D";
	var eOther = $("#options" + eOther);
	if (!eOther.length)
		return;

	// e = table element containing the fillOption options; eOther = table element containing the to-be-hidden options
	// If the to-be-hidden table has a radio button checked we want to un-check it (PERIOD - whether it has an associated
	// to-be-shown radio button or not). If the to-be-shown table has an associated rb (same value) we want to check it.
	// This is not as bad as it sounds because we can just iterate the inputs and if the name is SHIPTYPE we have a winner.

	eOther.fadeOut('fast', function(){
		e.fadeIn('fast');
	});

	var typeChecked = eOther.find("input[name='SHIPTYPE']:checked").val();
	if (typeChecked != undefined) {
		eOther.find("input[name='SHIPTYPE']:checked").attr('checked', false);

		e.find("input[name='SHIPTYPE']").each(function() {
			if ($(this).val() == typeChecked) {
				$(this).attr('checked', true);
				return false; // break out of each loop
			}
		});
		shippingSetShiptype();
	}

	return true;
}

/**
 * Was shipping_page_set_shiptype()
 *
 * Do what needs to be done when selecting given fillOption and shiptype.
 *
 * Note that either parm can be null and the script will use the
 * *currently selected* value for that. The currently selected
 * value will NOT be the one the user is attempting to select,
 * but rather the one that was selected prior to the event
 * that calls this firing.
 *
 * This has been vastly simplified.
 *
 */
function shippingSetShiptype(){

	// get our form
	var thisForm = $("#frmShippingMethod");

    // PDR
    var shipTotal = 0.0;
    var shipVouchered = 0.0;

	// initialize page total
	//var pageTotal = 0.0;


	// get non-rental shipping info
	if (thisForm.find(".shipping-method input[name='SHIPTYPE']").length)
	{
		// get current fill option value
		if (thisForm.find(".fill-method input[name='FILLOPTION']").length)
		{
			var fillOption = thisForm.find(".fill-method input[name='FILLOPTION']:checked").val();
			if (fillOption == undefined)
				fillOption = 'A';
		}
		else
			var fillOption = 'O';

		// get current ship type value
		var mbsShipType = thisForm.find(".shipping-method input[name='SHIPTYPE']:checked").val();
		if (mbsShipType == undefined)
			mbsShipType = '';

		// setup identifier ext
		var idExt = '_' + fillOption + '_' + mbsShipType.replace(/[^a-zA-Z0-9\.]/g, '_');

		// get ship cost
		//var mbsShipCost = null;
		var elem = thisForm.find("input[name='shipcost" + idExt + "']");
		if (elem.length)
        {
			//mbsShipCost = parseFloat(elem.val());
            shipTotal += parseFloat(elem.val());
        }

		// get page total
		//var mbsTotal = subtotal_nonrental + tax_nonrental + mbsShipCost;

		// get voucher total
		//var mbsTotalVoucherable = 0;
		//var mbsShipVoucherable = 0;
		if (subtotal_voucherable !== null)
		{
			//mbsTotalVoucherable = subtotal_voucherable + tax_voucherable;

			if (fillOption !== null && mbsShipType !== null)
			{
				if (ar_ship_covered[fillOption][mbsShipType])
				{
					//mbsShipVoucherable = shippingAmountVoucherable(mbsShipCost);
                    shipVouchered = shippingAmountVoucherable(shipTotal);
                    //mbsTotalVoucherable += mbsShipVoucherable; //shippingAmountVoucherable(mbsShipCost);
				}
			}
		}

		// display ship cost in summary
		//elem = thisForm.find(".mbs-direct .shippingValue");
		//elem = $("#ShippingSummaryAmount");
		//if (elem.length) { 
		//	var mbsShipCostDisp = (mbsShipCost !== null) ? '$' + mbsShipCost.ppPrice(true) : '$0.00';
		//	elem.html(mbsShipCostDisp);
		//}

		// display total
		//elem = thisForm.find(".mbs-direct .totalValue");
		//if (elem.length)
		//	elem.html(mbsTotal.ppPriceMarkup(true));

		// display amount due
		//elem = thisForm.find(".mbs-direct .amountValue");
		//if (elem.length) {
		//	var mbsAmtDue = (mbsTotalVoucherable >= mbsTotal) ? 0.0 : mbsTotal - mbsTotalVoucherable;
		//	elem.html(mbsAmtDue.ppPriceMarkup(true));
		//}

		// add to page total
		//pageTotal += (mbsTotalVoucherable >= mbsTotal) ? 0.0 : mbsTotal - mbsTotalVoucherable;
	}

	// get rental shipping info
	if (thisForm.find(".shipping-method input[name='RENT_SHIPTYPE']").length)
	{
		// get current ship type value
		var rentShipType = thisForm.find(".shipping-method input[name='RENT_SHIPTYPE']:checked").val();
		if (rentShipType == undefined)
			rentShipType = '';

		// setup identifier ext
		var idExt = '_R_' + rentShipType.replace(/[^a-zA-Z0-9\.]/g, '_');

		// get ship cost
		//var rentShipCost = null;
		var elem = thisForm.find("input[name='shipcost" + idExt + "']");
		if (elem.length)
        {
			//rentShipCost = parseFloat(elem.val());
            shipTotal += parseFloat(elem.val());
        }

		// get ship tax
		//var rentShipTax = 0.0;
		//var elem = thisForm.find("input[name='shiptax" + idExt + "']");
		//if (elem.length)
		//	rentShipTax = parseFloat(elem.val());

		// get page total
		//var rentTotal = subtotal_rental + tax_rental + rentShipCost + rentShipTax;

		// display tax in summary
		//elem = thisForm.find(".bookrenter .taxValue");
		//if (elem.length) {
		//	var rentTax = tax_rental + rentShipTax;
		//	var rentTaxDisp = '$' + rentTax.ppPrice(true);
		//	elem.html(rentTaxDisp);
		//}

		// display ship cost in summary
		//elem = thisForm.find(".bookrenter .shippingValue");
		//if (elem.length) {
		//	var rentShipCostDisp = (rentShipCost !== null) ? '$' + rentShipCost.ppPrice(true) : '';
		//	elem.html(rentShipCostDisp);
		//}

		// display total
		//elem = thisForm.find(".bookrenter .totalValue");
		//if (elem.length)
		//	elem.html(rentTotal.ppPriceMarkup(true));

		// add to page total
		//pageTotal += rentTotal;
	}

	// display page total
	//elem = $("#page-total-amount");
	//if (elem && elem.length)
	//	elem.html(pageTotal.ppPriceMarkup(true));

	elem = $("#ShippingSummaryAmount");
	if (elem.length)
		elem.html('$' + shipTotal.ppPrice(true));

	// display voucher total
	elem = $("#ShippingSummaryVoucher");
	if (elem && elem.length)
		elem.html('$' + shipVouchered.ppPrice(true));

	return true;
}

/**
 * Was shipping_amount_voucherable()
 *
 * Assumes it's a type that can be covered.
 */
function shippingAmountVoucherable(ship_cost){

	if (typeof(ship_cost) == 'string')
		ship_cost = parseFloat(ship_cost);

	var covered = 0;
	var ship_covered = 0;
	var i = 0;
	for (i = 0; i < ar_vch_info.length; i++) {
		if (ar_vch_info[i]['PCT']) {
			factor = (subtotal_nonrental > 0) ? (subtotal_voucherable/ar_vch_info[i]['PCT'])/subtotal_nonrental : 1;
			covered = ship_cost*ar_vch_info[i]['PCT']*factor;
			covered = Math.round(covered*100)/100;
			if ((ar_vch_info[i]['MAX'] > 0) && covered + ar_vch_scoreboard['pct_used'] > ar_vch_info[i]['MAX'])
				covered = ar_vch_info[i]['MAX'] - ar_vch_scoreboard['pct_used'];
			ship_cost -= covered;
			ship_covered += covered;
		}
		else {
			factor = (subtotal_nonrental > 0) ? subtotal_voucherable/subtotal_nonrental : 1;
			covered = Math.round((ship_cost*factor)*100)/100;
			if (!is_proxy) {
				if ((covered + ar_vch_scoreboard['reg_used']) > ar_vch_info[i]['AMT'])
					covered = ar_vch_info[i]['AMT'] - ar_vch_scoreboard['reg_used'];
			}
			ship_cost -= covered;
			ship_covered += covered;
		}
	}

	// hmmm, something above causes ship_covered to be a string. should not, don't know what, so casting here.
	ship_covered = parseFloat(ship_covered);
	return ship_covered;
}

/**
 * Validate shipping method form
 */
function validateShippingMethod(){

	if (alreadySubmitted) {
		triggerSmartAlert("Please wait while we gather your information.");
		return false;
	}

	// get our form
	var thisForm = $("#frmShippingMethod");

	// need non-rental ship type selected
	if (thisForm.find(".shipping-method input[name='SHIPTYPE']").length) {
		if (thisForm.find(".shipping-method input[name='SHIPTYPE']").is(':hidden')) {
			var shipType = thisForm.find(".shipping-method input[name='SHIPTYPE']").val();
			if (shipType == "")
				return DoFail(thisForm.find(".shipping-method input[name='SHIPTYPE']"), "Please select a Shipping Method");
		}
		else {
			var shipType = thisForm.find(".shipping-method input[name='SHIPTYPE']:checked").val();
			if (shipType == undefined)
				return DoFail(thisForm.find(".shipping-method input[name='SHIPTYPE']")[0], "Please select a Shipping Method");
		}
	}

	// need rental ship type selected
	if (thisForm.find(".shipping-method input[name='RENT_SHIPTYPE']").length) {
		var shipType = thisForm.find(".shipping-method input[name='RENT_SHIPTYPE']:checked").val();
		if (shipType == undefined)
			return DoFail(thisForm.find(".shipping-method input[name='RENT_SHIPTYPE']")[0], "Please select a Rental Shipping Method");
	}

	alreadySubmitted = true;
	$("#page-footer .step-button").text('Submitting...');

	return true;
}

/**
 * Validate billing form
 */
function validateBilling(){

	if (alreadySubmitted) {
		triggerSmartAlert("Please wait while we gather your information.");
		return false;
	}

	// get our form
	var thisForm = $("#frmBilling");

	// validate student id
	if (thisForm.find("input[name='EXTERNALSTUDENTID']").length) {
		if ($.trim(thisForm.find("input[name='EXTERNALSTUDENTID']").val()) == '')
			return DoFail(thisForm.find("input[name='EXTERNALSTUDENTID']")[0], "Please enter your Student ID");
	}

	// validate cc
	if (thisForm.find("#cc_info").length) {

		var usePayroll = (thisForm.find("input[name='CCPAYROLL']").length && thisForm.find("input[name='CCPAYROLL']").is(":checked")) ? true : false;

		if (!usePayroll) {

			var result = ccFormValid(document.frmBilling);

			var ctl = null;
			var msg = null;
			if (typeof result == "object")
			{
				var code = result[0];
				var ctl = result[1];
				if (result.length > 2)
					var cctype = result[2];
				var msg = null;
				if (code < 110)
					msg = "Please select a Credit Card type";
				else if (code == 120)
					msg = "Please enter a Credit Card number";
				else if (code < 130)
					msg = "Please enter a valid " + cctype + " Credit Card number";
				else if (code < 140)
					msg = "Please enter a valid expiration month for the Credit Card";
				else if (code < 150)
					msg = "Please enter a valid expiration year for the Credit Card";
				else if (code == 150)
					msg = "Please enter data for a non-expired Credit Card";
				else if (code == 160)
					msg = "Please enter a Credit Card Security Code";
				else /* if (code < 170) */
					msg = "Please enter a valid Credit Card Security Code";
				return DoFail(ctl, msg);
			}
		}
	}

	trackCCType($('#cc_card_type').val());

	// validate mbs tos
	if (thisForm.find("input[name='mbsTOS']").length) {
		if (!thisForm.find("input[name='mbsTOS']").is(":checked")) {
			var tosEl = $("#CSAB_tosHeader");
			var tosText = (tosEl.length && $.trim(tosEl.text()) != "") ? tosEl.text() : "Terms of Service";
			return DoFail(thisForm.find("input[name='mbsTOS']")[0], "Please read and agree to the " + tosText);
		}
	}

	// clear
	if (thisForm.find("input[name='CCNUM']").length) {
		thisForm.find("input[name='CCNUM_post']").val(thisForm.find("input[name='CCNUM']").val());
		thisForm.find("input[name='CCNUM']").val('');
	}
	if (thisForm.find("input[name='CCCODE']").length) {
		thisForm.find("input[name='CCCODE_post']").val(thisForm.find("input[name='CCCODE']").val());
		thisForm.find("input[name='CCCODE']").val('');
	}

	alreadySubmitted = true;
	$(".last-action .step-button").text('Submitting...');

	return true;
}

