$(document).ready(function(){

    // ==============================================
    // Sending the email
    // ==============================================

    function emailIsValid(){
	// See info on regular expressions + Email format definition: RFC 5322
	return $('#email').val().match("^[A-z0-9][\\w.-]*@[A-z0-9][\\w.-]+\\.[A-z0-9]{2,6}$");
    }

    function shakeError( obj ){
	obj.css('background','#F33')
	   .effect("shake",
		   { times: 2, distance: 10 },
		   100,
		   function(){ // When shaking over
		       obj.css('background','white');
		   });
    }

    function checkEmail(){
		var validEmail = true;
		if(emailIsValid()) {
			window.status='Valid Email';
			validEmail = true;
		} else {
			shakeError( $('#email') );
			window.status='Invalid Email';
			validEmail = false;
		}
		return validEmail;
    }

    function checkText(){
		var hasText = false;
		var messageObj = $('#message');
		var text = $.trim(messageObj.val());
		if (text.length < 1){ // empty text
			shakeError( messageObj );
			window.status='Empty text';
			hasText = false;
		} else { hasText = true; }
		return hasText;
    }

    function checkName(){
		var hasName = false;
		var nameObj = $('#name');
		var name = $.trim(nameObj.val());
		if (name.length < 1){ // empty name
			shakeError( nameObj );
			window.status='Empty name';
			hasName = false;
		} else { hasName = true; }
		return hasName;
    }
	
	function codeInput(){
		var hasCode = false;
		
		var codeObj = $('#crap');
		var codeObjC = $.trim(codeObj.val());
		
		var nameObj = $('#codeInput');
		var codeInput = $.trim(nameObj.val());
		if (codeInput.length < 1){ // empty code
			shakeError( nameObj );
			window.status='Empty name';
			hasCode = false;
		} else { hasCode = true; }
		return hasCode;
    }
	
    function sendEmailOnClick(){

		// Check for errors
		var oktopost = checkName();
		oktopost  = checkEmail() && oktopost;
		oktopost  = checkText() && oktopost;
		oktopost = codeInput() && oktopost;
	
		if(oktopost){
			// Remove the send handlers, not to click twice
			$('#contact-form-sendbutton').unbind('click', sendEmailOnClick);
	
			// Display sending
			$('#contact-form-answer').append('Skickar<br /><img src="./gfx/loading2.gif" alt=""/>');
			$('#fadeout').fadeTo('slow',0.33);
					
			// Send email
			$.post("post.php", // I post the that page, with POST method
			   { // I pass some parameters
				   name:$('#name').val(),
				   email:$('#email').val(),
				   message:$('#message').val(),
				   codeInput:$('#codeInput').val(),
				   rndCode:$('#rndCodeDiv').val(),
				   ajax:true // I pass this extra one to return a small display, not the thanks.html
			   },
			   // Upon success for the request
			   function(data){
	
				   //console.log("Error? "+data.error + "Reason: "+data.reason);
	
				   if(data.error){
					   $('#contact-form-answer').html('Mejlet kunde inte skickas! (JS)');
					   return false;
				   } else {
				   // Display "no error" message
				   $('#contact-form-answer').html('Tack '+data.name+'<br />Vi h&ouml;r av oss s&aring; fort som m&ouml;jligt!');
				   $('#fadeout').fadeTo('slow',1);
				   setTimeout(function(){
					   // Emptying the form
					   $('#contact-form-answer').empty();
					   $('#name').val('');
					   $('#email').val('');
					   $('#message').val('');
					   $('#codeInput').val('');
						   // Re-assigning the click action on the send button
					   $('#contact-form-sendbutton').bind('click', sendEmailOnClick);
				   }, 2000 // Timeout
						 );
					   return false;
				   }
			   },
			   "json" // Format of the answer. Programmed in post.html
			  );
		} // !oktopost
		return false; // I don't want to submit really...
		}
	
		// Assign the button action
		$('#contact-form-sendbutton').click(sendEmailOnClick);
	
		// Reset when input and textarea get clicked 
		$('input, textarea').focus(function(){$(this).css('background-color','white');});

	}
);

