
	var UsageCodeFuncs = {

//	
//		This is used to interact with #UsageCode 
//		as it can be like 
//			<select id="UsageCode">
//		
//		or like
//			<div id="UsageCode">
//				<input type="radio" />
//

		GetSelectedValue: function() {
			return $("#UsageCode").children("option:selected,input:radio:checked").val();
		},

		SetSelectedValue: function(sValue) {
			UsageCodeFuncs.UnDisable();
			$("#UsageCode").val(sValue).children("input[value=" + sValue + "]").click();
			UsageCodeFuncs.Disable();
		},

		Disable: function() {
			$("#UsageCode").attr("disabled", "disabled").children("input:radio").attr("disabled", "disabled");
		},

		UnDisable: function() {
			$("#UsageCode").removeAttr("disabled").children("input:radio").removeAttr("disabled");
		}
	}


    var arrCascadingLevels = ['CountryCode', 'StateCode', 'ClusterCode'];
    var oCountryOfResidence;
    var oCountryCode;
    var oStateCode;
    var oClusterCode;
    var oPromotionCode;
    var oLanguageCode;
    var oCardType;
    var sCulture;
    var bAccordion;
    var sLastProduct;

    function initPricing() {
    
        oCountryOfResidence = $('#Country');
        oPromotionCode = $('#PromotionCode');
        oStateCode = $('#StateCode');
        oClusterCode = $('#ClusterCode');
        oCountryCode = $('#CountryCode');
        oLanguageCode = $('#LanguageCode');
        oCardType = $('#CardTypeID');
        sCulture = $('#Culture').attr('value');

        logBasketEvent('scOpen,prodView,scAdd', false);

        var bPostedProduct = $('#PostedProduct').attr('value') != '';
        var bHideBlue = $('#HideBlue').attr('value') == 'True';

        if (bPostedProduct) {
            updateProduct($('input.card:checked').attr('value'));
            updatePricing(oClusterCode);
        }
        else if (bHideBlue) {
            updateProduct($('input.card:checked').attr('value'));
            updatePricing(oClusterCode);
        }
        else {
            clearCascade('CountryCode');
            updatePricing(oClusterCode);
        }

        $('#CountryCode, #StateCode, #ClusterCode, #UsageCode, #Country, #CardTypeID').change(function() {
            logBasketEvent('scRemove',true);
            updatePricing(this);
            logBasketEvent('prodView,scAdd',false);
        });
        $('#AccountCustomer, #ApplyPromotion, #UsageCode input:radio, input.card').click(function() {
            logBasketEvent('scRemove',true);
            updatePricing(this);
            logBasketEvent('prodView,scAdd', false);
        });
        $('#PostCode').blur(function() {
            updatePricing(this);
        });

        if (!bHideBlue) {
            var iProductID = $('input.card[checked]').attr('value');
            updateProduct(iProductID);
        }
        var iVal = $('#PaymentMethod[checked],#PaymentMethod2[checked]').attr('value');
        updateDebit(iVal);

        $('#contactLength').change(function() {
            $('.contactlengthhint').hide();
            $('#contactlengthhint' + $('#contactLength').val()).show();
        });
        $('.contactlengthhint').hide();
        $('#contactlengthhint' + $('#contactLength').val()).show();
    }

    function logBasketEvent(sEvent,bLast) {
        try
        {
            var sProd = $('input.card:checked').attr('value')
            var sBWProduct = 'BW' + sProd;
            if (parseInt(sProd) > 4) sBWProduct += '_' + UsageCodeFuncs.GetSelectedValue() + '_' + oCountryCode.val();

            var sTrackingProduct = sBWProduct;
            if (bLast) sTrackingProduct = sLastProduct;

            sLastProduct = sBWProduct;

            if ($('#UseAccordion').attr('value') == 'True') {
                s.events = sEvent;
                s.products = ';' + sTrackingProduct;
                s.linkTrackVars = 'events,products';
                s.linkTrackEvents = sEvent;
                s.tl(true, 'o', 'BW Package Change');
            }
        }
        catch (ex) { }
    }

    function initOther() {
        $('#Country').change(function() {
            updateStates($(this), $('#ContactCounty'), $('#ContactState'));
        });

        updateStates($('#Country'), $('#ContactCounty'), $('#ContactState'));
    }

    function initLayout() {
        bAccordion = $('#UseAccordion').attr('value') == 'True';

        if (!bAccordion) {
            $('#PromotionCode').blur(function() {
                if ($(this).val().length > 0 && confirm('Are you sure you want to apply a promo code')) {
                    updatePricing(this);
                }
            });
        }

        if (bAccordion) {
            $('#accordion h4').click(function() {
                return false;
            }).next('*:gt(0)').hide();

            $('#accordion .section').not(':last').append('<div class="next"><a>' + $('#nextText').val() + '</a></div>');
            $('#accordion .section .next').click(function() {
                if (!validateForm()) return false;
                $(this).parent().slideUp();
                $(this).parent().prev().click(function() {
                    $(this).next().slideDown();
                    $('#accordion h4').next(':not(:animated)').slideUp();
                    return false;
                })
                $(this).parent().parent().nextAll().children('h4:visible').eq(0).next().slideDown();
            })
        }
    }

    function updateStates(oSender, oTextTarget, oDDTarget) {

        var sCountryOfResidence = oCountryOfResidence.attr('value');
        var sUrl = '/zsys/ncms/_global_ajax/ajax_pricing.aspx?ContactCountryCode=' + sCountryOfResidence;

        $.getJSON(sUrl, function(data, status) {

            if (data.ContactStateOptions != null) {

                clearAll('ContactState');
                populateDropDown($('#ContactState'), data.ContactStateOptions);
                oTextTarget.attr('disabled', true);
                oTextTarget.hide();
                oDDTarget.attr('disabled', false);
                oDDTarget.show();
                $('#RequireState').show();
            }
            else {
                oDDTarget.attr('disabled', true);
                oDDTarget.hide();
                oTextTarget.attr('disabled', false);
                oTextTarget.show();
                $('#RequireState').hide();
            }
        });
    }


    function updatePricing(oSender) {
        debugOut('sender', oSender);

        clearCascade(oSender.id);

        var sSender = oSender.id;
        var iProductID = $('input.card:checked').attr('value');
        var sUsage = UsageCodeFuncs.GetSelectedValue();
        var sCountryCode = oCountryCode.attr('value');
        var sStateCode = oStateCode.attr('value');
        var sClusterCode = oClusterCode.attr('value');
        var sCountryOfResidence = oCountryOfResidence.attr('value');
        var sPromotionCode = oPromotionCode.attr('value');
        var bInternal = $('#UseAccordion').attr('value') == 'False';
        var sDiscount = $('#Discount').val();

        var bUseOSA = $('#UseOSA').attr('value') == 'True';
        var bAccCustomer = $('#AccountCustomer').attr('checked');
        var sPostCode = $('#PostCode').val();
        var sCCTypeId = $('#CardTypeID').attr('value');

        var bPartnerRenewal = $('#PartnerRenewal').attr('value') == 'True';

        if (sCountryCode == null) sCountryCode = "";
        if (sStateCode == null) sStateCode = "";
        if (sClusterCode == null) sClusterCode = "";

        var sUrl = '/zsys/ncms/_global_ajax/ajax_pricing.aspx?Sender=' + sSender
                 + '&PromotionCode=' + sPromotionCode
                 + '&ContactCountryCode=' + sCountryOfResidence
                 + '&ProductID=' + iProductID
                 + '&UsageCode=' + sUsage
                 + '&CountryCode=' + sCountryCode
                 + '&StateCode=' + sStateCode
                 + '&ClusterCode=' + sClusterCode
                 + '&Culture=' + sCulture
                 + '&Internal=' + bInternal
                 + '&discount=' + sDiscount
                 + '&useosa=' + bUseOSA
                 + '&accountcustomer=' + bAccCustomer
                 + '&contactpostcode=' + sPostCode
                 + '&cctypeid=' + sCCTypeId
                 + '&PartnerRenewal=' + bPartnerRenewal;

        debugOut("Url", sUrl);

        // Set loading
        setPrices('annual', 'Loading...');
        setPrices('monthly', 'Loading...');
        $('.promotionplaceholder').hide();
        $('.invalidpromo').hide();
        $('.validpromo').hide();     

        debugOut('JSON URL', sUrl);

        $.getJSON(sUrl, function(data, status) {
            debugOut('Annual', data.Annual);
            debugOut('Monthly', data.Monthly);
            debugOut('Promo', data.Promo);
            debugOut('StateOptions', data.StateOptions);
            debugOut('ClusterOptions', data.ClusterOptions);


            if (data.Error == 'false') {
                setPrices('annual', data.Annual);
                setPrices('monthly', data.Monthly);
                setPrices('quarterly', data.Quarterly);

                $('#StateCode').attr('disabled', data.StateOptions == null);
                $('#ClusterCode').attr('disabled', data.ClusterOptions == null);

                // Only re-populate if these were cleared in the first place
                populateDropDown(oStateCode, data.StateOptions);
                populateDropDown(oClusterCode, data.ClusterOptions);

                var bRequirePostcode = (data.PostcodeRequired == 'true');

                if (bRequirePostcode) {
                    if (!$('#PostCodeContainer').hasClass('required')) {
                        $('#PostCodeContainer').addClass('required');
                    }
                    $('#PostCodeContainer').find('span.req').show();
                } 
                else {
                    $('#PostCodeContainer').removeClass('required');
                    $('#PostCodeContainer').find('span.req').hide();
                    $('#PostCodeContainer').children('label').removeClass('validate');
                    $('#PostCodeContainer').css({ background: "#fff" });
                }

                var bAllowInvoice = (data.AllowInvoice == 'true');
                if (bAllowInvoice) {
                    $('#PaymentRow').show();
                    if (document.getElementById('PaymentMethod').checked == true) {
                        updateDebit('creditcard');
                    }
                    else updateDebit('invoice');

                }
                else {
                    $('#PaymentRow').hide();
                    document.getElementById('PaymentMethod').checked = true;
                    document.getElementById('PaymentMethod2').checked = false;
                    updateDebit('creditcard');
                }

                if (data.Promo == null && sPromotionCode != '') {
                    $('.invalidpromo').show();
                    $('.validpromo').hide();
                }

                if (data.Promo != null && sPromotionCode != '') {
                    $('.invalidpromo').hide();
                    $('.validpromo').show();
                }

                if (data.Promo != null) {
                    // Promo successful
                    $('.promotionplaceholder .value').text(data.Promo);
                    $('.promotionplaceholder').show();

                    if (document.getElementById('AccountCustomer') != null) {
                        if (document.getElementById('AccountCustomer').checked == false && data.Promo == "100%") {
                            $('#PaymentRow').hide();
                            $('#creditDebit').hide();
                            $('#directDebit').hide();
                        }
                    }
                    else if (data.Promo == "100%") {
                        $('#PaymentRow').hide();
                        $('#creditDebit').hide();
                        $('#directDebit').hide();
                    }
                }
                else {
                    // Promo failed
                    $('.promotionplaceholder').hide();
                }

                clearAll('LanguageCode');
                populateDropDown(oLanguageCode, data.LanguageOptions);

                clearAllButFirst('CardTypeID');
                populateAndSetDropDown(oCardType, data.Cards, sCCTypeId);

                // Card Issue & CVV
                var bCardCVV = (data.IncludeCVV == 'true');
                var bCardIssue = (data.IncludeIssue == 'true');

                if (bCardCVV) {
                    $('#CardCVVRow').css("visibility", "visible");
                } else {
                    $('#CardCVVRow').css("visibility", "hidden");
                    $('#CardCVV').val('');
                }
                if (bCardIssue) {
                    $('#CardIssueRow').css("visibility", "visible");
                } else {
                    $('#CardIssueRow').css("visibility", "hidden");
                    $('#CardIssue').val('');
                }

                $('#TitanCentreNumber').val(data.TitanCentreNumber);
            }
            else {
                setPrices('annual', 'Error');
                setPrices('monthly', 'Error');
            }
        });
    }

    function setPrices(sPeriod, sValue) {
        if (sValue != null) {
            $('.' + sPeriod + 'costplaceholder .price').text(sValue);
            $('.' + sPeriod + 'costplaceholder').show();
        }
        else {
            $('.' + sPeriod + 'costplaceholder').hide();
        }
    }

    function populateDropDown(oTarget, arrOptions) {
        if (arrOptions != null && oTarget != null && $('option',oTarget).length <= 1) {
            for (var ii = 0; ii < arrOptions.length; ii++) {
                oTarget.append('<option value="' + arrOptions[ii].Value + '">' + arrOptions[ii].Name + '</option>'); 
            }
        }
    }

    function populateAndSetDropDown(oTarget, arrOptions, selectedValue) {
        if (arrOptions != null && oTarget != null && $('option', oTarget).length <= 1) {
            for (var ii = 0; ii < arrOptions.length; ii++) {
                oTarget.append('<option value="' + arrOptions[ii].Value + '" ' + ((selectedValue == arrOptions[ii].Value) ? 'selected="selected"' : '') + '>' + arrOptions[ii].Name + '</option>');
            }
        }
    }

    function clearCascade(sSource) {
        var bStartRemove = false;
        for (var ii = 0; ii < arrCascadingLevels.length; ii++) {
            if (bStartRemove) {
                clearAllButFirst(arrCascadingLevels[ii]);
            }
            if (arrCascadingLevels[ii] == sSource && !bStartRemove) bStartRemove = true;
        }
    }

    function clearAllButFirst(sSource) {
        debugOut("Clearing", sSource);
        var oCtrl = document.getElementById(sSource);
        if (oCtrl == null) return;
        for (var ii = oCtrl.options.length - 1; ii > 0; ii--) {
            oCtrl.options[ii] = null;
        }
    }

    function clearAll(sSource) {
        debugOut("Clearing", sSource);
        var oCtrl = document.getElementById(sSource);
        if (oCtrl == null) {
            return;
        }
        try {
            for (var ii = oCtrl.options.length - 1; ii >= 0; ii--) {
                oCtrl.options[ii] = null;
            }
        }
        catch (ex)
        { }
    }

    function debugOut(sTitle, sMessage) {
        try {
            if (console && console.log) {
                console.log(sTitle + ':', sMessage);
            }
        }
        catch (ex) { }
    }

    $(document).ready(function() {
        initLayout();
        initPricing();
        initOther();
        initDatePickers();
        expandToolTip.init();
    });



    //////////////////////////////////////////////////////////////////////////////////////////////////////////


    function updateProduct(sValue) {
    
        sDefaultCountry = $('#DefaultCountry').attr('value');
    
        if (sValue == "1") { // blue
        	$('#paymentdetails').css('display', 'none');
        	$('#paymentsSingle').css('display', 'none');
        	$('#agreeTerms').css('display', 'none');
        	$('#terms1').css('display', 'none');
        	$('#paymentdetails').css('display', 'none');
            $('#contractLengthRow').hide();
            //document.getElementById('contactLength').selectedIndex = 1;
        }
        else {
        	$('#paymentdetails').css('display', 'block');
        	$('#agreeTerms').css('display', 'block');
        	$('#terms1').css('display', 'inline');
            $('#contractLengthRow').show();
        }

        if (sValue == "2") {
            document.getElementById('paymentsSingle').style.display = 'none';
            document.getElementById('platinumOptions').style.display = 'block';
            document.getElementById('paymentsOptions').style.display = 'block';
            
            if (sDefaultCountry == 'GB' || sDefaultCountry == 'US') {
                document.getElementById('terms1').href = "/businessworld/gold/termsandconditions.html";
                document.getElementById('terms2').href = "/businessworld/gold/termsandconditions.html";
            }
            UsageCodeFuncs.SetSelectedValue('UN');
            UsageCodeFuncs.Disable();
            
            //$('#contractLengthRow').hide();
            //document.getElementById('contactLength').selectedIndex = 1;
        }
        else {
            UsageCodeFuncs.UnDisable();
            $('#paymentsSingle').hide();
        }

        if (sValue == "5" || sValue == "6") { // platinum
            document.getElementById('platinumOptions').style.display = 'block';
            document.getElementById('paymentsOptions').style.display = 'block';
            //$('#paymentsOptions .rowright').hide();
            
            if (sDefaultCountry == 'GB' || sDefaultCountry == 'US') {
                document.getElementById('terms1').href = "/businessworld/plat/termsandconditions.html";
                document.getElementById('terms2').href = "/businessworld/plat/termsandconditions.html";
            }
        }
        else if (sValue != "2") {
            $('#platinumOptions').hide();
            $('#paymentsOptions').hide();
        }
    }

    function updateDebit(sValue) {
        if (sValue == "creditcard") { //credit card
            $('#creditDebit').show();
        }
        else {
            $('#creditDebit').hide();
        }

        if (sValue == "invoice") { //direct debit
            $('#directDebit').show();
        }
        else {
            $('#directDebit').hide();
        }
        // AJAX call to update prices
    }

    function validate(sContainer) {

        var bOk = true;
        var errors = '';
        var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        var objRegExp = /(^-?\d\d*$)/;

        $((sContainer) + ' .required').each(function(index, item) {
            var oInput = ($('input', item));
            var sLabel = $('label', item).html();
            var oSelect = ($('select', item));

            if (
                (oInput.is(':visible') && oInput[0] != null && oInput[0].value == '') ||
                (oSelect[0] != null && oSelect[0].selectedIndex == 0 && oSelect.is(':visible')) ||
                (oSelect[1] != null && oSelect[1].selectedIndex == 0 && oSelect.is(':visible')) ||
                (oInput.is(':visible') && oInput != null && oInput[0] != null && oInput[0].type == 'checkbox' && oInput[0].checked != true)
            ) {
                $('label', item).addClass('validate');
                $(item).css({ background: "#EEE0E5" });

                //errors += "- " + sLabel.replace('<span class="req">*</span>', '').replace('<SPAN class=req>*</SPAN>', '') + "\r\n";
                errors += "- " + sLabel.replace(/<[^<>]+>/g, '').replace('*', '') + "\r\n";

                bOk = false;
            }
            else {

                $('label', item).removeClass('validate');
                $(item).css({ background: "#fff" });
            }

        });


        // NameOnCard
        if ($('#NameOnCard').is(':visible')) {

            //var oNameCardRefPattern = /^[0-9a-zA-Z ]{0,25}$/;
            var sNameCardRefValue = $('#NameOnCard').val() + "";

            if (sNameCardRefValue.length > 25) {
                //if (!oNameCardRefPattern.test(sNameCardRefValue)) {
                    bOk = false;
                    errors += "- " + $('#NameOnCard').siblings('label').text().replace('*','') + "\r\n";
                    $('#NameOnCard').siblings('label').addClass('validate');
                    $('#NameOnCard').parent().css({ background: "#EEE0E5" });
                //}
            }
        }
        
        // email
        if ($('#Email').is(':visible')) {

            str = document.getElementById('Email').value;

            if (!str.match(emailRegEx)) {
                errors += "- " + $('#ErrorValidEmail').attr('value') + "\r\n";
                $('#validateEmail1').addClass('validate');
                $('#validateEmail1').css({ background: "#EEE0E5" });
                bOk = false;
            }
            else {
            }
            if ($('#Email').is(':visible') && $('#EmailCheck').is(':visible')) {
                if (document.getElementById('Email').value != document.getElementById('EmailCheck').value) {
                    errors += "- " + $('#ErrorEmailMatch').attr('value') + "\r\n";
                    $('#validateEmail1').addClass('validate');
                    $('#validateEmail1').css({ background: "#EEE0E5" });
                    $('#validateEmail2').addClass('validate');
                    $('#validateEmail2').css({ background: "#EEE0E5" });
                    bOk = false;
                }
                else {
                }
            }
        }
        else {
        }

        // postcode
        var postcodeReg = /^[a-zA-Z0-9 -]+$|^$/;

        if (!$('#PostCode').val().match(postcodeReg)) {
            $('#PostCodeContainer').children('label').addClass('validate');
            $('#PostCodeContainer').css({ background: "#EEE0E5" });
            errors += "- " + $('#PostCodeContainer').children('label').html().replace(/<[^<>]+>/g, '').replace('*', '') + "\r\n";
            bOk = false;
        }
        
        

        if ($('#CentreID').is(':visible')) {
            if (!document.getElementById('CentreID').value.match(objRegExp)) {
                errors += "- " + $('#ErrorValidCentre').attr('value') + "\r\n";
                $('#validateCentre').addClass('validate');
                $('#validateCentre').css({ background: "#EEE0E5" });
                bOk = false;
            }
        }
        else {
        }

        // CardNumber
        if ($('#CardNumber').is(':visible')) {
            sCardNumber = $('#CardNumber').val() + "";  
            cardchoice = parseInt($('#CardTypeID option:selected').val());

            if (sCardNumber.length > 0) {
                if (!validateCardNumber(sCardNumber, cardchoice)) {
                    bOk = false;
                    errors += "- " + $('#CardNumber').siblings('label').text().replace('*', '') + "\r\n";
                    $('#CardNumber').siblings('label').addClass('validate');
                    $('#CardNumber').parent().css({ background: "#EEE0E5" });
                }
            }
        }

        // CardValidMonth
        if ($('#CardValidMonth').is(':visible')) {
            var oNow = new Date();
            if (oNow.getFullYear() == $('#CardValidYear').val()) {
                if (oNow.getMonth() < document.getElementById('CardValidMonth').selectedIndex - 1) {
                    bOk = false;
                    errors += "- " + $('#CardValidYear').siblings('label').text() + "\r\n";
                    $('#CardValidYear').siblings('label').addClass('validate');
                    $('#CardValidYear').parent().css({ background: "#EEE0E5" });
                } else {
                    $('#CardValidYear').siblings('label').removeClass('validate');
                    $('#CardValidYear').parent().css({ background: "#fff" });
                }
            }
        }

        if ($('#CardExpiryMonth').is(':visible')) {
            var oNow = new Date();
            if (oNow.getFullYear() == $('#CardExpiryYear').val()) {
                if (oNow.getMonth() > document.getElementById('CardExpiryMonth').selectedIndex - 1) {
                    bOk = false;
                    errors += "- " + $('#CardExpiryYear').siblings('label').text() + "\r\n";
                    $('#CardExpiryYear').siblings('label').addClass('validate');
                    $('#CardExpiryYear').parent().css({ background: "#EEE0E5" });              
                }
            }
        }

        // CardIssue
        if($('#CardIssueRow').css("visibility") == "visible") {
        
            var oCardIssuePattern = /^[0-9]{0,2}$/;
            var sCardIssue = $('#CardIssue').val() + "";

            $('#CardIssue').siblings('label').removeClass('validate');
            $('#CardIssue').parent().css({ background: "none" });

            if (sCardIssue.length > 0) {
                if (!oCardIssuePattern.test(sCardIssue)) {
                    bOk = false;
                    errors += "- " + $('#CardIssue').siblings('label').text() + "\r\n";
                    $('#CardIssue').siblings('label').addClass('validate');
                    $('#CardIssue').parent().css({ background: "#EEE0E5" });
                }
            }
        }

        // CardCVV
        if ($('#CardCVVRow').css("visibility") == "visible") {
        
            var oCardCVVPattern;
            var sCardCVV = $('#CardCVV').val() + "";
            
            if ($('#CardTypeID option:selected').val() == 164 ||
                $('#CardTypeID option:selected').val() == 3) {
                oCardCVVPattern = /^[0-9]{4}$/;
            } else {
                oCardCVVPattern = /^[0-9]{3}$/;
            }

            $('#CardCVV').siblings('label').removeClass('validate');
            $('#CardCVV').parent().css({ background: "none" });

            if (!oCardCVVPattern.test(sCardCVV)) {
                bOk = false;
                errors += "- " + $('#CardCVV').siblings('label').text().replace('*', '') + "\r\n";
                $('#CardCVV').siblings('label').addClass('validate');
                $('#CardCVV').parent().css({ background: "#EEE0E5" });
            }
            
        }

        // Pivotal Ref
        if ($('#PivotalRef').is(':visible')) {
        
        	var oPivotalRefPattern = /^[0-9a-zA-Z]{0,20}$/;
        	var sPivotalRefValue = $('#PivotalRef').val() + "";
        	
			$('#PivotalRef').siblings('label').removeClass('validate');
			$('#PivotalRef').parent().css({ background: "none" });
        	
        	if(sPivotalRefValue.length > 0) {
				if(!oPivotalRefPattern.test(sPivotalRefValue)){
				
					bOk = false;
					errors += "- " + $('#PivotalRef').siblings('label').text() + "\r\n";
					$('#PivotalRef').siblings('label').addClass('validate');
					$('#PivotalRef').parent().css({ background: "#EEE0E5" });
				}
        	}
        }
        

        if (errors == '') {
        }
        else {
            alert($('#ErrorEnterFields').attr('value') + "\r\n" + errors);
        }


        return (bOk)
    }


    function validateCardNumber(sCardNumber, iSelectedValue) {

        switch (iSelectedValue) {
            case 1:    //MasterCard
            case 163:
                return CreditCardNumberValidation.MasterCard(sCardNumber);

            case 2:    //Visa
            case 161:  //Visa
            case 162:  //Visa Debit
            case 170:  //Visa Electron
                return CreditCardNumberValidation.Visa(sCardNumber);

            case 3:  //American Express:
            case 164:
                return CreditCardNumberValidation.Amex(sCardNumber);

            case 4:  //Diners:
            case 167:
                return CreditCardNumberValidation.DinersClub(sCardNumber);

            case 168:  //JCB
                return CreditCardNumberValidation.JCB(sCardNumber);

            case 169:  //SOLO
                return CreditCardNumberValidation.Solo(sCardNumber);

            default:
                return CreditCardNumberValidation.Generic(sCardNumber);
        }
        
    }
    
    

    function validateForm() {
        var bOk = true;

        if (!validate('#applicationform')) {
            bOk = false;
        }
        else {
        }

        return bOk;
    }
    
    
    function SetNameOnCard()
    {
         var noc = document.getElementById('FirstName').value + ' ' + document.getElementById('LastName').value;
         
         if (noc.length > 25) {
            noc = document.getElementById('FirstName').value.substring(0,1) + ' ' + document.getElementById('LastName').value;
         }
         if (noc.length <= 25) {
            document.getElementById('NameOnCard').value = noc;
        }
        else {
            document.getElementById('NameOnCard').value = '';
        }
    }




    var CreditCardNumberValidation = {

        // "Public" functions:

        Generic: function(sCardNumber) {
            return this._Test(/^\d{12,19}$/, sCardNumber);
        },

        Amex: function(sCardNumber) {
            return this._Test(/^3[47]\d{13}$/, sCardNumber);
        },

        DinersClub: function(sCardNumber) {
            return this._Test(/^(30[0-5]|36\d|38\d)\d{11}$/, sCardNumber);
        },

        Discover: function(sCardNumber) {
            return this._Test(/^6011\d{12}$/, sCardNumber);
        },

        JCB: function(sCardNumber) {
            return this._Test(/^35((28)|(89))\d{12}$/, sCardNumber);
        },

        MasterCard: function(sCardNumber) {
            return this._Test(/^5[1-5]\d{14}$/, sCardNumber);
        },

        Solo: function(sCardNumber) {
            return this._Test(/^((6334)|(6767))\d{12}(\d{2,3})?$/, sCardNumber);
        },

        Visa: function(sCardNumber) {
            return this._Test(/^4\d{12}(\d{3})?$/, sCardNumber);
        },

        // "Private" functions:

        _Test: function(oRegex, sCardNumber) {

            // Strip any non-digits (useful for credit card numbers with spaces and hyphens)
            sCardNumber = sCardNumber.replace(/\D/g, '');

            if (oRegex.test(sCardNumber)) {
                return this._LuhnAlgorithm(sCardNumber);
            }

            return false;
        },

        _LuhnAlgorithm: function(sCardNumber) {

            //Checks for parity in the card number:

            var bDouble = false;
            var iSum = 0, iNum;

            for (var i = sCardNumber.length - 1; i >= 0; i--) {

                iNum = parseInt(sCardNumber.charAt(i));

                if (bDouble) {
                    iSum += (iNum > 4) ? (iNum * 2 - 9) : (iNum * 2);
                } else {
                    iSum += iNum;
                }

                bDouble = !bDouble;
            }

            return (iSum % 10) == 0;
        }
    }


    
    
    
    
    
    
