function frmDataCollector(frm)
{
	this.frm = frm;
}

frmDataCollector.prototype =
{
	encodeNameAndValue: function(name, value)
	{
		param = name+'='+value;
		return param;
	},
	
	frmDataToParams: function()
	{
		var oThis = this;
		var params = "";
		var form = this.frm;
		
		var formElementsLenght = $('#'+this.frm+' :input').length;
		
		$('#'+this.frm+' :input').each(function(i) {
			var field = this;
			var stopped = false;
			
			switch (field.type) {
				case "button":
				case "submit":
				case "reset":
					stopped = true;
				break;
				case "checkbox":
				case "radio":
					if (!field.checked) {
						stopped = true;
						break;
					}
				case "text":
				case "hidden":
				case "password":
					params += oThis.encodeNameAndValue(field.name, field.value);
					break;
				default:
					switch(field.tagName.toLowerCase()) {
						case "select":
							params += oThis.encodeNameAndValue(field.name, field.options[field.selectedIndex].value);
							break;
						default:
							params += oThis.encodeNameAndValue(field.name, field.value);
					}
			}
			if (i < formElementsLenght-2 && !stopped) {
				params += "&";
			}
		});
		return params;
	}
}


function Mailer(strName, strEmail, strSubject, strBody, strPage, send, retmsg, form)
{
	this.name = $('#'+strName);
	this.email = $('#'+strEmail);
	this.subject = $('#'+strSubject);
	this.message = $('#'+strBody);
	this.send = $('#'+send);
	this.retMsg = $('#'+retmsg);
	this.page = $('#'+strPage);
	this.form = form;
	var oThis = this;
	
	if (this.send)
	{
		this.send.bind('click', function() { oThis.sendMail(); });
	}
}

Mailer.prototype = {
	
	checkForm: function()
	{
		if (this.name.attr('value')=="" || this.email.attr('value')=="" || this.subject.attr('value')=="" || this.message.attr('value')=="")
		{
			return "Please fill out all fields marked with a *!";
		}
		if (!this.email.attr('value').match(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/))
		{
			return "Incorrect email address!";
		}
		return "OK";
	},
	
	sendMail: function()
	{
		var oThis = this;
		var check = oThis.checkForm();
		
		if (check == "OK")
		{
			var collector = new frmDataCollector(this.form);
			var params = collector.frmDataToParams();
			var url = "send_contact.php";
			$.ajax({
				type: "POST",
				cache: false,
				url: 'send_contact.php',
				data: params,
				success: function(data) {
					oThis.retMsg.html(data);
				}
			});
		}
		else
		{
			this.retMsg.html('<p>'+check+'</p>');
		}
	}
	
}

$(window).bind('load', function(){
	var mail = new Mailer('uname', 'email', 'subject', 'message', 'page', 'cof_submit', 'retMsg', 'msgfrm');
});
