// High-level AJAX objects (site-specific)
// Author: Bernard Chan (2008)

// Initial establishment of the namespace
var com = {
	cbkihong: {
	}
};

com.cbkihong.Mailform = function() {
};
Object.extend(com.cbkihong.Mailform.prototype, AnimatedWindow.prototype);
Object.extend(com.cbkihong.Mailform.prototype, {
	setExceptionHandlers: function(handlers) {
		this._handlers = handlers;
	},
	displayForm: function() {
		var me = this;
		if (me.isDisplayed()) {
			return;
		}

		var xmlhttp = getXMLHttpRequest();
		var xmlhttpTimeout = null;
		if (!xmlhttp) {
			(me._handlers['XHRUnavailable'] || function() {})();
			return;
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				window.clearTimeout(xmlhttpTimeout);
				xmlhttpTimeout = null;
				if (xmlhttp.status == 200) {
					var contentDiv = document.createElement('div');
					contentDiv.id = 'form_prefetch';
					document.body.appendChild(contentDiv);
					contentDiv.innerHTML = xmlhttp.responseText;
					document.getElementById('anonymous').onclick = function() { me.toggleEmailFieldStatus() };
					document.getElementById('mailform_send').onclick = function() { me.submitForm() };
					document.getElementById('mailform_reset').onclick = function() { me.resetForm() };
					document.getElementById('mailform_close').onclick = function() { 
						me.collapse();
						document.body.removeChild(contentDiv);
					};
					me.setContentDiv(contentDiv);
					me.onexpanded = function() {
						document.getElementById('email').focus();
					};
					me.expand(); 
				} else {
					(me._handlers['InvalidHttpResponse'] || function() {})();
				}
			}
		};
		xmlhttpTimeout = window.setTimeout(function() {
			window.clearTimeout(xmlhttpTimeout);
			xmlhttpTimeout = null;
			(me._handlers['XHRTimeout'] || function() {})();
		}, 10000);
		xmlhttp.open("GET", 'ajax/view.pl/feedback', true);
		xmlhttp.send('');
	},
	submitForm: function() {
		var me = this;
		var xmlhttp = getXMLHttpRequest();
		var xmlhttpTimeout;
		var respObj = null;

		// TODO Temporary only
		var messages = {
			EMPTY: 'This field cannot be empty.',
			EMAIL_FORMAT: 'Email address not specified in the expected format.',
			MAILFORM_REJECTED: 'Your message was rejected.'
		};

		var si_list = ['status_email', 'status_name', 'status_subject', 'status_message'];
		for (var si = 0; si < si_list.length; si++) {
			document.getElementById(si_list[si]).style.visibility = 'hidden';
		}
		if (!xmlhttp) {
			(me._handlers['XHRUnavailable'] || function() {})();
			return;
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				window.clearTimeout(xmlhttpTimeout);
				xmlhttpTimeout = null;
				if (xmlhttp.status == 200) {
					try {
						eval('respObj = ' + xmlhttp.responseText);
					} catch (error) {
						(me._handlers['InvalidHttpResponse'] || function() {})();
						return;
					}
					if (respObj.status != 'OK') {
						me.shake();
						// Now update the UI to indicate the errors
						for (var fld in respObj.err) {
							with (document.getElementById('status_' + fld)) {
								title = messages[respObj.err[fld]];
								style.visibility = 'visible';
							}
						}
						if (respObj.status == 'MAILFORM_REJECTED') {
							window.alert(messages['MAILFORM_REJECTED']);
						}
					} else {
						// Form accepted
						window.alert('Your feedback has been delivered.');
						document.getElementById('mailform_close').click();
					}
				} else {
					(me._handlers['InvalidHttpResponse'] || function() {})();
				}
			}
		};
		xmlhttpTimeout = window.setTimeout(function() {
			window.clearTimeout(xmlhttpTimeout);
			xmlhttpTimeout = null;
			(me._handlers['XHRTimeout'] || function() {})();
		}, 10000);
		xmlhttp.open("POST", 'ajax/proc/mailform.pl', true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		var qs = [];
		var data = {
			anonymous: (document.getElementById('anonymous').checked?1:0),
			email: document.getElementById('email').value,
			name: document.getElementById('name').value,
			subject: document.getElementById('subject').value,
			message: document.getElementById('message').value,
			sic: document.getElementById('sic').value
		};
		for (var k in data) {
			qs.push(k + '=' + encodeURIComponent(data[k]));
		}
		xmlhttp.send(qs.join('&'));
	},
	toggleEmailFieldStatus: function() {
		var an = document.getElementById('anonymous').checked;
		document.getElementById('email').disabled = an;
		document.getElementById('email').readOnly = an;
	},
	prefillFormFields: function(params) {
		document.getElementById('anonymous').checked = params.anonymous;
		this.toggleEmailFieldStatus(document.getElementById('anonymous'));
		document.getElementById('email').value = params.email;
		document.getElementById('name').value = params.name;
		document.getElementById('subject').value = params.subject;
		document.getElementById('message').value = params.message;
	},
	resetForm: function() {
		var si_list = ['status_email', 'status_name', 'status_subject', 'status_message'];
		for (var si = 0; si < si_list.length; si++) {
			document.getElementById(si_list[si]).style.visibility = 'hidden';
		}
		this.prefillFormFields({
			anonymous: false,
			email: '',
			name: '',
			subject: '',
			message: ''
		});
	}
});
