$(document).ready(function() {
	$('a[href^="send:"],a[href^="mailto:"]').each(function() {
			$(this).attr('href', $(this).attr('href').replace('send', 'mailto').replace('[+]', '@'))
				.click(contactform);
		});
	$('<div></div>', { id: 'contact'})
		.dialog({
			modal: true,
			autoOpen: false,
			width: 500,
			height: 613,
			title: 'Loading ...',
			show: 'clip',
			hide: 'clip',
			buttons: { 'Cancel': function() { $(this).dialog('close'); } }
		});
});

function contactform() {
	$('#contact').html('<img src="/images/loading.gif" height="32" width="32" alt="loading" style="margin: 218px;">')
		.dialog('option', { title: 'Loading ...', buttons: { 'Cancel': function() { $(this).dialog('close'); } }})
		.dialog('open');
	var href = $(this).attr('href');
	var name = (href.indexOf('<') > -1 && href.indexOf('>') > -1) ? href.substring(7, href.indexOf(' <')) : '';
	var email = (href.indexOf('<') > -1) ? href.substring(href.indexOf('<')+1, href.indexOf('>')) : href.substring(7, ((href.indexOf('?') > -1) ? href.indexOf('?') : href.length));
	var subject = (href.indexOf('subject=') > -1) ? href.substring(href.indexOf('subject=')+8, ((href.indexOf('&', href.indexOf('subject=')) > -1) ? href.indexOf('&', href.indexOf('subject=')) : href.length)) : '';
	var message = (href.indexOf('message=') > -1) ? href.substring(href.indexOf('message=')+8, ((href.indexOf('&', href.indexOf('message=')) > -1) ? href.indexOf('&', href.indexOf('subject=')) : href.length)) : '';
	$.get('/contact.php', { email: email, name: name, subject: subject, message: message },
		function(data) {
			$('#contact').dialog('option', { height: 'auto', 'title': 'Contact '+data.name, buttons: {
					'Send': contactsubmit, 
					'Cancel': function() { $(this).dialog('close'); }
				}})
				.html(data.html);
		}, 'json');
	return false;
}

function contactsubmit() {
	var formdata = $('#contactform').serialize();
	$('#contact').html('<img src="/images/loading.gif" height="32" width="32" alt="sending" style="margin: 218px;">')
		.dialog('option', { title: 'Sending...', buttons: { 'Cancel': function() { $(this).dialog('close'); } }})
	$.post('/contact.php', formdata, function(data) {
			$('#contact').dialog('option', { title: data.title, buttons: { 'Close': function() { $(this).dialog('close'); } } })
				.html(data.html);
		}, 'json');
	return false;
}
