/**
 * Webfolio CMS
 *
 * Copyright (C) 2009 Nikola Posa (http://www.nikolaposa.in.rs)
 *
 * This file is part of Webfolio CMS.
 *
 * Webfolio CMS is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 *
 * Webfolio CMS is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License 
 * along with Webfolio CMS. If not, see <http://www.gnu.org/licenses/>.
 */
 
/**
 * Contact form JS/AJAX functionality.
 *
 * @author Nikola Posa <posa.nikola@gmail.com>
 * @license http://opensource.org/licenses/gpl-3.0.html GNU General Public License
 */
  
/**
 * Sends email using AJAX request.
 *
 * @return void
 */
function sendEmail() {
	$('#contact_form').ajaxSubmit(
	{
		type: 'POST',
		url: $('#base_url').val() + '/front-end/ajax_handlers/contact_form.php',
		beforeSubmit: function(data, form, options) {
			$('#progressImg').html('<img src = "' + $('#base_url').val() + '/front-end/img/ajax-loader.gif" alt = "Sending..." />');
		},
		success: function(response, status, xhr) {
			$('.error_message').html('');
			$('#progressImg').html('');
			
			var msg = $.secureEvalJSON(response);
			
			if (msg.status && msg.message) { //Regular message.
				var messageClass = '';
			
				if (msg.status == 'ok') {
					messageClass = 'green';
					$('#text').val(''); //Reseting text field.
				}
				else if (msg.status == 'error') {
					messageClass = 'red';
				}
				
				$('#message').show();
				$('#message').html('<p class = "message_' + messageClass + '">' + msg.message + '</p>');
			}
			else { //JSON (validation errors)?
				var errMsgs = msg;
				
				//Displaying validation messages.
				var marker = 0;
				for (var field in errMsgs) {
					$('#err_' + field).html(errMsgs[field]);
					if (marker == 0) {
						$('#' + field).focus();
						marker = 1;
					}
					
					//Enabling AJAX validation of single contact form element (onkeyup event).
					$('#' + field).keyup(function(){
						var field = $(this).attr('name');
						
						$.ajax({
							type: 'POST',
							url: $('#base_url').val() + '/front-end/ajax_handlers/contact_form.php',
							data: $('#' + field).fieldSerialize(),
							dataType: 'json',
							success: function(msg) {
								$('#err_' + field).html(msg[field]);
							}
						});
					});
				}
			}
		}
	});
}