Event.observe(window, 'load', function() {
	if ($("total") != null) {
		updateCreditCardFields();
		addCreditCardNumberListeners();
	}
});

/*
 Shows or hides fields on the buy pass page as
	selected by the user
*/
function toggleStep6(elemToShow) {
	elemToShow = $(elemToShow);
	var elems = [ "post_address_div", "email_address_div" ];
	
	for (var i = 0; i < elems.length; i++) {
		var ce = $(elems[i]);
		if (ce == elemToShow) {
			ce.show();
		}
		else {
			ce.hide();
		}
	}
}

/*
 Checks whether all mandatory fields are filled out.
*/
function validateForm() {
	var fields = $$(".validatorText");
	var submitForm = true;
	
	for (var i = 0; i < fields.length; i++) {
		var text = fields[i];
		var input = text.previous("input");

		// check if this field is in an optional section
		var optional = input.up(".optional");
		if (optional != null && !optional.visible()) {
			continue;
		}

		// ignore if is a confirm field 
		if (text.hasClassName("confirm") || input.hasClassName("one_of_two")) { text.hide(); continue; }
		
		// otheriwse check if the value is non-empty
		var value = $F(input);
		if (value == "") {
			text.show();
			submitForm = false;
		}
		else {
			text.hide();
		}
	}
	
	if (submitForm) {
		submitForm = checkConfirmLicensePlate();
	}
	//r tagOk = checkTagOrAccountNumber();
	var ccOk = checkCreditCardIsValid();
//  mitForm = submitForm && tagOk && ccOk;
	submitForm = submitForm && ccOk;
	
	return submitForm;
}

/*
function checkTagOrAccountNumber() {
    var res = true;
    
    var tag = $("txtTagNo");
    var acct = $("txtTollAccountNumber");
    var visible = (tag != null && tag.up(".optional").visible());

    if (visible && tag != null && acct != null) {
        if ($F(tag) == "" && $F(acct) == "") {
            res = false;
            tag.next(".validatorText").show();
        }
    }
    
    return res;
}
*/

function checkCreditCardIsValid() {
    var res = true;
    var ccField = $("txtCCNO1");
    if (ccField != null) {
        ccField.next(".creditCardValidatorText").hide();
    }
    
    for (var i = 1; res && i <= 4; i++) {
        ccField = $("txtCCNO" + i);
        if (ccField == null) { continue; }
        
        var optional = ccField.up(".optional");
        if (!optional.visible()) {
            continue;
        }
        else if (ccField && ccField.visible() && $F(ccField).length != ccField.maxLength) {
            ccField.next(".creditCardValidatorText").show();
            res = false;
        }
    }
    
    return res;
}

/*
 Checks the licence plate matches the confirm value
*/
function checkConfirmLicensePlate() {
	var res = true;
	var confirm = $("txtLicPlateNoConfirm");
	if (confirm != null && $F("txtLicPlateNo") != $F(confirm)) {
		res = false;
		confirm.next(".confirm").show();
	}
	
	return res;
}

function getTotalCharges() {
    if (isBuyPassPage()) {
        return getTotalBuyPassCharges();
    }
    else {
        return getTotalNoticeCharges();
    }
}

function isBuyPassPage() {
    return $("lblOpeningFee") != null;
}

function floatFromDollarAmount(elem) {
    var val = elem.innerHTML;
    return parseFloat(val.substring(1, val.length));
}

function getTotalBuyPassCharges() {
	var elems = [ "lblChargeEmailStatement", "lblOpeningFee", "subtotal", "admin_charges" ];
	var total = 0;
	for (var i = 0; i < elems.length; i++) {
	    var elem = $(elems[i]);
        if (elem != null) {
    	    var optional = elem.up(".optional");
	        if (optional == null || optional.visible()) {
		        total += floatFromDollarAmount(elem);
	        }
	    }
	};
	
	return total;
}

function getTotalNoticeCharges() {
    var elems = $$(".subtotal");
    var total = 0.0;
    
    for (var i = 0; i < elems.length; i++) {
        total += floatFromDollarAmount(elems[i]);
    }
    
    return total;
}

function payingByTag() {
    return $F("rbtnDeductFromTollAcc") == "rbtnDeductFromTollAcc";
}

function getSurchargeForSelectedCard() {
    var select = $("ddlTypeOfCC");
    var selected = $(select.options[select.selectedIndex]);
    
    var surcharge = parseFloat(selected.readAttribute("surcharge"));
    return surcharge;
}

function updateCreditCardFields() {
	if (getSurchargeForSelectedCard() > 1) {
		$("lblCCNote").show();
	}
	else {
		$("lblCCNote").hide();
	}
	
	var surcharge = isOptionalElemVisible("lblCCNote", ".credit_card") ? getSurchargeForSelectedCard() : 1;
	
	updateSubTotals();
	var total = surcharge * getTotalCharges();
	total = total.toFixed(2);
	$("totalLabel").update("$" + total);
	$("total").value = total;
	
	updateCreditCardNumberFields();
}

function updateSubTotals() {
    if (!isBuyPassPage()) {
        if (payingByTag()) {
            $$(".no_admin_charge").each(function(e) { e.show(); });
            $$(".admin_charge").each(function(e) { e.hide(); });
            $$(".tag_only").each(function(e) { e.show(); });
        }
        else {
            $$(".admin_charge").each(function(e) { e.show(); });
            $$(".no_admin_charge").each(function(e) { e.hide(); });
            $$(".tag_only").each(function(e) { e.hide(); });
        }
        
        $$(".subtotal").each(function(st) {
            var fare = floatFromDollarAmount(st.up(".notice").down(".fare"));
            var admin = floatFromDollarAmount(st.up(".notice").down(".admin"));
            
            var subtotal = fare;
            if (!payingByTag()) {
                subtotal += admin;
            }
            st.update("$" + subtotal.toFixed(2));
        });
    }
}

function updateCreditCardNumberFields() {
    var cardType = $F("ddlTypeOfCC");
    
    var widths = [ 4, 4, 4, 4 ];
    if (cardType == "D") {
        widths = [ 4, 6, 4 ];
    }
    else if (cardType == "A") {
        widths = [5, 5, 5 ];
    }
    
    for (var i = 0; i < 4; i++) {
        var field = $("txtCCNO" + (i + 1));
        field.value = "";
        
        if (i < widths.length) {
            field.show();
            field.maxLength = widths[i];
            var pxWidth = (widths[i] * 10) + "px";
            field.setStyle({ width : pxWidth });
        }
        else {
            field.hide();
        }
    }
}

function isOptionalElemVisible(elem, parentSelector) {
    var res = false;
    elem = $(elem);
    if (parentSelector == null) { parentSelector = ".optional"; }
    
    if (elem != null) {
        var optional = elem.up(parentSelector);
        res = (optional != null && optional.visible());
    }
    
    return res;
}

function togglePaymentType(elem) {
    var value = $F(elem);
    var toShow = ".credit_card";
    var toHide = ".toll_account";
    
    if (value == "rbtnDeductFromTollAcc") {
        toHide = ".credit_card";
        toShow = ".toll_account";
    }
    
    $$(toHide).each(function(e) { e.hide(); });
    $$(toShow).each(function(e) { e.show(); });
    
    updateCreditCardFields();
}

function addCreditCardNumberListeners() {
    var func = function(evt) {
        var elem = Event.element(evt);
            if (elem) {
            var val = $F(elem);
            
            var tab = 9;
            var backspace = 8;
            var del = 46;
            
            if (val.length >= elem.maxLength && evt.keyCode != tab && evt.keyCode != backspace && evt.keyCode != del) {
                var nextField = elem.next('input');
                if (nextField && nextField.visible() && nextField.readAttribute("type") == "text") {
                    try {
                        nextField.focus();
                    }
                    catch (err) {}
                }
            }
        }
    }
    
    for (var i = 0; i < 4; i++) {
        var elem = $("txtCCNO" + (i + 1));
        Event.observe(elem, "keyup", func);
    }
}