// prepare the form when the DOM is ready 
// options configuration: http://jquery.malsup.com/form/#options-object
// http://jquery.malsup.com/form/

$(document).ready(function() 
{ 
	// full version
	var options = 
	{ 
		target: '#social_email_form',		// target element(s) to be updated with server response 
		dataType: 'json',				
		beforeSubmit: showRequest,		// pre-submit callback 
		success: processJson, 
		resetForm: true			// post-submit callback
	}; 
	$('#send_page_via_email').ajaxForm(options); 

	// min version
	var options_min = 
	{ 
		target: '#social_email_form_min',		// target element(s) to be updated with server response 
		dataType: 'json',				
		beforeSubmit: showRequest,			// pre-submit callback 
		success: processJson, 
		resetForm: true				// post-submit callback
	}; 

	$('#send_page_via_email_min').ajaxForm(options_min);

}); 

// pre-submit callback 
function showRequest(formData, jqForm, options) 
{ 
	//var queryString = $.param(formData); 
	var emailString = formData['0']['value'];
	if ( confirm ('Send page link to: ' + emailString + ' ?') )
		return true;
	else
		return false;

	// here we could return false to prevent the form from being submitted; 
	// returning anything other than false will allow the form submit to continue 
	//return true; 
} 

// full version post-submit callback 
function processJson(data) 
{ 
	// 'data' is the json object returned from the server 
	alert(data.message); 
	
	if (data.val==true) {
		// overwrite both full and min divs to prevent further sends
		var msgstr = "Please reload the page in order to email another link.";
		$('#send_page_via_email').html(msgstr);
		$('#send_page_via_email_min').html(msgstr);
	}

	// close either form if open
	if ( $('#social_email_form').is(':visible')) {
		$('#social_email_form').hide();
	}
	if ( $('#social_email_form_min').is(':visible')) {
		$('#social_email_form_min').hide();
	}

}
