// JavaScript Document

DonationFormUtils = function(api, confirm, dialogStyle, minGift) {
	this._api = api;
	this._confirm = confirm;
	this._dialogStyle = dialogStyle;
	this._minGift = minGift;
}

DonationFormUtils.prototype = {
	_api: null,
	_form: null,
	_confirm: false,
	_dialogStyle: 'default',
        _minGift: '$5.00',
	_giftAmount: null,
	_firstName: null,
	_lastName: null,
	_email: null,
	_street1: null,
	_street2: null,
	_city: null,
	_state: null,
	_country: null,
	_zip: null,
	_cardLast4: null,
	_cardExpMonth: null,
	_cardExpYear: null,
	_valueOfGoods: null,
	_taxDeductibleAmount: null,
	_confirmationCode: null,
	_orgTaxId: null,

	setGiftAmount: function(amt) {
		this._giftAmount = amt;
	},

		
	submitFormUsingAjax : function(form) {
		this._form = form;
		// Hide any error messages
		_errors = new Array();
		findAllOfClass (this._form, 'ErrorMessage', _errors);
		if (_errors.length > 0) {
			for(var i = 0;i < _errors.length; i++) {   
				_el = _errors[i]; 
				_el.style.display = 'none';
			}
		}

		if (this.validateForm()) {
/*			if (this._confirm) {
				this.confirmForm();
			}
			else {
*/				this.realSubmit();
//			}
		}else{
			showPage(0);
		}
	},


	validateForm: function() {
		this._firstName = this.extractFormFieldValue('billing_name_first');
		this._lastName = this.extractFormFieldValue('billing_name_last');
		this._email = this.extractFormFieldValue('donor_email');
		this._street1 = this.extractFormFieldValue('billing_address_street1');
		this._street2 = this.extractFormFieldValue('billing_address_street2');
		this._city = this.extractFormFieldValue('billing_address_city');
		this._state = this.extractFormFieldValue('billing_address_state');
		this._zip = this.extractFormFieldValue('billing_address_zip');
		this._country = this.extractFormFieldValue('billing_address_country');
		this._cardLast4 = this.extractFormFieldValue('card_number');
		this._cardExpMonth = this.extractFormFieldValue('card_exp_date_month');
		this._cardExpYear = this.extractFormFieldValue('card_exp_date_year');

		if (this._cardLast4 != null && this._cardLast4.length > 4) {
			var _end = this._cardLast4.length;
			var _start = _end - 4;			
			this._cardLast4 = this._cardLast4.substr(_start, 4);
			this._cardLast4 = '************' + this._cardLast4;
		}

		var _valid = true;

		if (this.getFormElementById('level_other') && this.getFormElementById('level_other').checked) {
			this.setGiftAmount('');
			var _other = this.getFormElementById('other_amount').value;
			if (_other == null || _other == '') {
				this.displayFieldError('Gift amount is required.');
				_valid = false;
			}
			var _amt = parseCurrency(_other);
			var _min = parseCurrency(this._minGift);
			if (isNaN(_amt)) {
				this.displayFieldError('Please enter a valid gift amount.');
				_valid = false;
			}
			else if (_amt == 0) {
				this.displayFieldError('Gift amount is required.');
				_valid = false;
			}
			else if (_amt < _min) {
				this.displayFieldError('The minimum gift amount is ' + this._minGift + '.');
				_valid = false;
			}
			this.setGiftAmount(_other);
		}
		else {
			this.getFormElementById('other_amount').value = '';
		}
		if (this._giftAmount == null) {
			this.displayFieldError('Gift amount is required.');
			_valid = false;
		}
		if (this._firstName == null) {
			this.displayFieldError('First name is required.');
			_valid = false;
		}
		if (this._lastName == null) {
			this.displayFieldError('Last name is required.');
			_valid = false;
		}
		if (this._email == null) {
			this.displayFieldError('Email address is required.');
			_valid = false;
		}
		if (this._street1 == null) {
			this.displayFieldError('Street address is required.');
			_valid = false;
		}
		if (this._street2 == null) {
			this._street2 = '';
		}
		if (this._city == null) {
			this.displayFieldError('City is required.');
			_valid = false;
		}
		if (this._state == null) {
			this.displayFieldError('State or Province is required.');
			_valid = false;
		}
		if (this._country == null) {
			this._country = '';
		}
		if (this._zip == null) {
			this.displayFieldError('ZIP or postal code is required.');
			_valid = false;
		}
		return _valid;
	},

	extractFormFieldValue: function(id) {
		var _field = this.getFormElementById(id);
		if (_field && _field.value) return _field.value;
		return null;
	},

	confirmForm: function() {
		var submit = this.hitch(this, this.closeAndSubmit);
		var content = this.getFormElementById('confirmation_dialog').innerHTML;
		content = content.replace(/\$firstName/g, this._firstName);
		content = content.replace(/\$lastName/g, this._lastName);
		content = content.replace(/\$email/g, this._email);
		content = content.replace(/\$street1/g, this._street1);
		content = content.replace(/\$street2/g, this._street2);
		content = content.replace(/\$city/g, this._city);
		content = content.replace(/\$state/g, this._state);
		content = content.replace(/\$zip/g, this._zip);
		content = content.replace(/\$country/g, this._country);
		content = content.replace(/\$cardLast4/g, this._cardLast4);
		content = content.replace(/\$cardExpMonth/g, this._cardExpMonth);
		content = content.replace(/\$cardExpYear/g, this._cardExpYear);
		content = content.replace(/\$giftAmount/g, this._giftAmount);
	
		Dialog.confirm(content, {className:this._dialogStyle, width:400, 
                                      okLabel: "Process", cancelLabel: "Cancel", onOk: submit});
	},

	closeAndSubmit: function(win) {
		this.realSubmit();
		return true;
	},

	realSubmit: function() {
		// Tell the user that donation is processing
		this.displayAjaxLoading(true);
			
		// Make the AJAX call
		var handleApiReturn = this.hitch(this, this.handleAjaxSuccess);
		api.callDonationAPI('donate', handleApiReturn, this._form);
	},

	displayAjaxLoading: function(isLoading) {
	    if(isLoading) {
		    // Disable all form elements
			for(var i = 0;i < this._form.elements.length;i++) {   
				_el = this._form.elements[i]; 
				if (_el.disabled == false) {
					_el.should_be_enabled = true;
					_el.disabled = true;
				}
			}
	        this.getFormElementById('ajax_loading').style.display = '';
	    }
	    else {
		    // Enable all form elements
			for(var i = 0;i < this._form.elements.length;i++) {   
				_el = this._form.elements[i]; 
				if (_el.disabled && _el.disabled == true && _el.should_be_enabled) {
					_el.disabled = false;
				}
			}
	        this.getFormElementById('ajax_loading').style.display = 'none';
	    }
	},

	handleAjaxSuccess: function(responseXML, status) {
	    this.displayAjaxLoading(false);
	    if (status == 200) {
		    window.top.location = document.getElementById('success_redirect').value;
	    }
	    else {
		    this.handleAjaxFailure(responseXML, status);
	    }
	},

	displayThankYou: function(responseXML) {
	    	try {
        		this._giftAmount = responseXML.getElementsByTagName("amount").item(0).getElementsByTagName("formatted").item(0).firstChild.nodeValue;
        		this._taxDeductibleAmount = responseXML.getElementsByTagName("tax_deductible_amount").item(0).getElementsByTagName("formatted").item(0).firstChild.nodeValue;
        		this._valueOfGoods = responseXML.getElementsByTagName("value_of_goods").item(0).getElementsByTagName("formatted").item(0).firstChild.nodeValue;
        		this._confirmationCode = responseXML.getElementsByTagName("confirmation_code").item(0).firstChild.nodeValue;
        		this._orgTaxId = responseXML.getElementsByTagName("org_tax_id").item(0).firstChild.nodeValue;
	   	 } catch(e){};

		var content = this.getFormElementById('thanks_window').innerHTML;
		content = content.replace(/\$firstName/g, this._firstName);
		content = content.replace(/\$lastName/g, this._lastName);
		content = content.replace(/\$email/g, this._email);
		content = content.replace(/\$street1/g, this._street1);
		content = content.replace(/\$street2/g, this._street2);
		content = content.replace(/\$city/g, this._city);
		content = content.replace(/\$state/g, this._state);
		content = content.replace(/\$zip/g, this._zip);
		content = content.replace(/\$country/g, this._country);
		content = content.replace(/\$cardLast4/g, this._cardLast4);
		content = content.replace(/\$cardExpMonth/g, this._cardExpMonth);
		content = content.replace(/\$cardExpYear/g, this._cardExpYear);
		content = content.replace(/\$giftAmount/g, this._giftAmount);
		content = content.replace(/\$taxDeductibleAmount/g, this._taxDeductibleAmount);
		content = content.replace(/\$valueOfGoods/g, this._valueOfGoods);
		content = content.replace(/\$confirmationCode/g, this._confirmationCode);
		content = content.replace(/\$orgTaxId/g, this._orgTaxId);

		var resetForm = this.hitch(this, this.closeAndResetForm);

		Dialog.alert(content, {className:this._dialogStyle, width:400, 
                                      okLabel: "Done", onOk: resetForm});
	},

	closeAndResetForm: function(win) {
		this.resetForm();
		return true;
	},

	resetForm: function() {		 	
		// Make the AJAX call to logout
		var handleLogoutReturn = this.hitch(this, this.handleLogoutReturn);
		api.callConsAPI('logout', handleLogoutReturn);
	},

	handleLogoutReturn: function() {	
		window.location.reload(true);
	},

	handleAjaxFailure: function(responseXML, status) {
	    this.displayAjaxLoading(false);
	    var _code = '';
	    var _message = '';
	    var _reason = '';
	    var _pageError = '';
    	    var _fieldErrors = new Array();

	    try {
	    	// Should be included in all error responses
        	_code = responseXML.getElementsByTagName("code").item(0).firstChild.nodeValue;
        	_message = responseXML.getElementsByTagName("message").item(0).firstChild.nodeValue;
        	_reason = responseXML.getElementsByTagName("reason").item(0).firstChild.nodeValue;
	    
		// Optional page error
	        _pe = responseXML.getElementsByTagName("pageError");
	        if (_pe && _pe.length > 0)
	            _pageError = _pe.item(0).firstChild.nodeValue;
	
	        // Optional field errors
	    	var _fe = responseXML.getElementsByTagName("fieldError");
	    	if (_fe && _fe.length > 0) {
	        	for (var i = 0; i < _fe.length; i++) {
	            	_fieldErrors[i] = _fe.item(i).firstChild.nodeValue;
	        	}
	    	}
	    } catch(e){};
            this.displayErrorMessages(_code, _message, _reason, _pageError, _fieldErrors);
	},

	displayFieldError: function(fieldError) {
		var _pageError = 'There was a problem processing your request. Please see below.';
		_fieldErrors = new Array();
		_fieldErrors[0] = fieldError;
		this.displayErrorMessages(0, '', '', _pageError, _fieldErrors);
	},
	
	displayErrorMessages: function(code, message, reason, pageError, fieldErrors) {
		_errorMessage = this.getFormElementById('DonationFormError');
		_errorMessage.style.display = '';
		if (pageError)
			_errorMessage.innerHTML = pageError;
		else
			_errorMessage.innerHTML = message;

		// Handle specific field errors
		if (code == 103) { // Invalid level selected
			_fieldErrorMessage = this.getFormElementById('GiftAmountError');
			if (_fieldErrorMessage) {
				_errorMessage.innerHTML = 'Error: Please select one of the available gift amounts.';
				_fieldErrorMessage.innerHTML = 'Gift amount is required.';
				_fieldErrorMessage.style.display = '';
			}
		}

		// Blank CC number may not generate a field error message
		if (this._form.card_number.value == null || this._form.card_number.value.length == 0) {
			_fieldErrorMessage = this.getFormElementById('CardNumberError');
			if (_fieldErrorMessage) {
			    _fieldErrorMessage.innerHTML = 'Credit card number is required.';
			    _fieldErrorMessage.style.display = '';
			}
		}

		// Kind of a hack - look at the text of the error to determine
		// where to display the error message.
		for (var i = 0; i < fieldErrors.length; i++) { 
			if (fieldErrors[i].toLowerCase().indexOf('amount') > -1) {
				_fieldErrorMessage = this.getFormElementById('GiftAmountError');
				if (_fieldErrorMessage) {
					_fieldErrorMessage.innerHTML = fieldErrors[i];
					_fieldErrorMessage.style.display = '';
				}
			} 
			if (fieldErrors[i].toLowerCase().indexOf('title') > -1) {
				_fieldErrorMessage = this.getFormElementById('TitleError');
				if (_fieldErrorMessage) {
					_fieldErrorMessage.innerHTML = fieldErrors[i];
					_fieldErrorMessage.style.display = '';
				}
			}
			if (fieldErrors[i].toLowerCase().indexOf('first') > -1) {
				_fieldErrorMessage = this.getFormElementById('FirstNameError');
				if (_fieldErrorMessage) {
					_fieldErrorMessage.innerHTML = fieldErrors[i];
					_fieldErrorMessage.style.display = '';
				}
			}
			if (fieldErrors[i].toLowerCase().indexOf('last') > -1) {
				_fieldErrorMessage = this.getFormElementById('LastNameError');
				if (_fieldErrorMessage) {
					_fieldErrorMessage.innerHTML = fieldErrors[i];
					_fieldErrorMessage.style.display = '';
				}
			}
			if (fieldErrors[i].toLowerCase().indexOf('email') > -1) {
				_fieldErrorMessage = this.getFormElementById('EmailError');
				if (_fieldErrorMessage) {
					_fieldErrorMessage.innerHTML = fieldErrors[i];
					_fieldErrorMessage.style.display = '';
				}
			}
			if (fieldErrors[i].toLowerCase().indexOf('street') > -1) {
				_fieldErrorMessage = this.getFormElementById('AddressError');
				if (_fieldErrorMessage) {
					_fieldErrorMessage.innerHTML = fieldErrors[i];
					_fieldErrorMessage.style.display = '';
				}
			}
			if (fieldErrors[i].toLowerCase().indexOf('city') > -1) {
				_fieldErrorMessage = this.getFormElementById('CityError');	
				if (_fieldErrorMessage) {
					_fieldErrorMessage.innerHTML = fieldErrors[i];
					_fieldErrorMessage.style.display = '';
				}
			}
			if (fieldErrors[i].toLowerCase().indexOf('state') > -1) {
				_fieldErrorMessage = this.getFormElementById('StateError');
				if (_fieldErrorMessage) {
					_fieldErrorMessage.innerHTML = fieldErrors[i];
					_fieldErrorMessage.style.display = '';
				}
			}
			if (fieldErrors[i].toLowerCase().indexOf('zip') > -1) {
				_fieldErrorMessage = this.getFormElementById('ZipError');
				if (_fieldErrorMessage) {
					_fieldErrorMessage.innerHTML = fieldErrors[i];
					_fieldErrorMessage.style.display = '';
				}
			}
			if (fieldErrors[i].toLowerCase().indexOf('card number') > -1) {
				_fieldErrorMessage = this.getFormElementById('CardNumberError');
				_fieldErrorMessage.innerHTML = fieldErrors[i];
				_fieldErrorMessage.style.display = '';
			}
			if (fieldErrors[i].toLowerCase().indexOf('expiration') > -1) {
				_fieldErrorMessage = this.getFormElementById('CardExpDateError');
				if (_fieldErrorMessage) {
					_fieldErrorMessage.innerHTML = fieldErrors[i];
					_fieldErrorMessage.style.display = '';
				}
			}
			if (fieldErrors[i].toLowerCase().indexOf('cvv') > -1) {
				_fieldErrorMessage = this.getFormElementById('CVVError');
				if (_fieldErrorMessage) {
					_fieldErrorMessage.innerHTML = fieldErrors[i];
					_fieldErrorMessage.style.display = '';
				}
			}
		}
		window.location.hash = 'DonationFormError';
		showPage(0);
	},

	getFormElementById: function(_id) {
		var _el;
		if (this._form.all) {
			_el = this._form.all[_id];
		}
		else if (this._form.children) {			
			_el = this._form.children[_id];
		}
		if (_el) return _el;
		_list = new Array();
		this.findAllElementsById (this._form, _id, _list);
		if (_list.length > 0) {
			return _list[0];
		}
	},

	findAllElementsById: function (_parent, _id, _list)
	{	

		var ch = _parent.childNodes;

		for (var c = 0; (c < ch.length); c++) {
			var node = ch.item(c);

			// Do not recurse if the node is a leaf (saves tens of thousands of
			// function calls on some pages).

			if (node && node.id && node.id == _id) {
				_list.push (node);
			}
			else if (node.hasChildNodes()) {
				this.findAllElementsById (node, _id, _list);
			}
		}
	},


	hitch: function(/*Object*/scope, /*Function*/method ) {
		return function(){ return method.apply(scope, arguments || []); }; // Function
	}

}

