var visitor_name, visitor_email, visitor_phone;

$(function () {
	$('input[name="email"]').blur(function(event) {
		/*if (event.which === 13) {
			// the enter key was pressed
		}*/
		visitor_name = $('input[name="name"]').val();
		visitor_email = $(this).val();
		visitor_phone = $('input[name="phone"]').val();
		
		if( isValidEmailAddress(visitor_email) ) {
			ajax_process_email();
		}		
	});
	
	$('input[name="name"]').blur(function(event) {
		/*if (event.which === 13) {
			// the enter key was pressed
		}*/
		visitor_name = $(this).val();
		visitor_email = $('input[name="email"]').val();
		visitor_phone = $('input[name="phone"]').val();
		
		if( isValidEmailAddress(visitor_email) ||  visitor_phone.length > 0) {
			ajax_process_email();
		}		
	});
	
	$('input[name="phone"]').blur(function(event) {
		/*if (event.which === 13) {
			// the enter key was pressed
		}*/
		visitor_name = $('input[name="name"]').val();
		visitor_email = $('input[name="email"]').val();
		visitor_phone = $(this).val();
		
		if( visitor_phone.length > 0) {
			ajax_process_email();
		}		
	});
	
});


function ajax_process_email() {
	//alert("in ajax_process_email");
    $.ajax({ /*url : 'http://www.mydemozone.com/campuspoint/ajax_process.php',*/
        url: template_url + '/js/trackvisitor-ajax.php', // template_url defined in contactus.php (wordpress env)
        type: 'post',
        data: 'Email=' + visitor_email + '&Name=' + visitor_name + '&Phone=' + visitor_phone,
        timeout: 10000/*, //  timeout 10 seconds
        success: function (response) {
            alert(response);
        },
        error: function (x, t, m) {
            if (t === "timeout") {
                alert("Got timeout in AJAX");
            } else {
                alert("Error in AJAX loading: " + t);
            }
        }*/
    });
}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
};
