var donationForm;

// Path to the blank image must point to a valid location on your server
Ext.BLANK_IMAGE_URL = 'scripts/ext-3.1.1/resources/images/default/s.gif';

// Main application entry point
Ext.onReady(function() {
    Ext.QuickTips.init();
    
    Ext.apply(Ext.form.VTypes, {
        BankAccount: function(v) {
            if (!/^\d{3}\-\d{7}\-\d{2}$/.test(v)) {
	            return false;
            }
			
			var n = parseInt(v.substring(0, 3), 10);
			var b = n;
			b = (b % 97) * (10000000 % 97);
			n = parseInt(v.substring(4, 7), 10);
			b = (b % 97) + (n % 97) * (10000 % 97);
			n = parseInt(v.substring(7, 10), 10);
			b = (b % 97) + (n % 97) * 10;
			n = parseInt(v.substring(10, 11), 10);
			b = (b % 97) + n;
			b = b % 97;
			if (b == 0) {
				b = 97;
			}
			
			n = parseInt(v.substring(12, 14) ,10);
            return b == n;
        },
        BankAccountText: l10nInvalidAccount,
        BankAccountMask: /[\d\-]/i,
        CreditCard: function(sCardNumber) {
        	if (Ext.getDom('payment_cardBrandBancontact').checked) {
        		// bancontact card number validation
	            return /^6703\d{13}$/.test(sCardNumber);
        	} else {
        		// credit card number validation
	            if (!/^\d{16}$/.test(sCardNumber)) {
		            return false;
	            }
				
				var bDoubleDigit = false;
				var iSum = 0, iNum;
	 
		        for (var i = sCardNumber.length - 1; i >= 0; i--){
		            iNum = parseInt(sCardNumber.charAt(i));
		 
		            if (bDoubleDigit){
		                iSum += (iNum > 4) ? (iNum * 2 - 9) : (iNum * 2);
		            } else {
		                iSum += iNum;
		            }
		 
		            bDoubleDigit = !bDoubleDigit;
		        }
	 
		        return (iSum % 10) == 0;
        	}
    	},
    	CreditCardText: l10nInvalidCardNumber,
    	CreditCardMask: /[\d]/i
    });
    
    Ext.form.Field.prototype.msgTarget = 'side';

    donationForm = new Ext.form.BasicForm('donation-form', {
	    standardSubmit: true,
	    setPaymentMethod: function(method) {
	    	Ext.getCmp('payment_cardBrand').allowBlank = true;
	    	Ext.getCmp('payment_cardNumber').allowBlank = true;
	    	Ext.getCmp('payment_cardExpirationMonth').allowBlank = true;
	    	Ext.getCmp('payment_cardExpirationYear').allowBlank = true;
	    	Ext.getCmp('payment_cardVerification').allowBlank = true;
	    	Ext.getCmp('payment_bank').allowBlank = true;
	    	Ext.getCmp('payment_recurringDay').allowBlank = true;
	    	Ext.getCmp('payment_account').allowBlank = true;
	    	
	    	if ('ogone' == method) {
		    	Ext.getCmp('payment_cardBrand').allowBlank = false;
		    	Ext.getCmp('payment_cardNumber').allowBlank = false;
		    	Ext.getCmp('payment_cardExpirationMonth').allowBlank = false;
		    	Ext.getCmp('payment_cardExpirationYear').allowBlank = false;
			    if (!Ext.getDom('payment_cardBrandBancontact').checked) { 
			    	Ext.getCmp('payment_cardVerification').allowBlank = false;
			    }
	    	} else if ('bank' == method) {
		    	Ext.getCmp('payment_bank').allowBlank = false;
		    	Ext.getCmp('payment_recurringDay').allowBlank = false;
		    	Ext.getCmp('payment_account').allowBlank = false;
	    	}
	    	document.forms['donation-form'].elements['paymentMethod'].value = method;
    	},
    	isValid: function() {
    		var result = true;
    		if ('bank' == this.getPaymentMethod() && isSingleAmountProvided()) {
    			Ext.Msg.show({
    				   title: l10nNotapplicableCurringPaymentTitle,
    				   msg: l10nNotapplicableCurringPaymentText,
    				   icon: Ext.MessageBox.ERROR
    				});
    			result = false;
    		}
    		return Ext.form.BasicForm.prototype.isValid.call(this) && result;
    	},
    	getPaymentMethod: function() {
    		return document.forms['donation-form'].elements['paymentMethod'].value;
    	}
    });

    var personalTitle = new Ext.form.ComboBox({
        store: new Ext.data.ArrayStore({
	        fields: ['id', 'text'],
	        data : [
				['mr', l10nTitleMr],
				['mrs', l10nTitleMrs]
			]
	    }),
        allowBlank: false,
	    width: 70,
	    hiddenName: 'title',
	    valueField: 'id',
        displayField: 'text',
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        selectOnFocus: true,
        blankText: l10nMandatoryTitle
	});
	personalTitle.applyToMarkup('personal_title');
    donationForm.add(personalTitle);
	
    var personalFirstname = new Ext.form.TextField({
        allowBlank: false,
        blankText: l10nMandatoryFirstname
    });
    personalFirstname.applyToMarkup('personal_firstname');
    donationForm.add(personalFirstname);

    var personalLastname = new Ext.form.TextField({
        allowBlank: false,
        blankText: l10nMandatoryLastname
    });
    personalLastname.applyToMarkup('personal_lastname');
    donationForm.add(personalLastname);

    var personalStreet = new Ext.form.TextField({
        allowBlank: false,
        blankText: l10nMandatoryStreet
    });
    personalStreet.applyToMarkup('personal_street');
    donationForm.add(personalStreet);

    var personalHousenumber = new Ext.form.TextField({
        allowBlank: false,
        blankText: l10nMandatoryHousenumber
    });
    personalHousenumber.applyToMarkup('personal_housenumber');
    donationForm.add(personalHousenumber);

    var personalMailbox = new Ext.form.TextField({
        allowBlank: true
    });
    personalMailbox.applyToMarkup('personal_mailbox');
    donationForm.add(personalMailbox);

    var personalPostcode = new Ext.form.TextField({
        allowBlank: false,
        blankText: l10nMandatoryPostcode
    });
    personalPostcode.applyToMarkup('personal_postcode');
    donationForm.add(personalPostcode);

    var personalLocation = new Ext.form.TextField({
        allowBlank: false,
        blankText: l10nMandatoryLocation
    });
    personalLocation.applyToMarkup('personal_location');
    donationForm.add(personalLocation);

    var personalCountry = new Ext.form.TextField({
        allowBlank: false,
        blankText: l10nMandatoryCountry
    });
    personalCountry.applyToMarkup('personal_country');
    donationForm.add(personalCountry);

    var personalEmail = new Ext.form.TextField({
	    vtype: 'email',
        allowBlank: false,
        blankText: l10nMandatoryEmail,
        invalidText: l10nInvalidEmail,
        vtypeText: l10nInvalidEmail
    });
    personalEmail.applyToMarkup('personal_email');
    donationForm.add(personalEmail);

    var personalTelephone = new Ext.form.TextField({
    });
    personalTelephone.applyToMarkup('personal_telephone');
    donationForm.add(personalTelephone);

    var donationrecurringFree = new Ext.form.NumberField({
	    id: 'donationrecurring-free',
    	decimalPrecision: 0,
    	minValue: 5,
        nanText: l10nInvalidDonationFree,
        invalidText: l10nInvalidDonationFree,
    	minText: l10nToolowDonationFree,
    	validator: function(value) {
	    	return !Ext.isEmpty(value) || isDonationAmountSelected() || !Ext.isEmpty(Ext.getCmp('donationonce-free').getValue());
    	}
    });
    donationrecurringFree.applyToMarkup('donationrecurring-free');
    donationrecurringFree.on('change', function(ev, target) {
    	uncheckAllDonationAmounts();
    	Ext.getCmp('donationonce-free').reset();
    	adaptRecurringSection();
	});
    donationForm.add(donationrecurringFree);

    var donationonceFree = new Ext.form.NumberField({
	    id: 'donationonce-free',
    	decimalPrecision: 0,
    	minValue: 5,
        nanText: l10nInvalidDonationFree,
        invalidText: l10nInvalidDonationFree,
    	minText: l10nToolowDonationFree,
    	validator: function(value) {
	    	return !Ext.isEmpty(value) || isDonationAmountSelected() || !Ext.isEmpty(Ext.getCmp('donationrecurring-free').getValue());
    	}
    });
    donationonceFree.applyToMarkup('donationonce-free');
    donationonceFree.on('change', function(ev, target) {
    	uncheckAllDonationAmounts();
    	Ext.getCmp('donationrecurring-free').reset();
    	adaptRecurringSection();
	});
    donationForm.add(donationonceFree);

    var paymentCardBrand = new Ext.form.RadioGroup({
	    id: 'payment_cardBrand',
	    validate: function() {
    		if ('bank'== donationForm.getPaymentMethod()) { 
    			return true;
    		}

		    if (Ext.getDom('payment_cardBrandBancontact').checked) {
		    	Ext.getCmp('payment_cardVerification').allowBlank = true;
		    	Ext.getCmp('payment_cardVerification').reset();
		    	Ext.get('payment_cardVerification_row').hide();
		    } else {
		    	Ext.getCmp('payment_cardVerification').allowBlank = false;
		    	Ext.get('payment_cardVerification_row').show();
		    }		    	
		    
		    this.clearInvalid();
		    if (this.allowBlank) {
			    return true;
		    }
		    var result =
			    Ext.getDom('payment_cardBrandVisa').checked ||
			    Ext.getDom('payment_cardBrandMastercard').checked ||
			    Ext.getDom('payment_cardBrandAmex').checked ||
			    Ext.getDom('payment_cardBrandBancontact').checked;
		    if (!result) {
			    this.markInvalid(l10nMandatoryCardBrand);
		    }
		    return result;
	    }
    });
    paymentCardBrand.applyToMarkup('payment_cardBrand');
    donationForm.add(paymentCardBrand);

    var paymentCardNumber = new Ext.form.TextField({
	    id: 'payment_cardNumber',
	    vtype: 'CreditCard',
    	minLength: 16,
    	maxLength: 17,
        blankText: l10nMandatoryCardNumber,
        minLengthText: l10nTooshortCardNumber
    });
    paymentCardNumber.applyToMarkup('payment_cardNumber');
    donationForm.add(paymentCardNumber);

    var paymentCardExpirationMonth = new Ext.form.ComboBox({
	    id: 'payment_cardExpirationMonth',
        store: new Ext.data.ArrayStore({
	        fields: ['month'],
	        data : [['01'], ['02'], ['03'], ['04'], ['05'], ['06'], ['07'], ['08'], ['09'], ['10'], ['11'], ['12']]
	    }),
	    maxLength: 2,
	    width: 50,
        displayField: 'month',
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        selectOnFocus: true,
        blankText: l10nMandatoryCardExpirationMonth
    });
    paymentCardExpirationMonth.applyToMarkup('payment_cardExpirationMonth');
    donationForm.add(paymentCardExpirationMonth);

    var paymentCardExpirationYear = new Ext.form.ComboBox({
	    id: 'payment_cardExpirationYear',
        store: new Ext.data.ArrayStore({
	        fields: ['year'],
	        data : [
				['10'], ['11'], ['12'], ['13'], ['14'], ['15'], ['16'], ['17'], ['18'], ['19'], ['20'],
				['21'], ['22'], ['23'], ['24'], ['25'], ['26'], ['27'], ['28'], ['29'], ['30']
			]
	    }),
	    maxLength: 2,
	    width: 70,
        displayField: 'year',
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        selectOnFocus: true,
        blankText: l10nMandatoryCardExpirationYear
    });
    paymentCardExpirationYear.applyToMarkup('payment_cardExpirationYear');
    donationForm.add(paymentCardExpirationYear);

    var paymentCardVerification = new Ext.form.NumberField({
	    id: 'payment_cardVerification',
    	decimalPrecision: 0,
    	minLength: 3,
    	maxLength: 4,
    	minValue: 0,
        blankText: l10nMandatoryCardVerification,
        minLengthText: l10nTooShortCardVerification
    });
    paymentCardVerification.applyToMarkup('payment_cardVerification');
    donationForm.add(paymentCardVerification);

    var paymentBank = new Ext.form.ComboBox({
	    id: 'payment_bank',
        store: new Ext.data.ArrayStore({
	        fields: ['bank'],
	        data : [
				['Fortis'],
				['Dexia'],
				['KBC']
			]
	    }),
	    width: 100,
        displayField: 'bank',
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        selectOnFocus: true,
        blankText: l10nMandatoryBank
    });
    paymentBank.applyToMarkup('payment_bank');
    donationForm.add(paymentBank);

    var paymentRecurringDay = new Ext.form.ComboBox({
	    id: 'payment_recurringDay',
        store: new Ext.data.ArrayStore({
	        fields: ['day'],
	        data : [
				[1], [2], [3], [4], [5], [6], [7], [8], [9], [10],
				[11], [12], [13], [14], [15], [16], [17], [18], [19], [20],
				[21], [22], [23], [24], [25], [26], [27], [28], [29], [30]
			]
	    }),
	    width: 100,
        displayField: 'day',
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        selectOnFocus: true,
        blankText: l10nMandatoryRecurringDay
    });
    paymentRecurringDay.applyToMarkup('payment_recurringDay');
    donationForm.add(paymentRecurringDay);

    var paymentAccount = new Ext.form.TextField({
	    id: 'payment_account',
	    vtype: 'BankAccount',
    	minLength: 14,
    	maxLength: 14,
        blankText: l10nMandatoryAccount,
        minLengthText: l10nTooShortAccount
    });
    paymentAccount.applyToMarkup('payment_account');
    donationForm.add(paymentAccount);
    
    new Ext.ToolTip({
        target: 'payment_domiciliation_tip',
        anchorToTarget: false,
        anchorOffset: -20,
        trackMouse : true,
        width: 120,
        dismissDelay: 0,
        html: l10nPaymentDomiciliationTip
    });
});

function uncheckAllDonationAmounts() {
	for (var i = 0; i < document.forms['donation-form'].elements.length; i++) {
		if ('donation' == document.forms['donation-form'].elements[i].name) {
			document.forms['donation-form'].elements[i].checked = false;
		}
	}
}

function isDonationAmountSelected() {
	for (var i = 0; i < document.forms['donation-form'].elements.length; i++) {
		if ('donation' == document.forms['donation-form'].elements[i].name &&
			document.forms['donation-form'].elements[i].checked) {
			return true;
		}
	}
	return false;
}

function isSingleAmountProvided() {
	for (var i = 0; i < document.forms['donation-form'].elements.length; i++) {
		if ('donation' == document.forms['donation-form'].elements[i].name &&
			document.forms['donation-form'].elements[i].value.match("^once_") &&
			document.forms['donation-form'].elements[i].checked) {
			return true;
		}
	}
	return !Ext.isEmpty(Ext.getDom('donationonce-free').value);
}

function resetFreeAmounts() {
	Ext.getCmp('donationrecurring-free').reset();
	Ext.getCmp('donationonce-free').reset();
	adaptRecurringSection();
}

function adaptRecurringSection() {
	if (isSingleAmountProvided()) {
		if (Ext.get('payment-recurring-section').isVisible()) {
			donationForm.clearInvalid();
			Ext.get('payment-recurring-section').hide();
		}
		if (!Ext.get('payment_cardBrandBancontact').isVisible()) {
			Ext.get('payment_cardBrandBancontact_logo').show();
			Ext.get('payment_cardBrandBancontact').show();
	    	Ext.get('payment_cardVerification_row').show();
		}
	} else {
		Ext.get('payment-recurring-section').show();
		if (Ext.get('payment_cardBrandBancontact').isVisible()) {
			Ext.get('payment_cardBrandBancontact_logo').hide();
			Ext.get('payment_cardBrandBancontact').hide();
		}
    	Ext.get('payment_cardVerification_row').show();
    	Ext.get('payment_cardBrandBancontact').dom.checked = false;
	}
}

function validateCardBrand() {
	Ext.getCmp('payment_cardBrand').validate();
}
