<?php defined('_JEXEC') or die;

/**
 * File       mod_ob_ajax_form.php
 * Created    02/01/16 12:29 PM
 * Author     foobla | noreply@foobla.com | http://foobla.com
 * Copyright  Copyright (C) 2016 betweenbrain llc. All Rights Reserved.
 * License    GNU General Public License version 2, or later.
 */

// Include the helper.
require_once __DIR__ . '/helper.php';
//var_dump($params->get('number'));
// Instantiate global document object
$doc = JFactory::getDocument();

$js = <<<JS
(function ($) {
	function loadAjax() {
	   //var value = JSON.stringify($('.ob_ajax_form form').serializeArray());
	   var value = $('.ob_ajax_form form').serializeArray();
			request = {
					'option' : 'com_ajax',
					'module' : 'ob_ajax_form',
					'data'   : value,
					'format' : 'raw'
				};
		$.ajax({
			type   : 'POST',
			data   : request,
			success: function (response) {
				$('.message').html(response);
			}
		});
	}
	$(document).on('click', '.ob_ajax_form input[type="submit"]', function () {
		var error = false;
		$('.ob_ajax_form form').find('.required').each(function(){
			if($(this).val()=='') {
				$(this).addClass('error');
				error = true;
			} else {
				$(this).removeClass('error');
			}
			if($(this).attr('name')=='email') {
				var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
				var kq = re.test($(this).val());
				if (!kq) {
					$(this).addClass('error');
					error = true;
				}
			}
		});
		if(!error)
			loadAjax();
		return false;
	});
})(jQuery)
JS;

$doc->addScriptDeclaration($js);

require JModuleHelper::getLayoutPath('mod_ob_ajax_form', $params->get('layout', 'default'));