$(document).ready(function() {
	//set up a dialog object for send email:
	$("#send-email-dialog").dialog({ 
		autoOpen: false,
		modal:true,
		width:'450px',
		width:'500px',
		open: function(e, ui){
			//callback to load form via ajax:
			$.ajax({
				url:vistula.baseUrl+'send-to-friend',
				dataType:'html',
				data: {
					id:vistula.productId
				},
				success:function(data){
					$("#send-email-dialog").html(data);	
					document.getElementById('email-form').to.focus();
				}
			});
		}
	});
	
	$(".send-to-friend").click(function(e){
		e.preventDefault();
		$("#send-email-dialog").dialog('open');
	});
});

vistula.isValidEmailAddress = function(email){
	return /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i.test(email);	
}

vistula.sendToFriend = function(form){
	
	var to = form.to.value;
	var from = form.from.value;
	var subject = form.subject.value;
	var message = form.message.value;
	var id = form.id.value;
	
	//make sure we have a To address:
	if(!vistula.isValidEmailAddress(to)){
		alert('Please provide a valid email address in the "To" field');
		form.to.focus();
		return false;
	}
	
	//and a from address:
	if(!vistula.isValidEmailAddress(from)){
		alert('Please provide a valid email address in the "From" field');
		form.from.focus();
		return false;
	}	
	
	//change form to loading icon:
	$("#send-email-dialog").html('<img src="images/loading.gif"/>');
		
	//ajax post the form to /send-email:
	$.ajax({
		url:vistula.baseUrl+'send-email',
		type: 'POST',
		dataType:'html',
		data: {
			to: to,
			from: from,
			subject: subject,
			message: message,
			id: id
		},
		//on error inform user:
		error:function(xhr, msg, err){
			$("#send-email-dialog").html('Sorry, an error occurred trying to send your email');	
		},
		//on success close dialogue:
		success:function(data){
			$('#send-email-dialog').dialog('close');
		}
	});	
	
}
