/**
 * @author Seich
 * Martian Wabbit Productions © All Rigths Reserved
 *
 * if you are looking at this code to learn something. Go ahead and read it :)
 */

//check email valid against pattern.
function chkemail(e){
	var pattern = new RegExp(/\w+([.-_]\w+)*@\w+([.-_]\w+)*\.\w{2,4}/g);
	return pattern.test(e);
}

$.fn.clearForm = function() {
  return this.each(function() {
 var type = this.type, tag = this.tagName.toLowerCase();
 if (tag == 'form')
   return $(':input',this).clearForm();
 if (type == 'text' || type == 'password' || tag == 'textarea')
   this.value = '';
 else if (type == 'checkbox' || type == 'radio')
   this.checked = false;
 else if (tag == 'select')
   this.selectedIndex = -1;
  });
};

$(function(){
	//real-time field value checker.
	$("#formName").keyup(function(){
		var name = $("#formName").val().length;
		if(name != 0){
			if(name > 2){
				$("#nind").css({ "background-image": "url('images/check.gif')"});
			}else{
				$("#nind").css({ "background-image": "url('images/x.gif')"});
			}
		}else{
			$("#nind").css({ "background-image": "none"});
		}
	});
	
	$("#formEmail").keyup(function(){
		var email = $(this).val();
		if(email != 0){
			if(chkemail(email)){
				$("#emind").css({ "background-image": "url('images/check.gif')"});
			}else{
				$("#emind").css({ "background-image": "url('images/x.gif')"});
			}
		}else{
			$("#emind").css({ "background-image": "none"});
		}
	});	
	
    $("#submit").click(function(){
		var name = $("#formName").val();
		var email = $("#formEmail").val();
		var msg = $("textarea").val();
		
		$("#mainForm").hide();
		$("#body").append("<img src='images/loading.gif' id='loader' width='136' height='134' />");
		
		$.ajax({
			type: "POST",
			url: "mail.php",
			data: 'name=' + name + '&email=' + email + '&msg=' + msg,
			success: function(r){
				$("#loader").remove();
				$("#result").replaceWith("<div id='result'>" + r + "</div>");
				$("#result").hide().fadeIn("slow");
				$("#mainForm").fadeIn();
				if(r == "Your name should be atleast 3 characters long to be valid."){
					$("#formName").focus();
				}else if(r == "Please enter a valid email."){
					$("#formEmail").focus();
				}else if(r == "Please enter a message."){
					$("textarea").focus();
				}else if(r == "The Message was sent successfully."){
					$("form").clearForm();
				}
			}
		});		
		return false;
	});
});
