/**
* TiM's Regex Tester
* JavaScript code to setup and send AJAX
* requests, and to then parse the result.
*
* Powered by jQuery - http://www.jquery.com/
**/

/*Called when the form is submitted.*/
function SubmitRequest()
{
	//verify regex data is correct
	if( $("#regex_field").val() == '' )
	{
		alert( 'ERROR: You must fill in the regex text field!' );
		return;
	}

	//verify search data
	if( $("#search_field").val() == '' )
	{
		alert( 'ERROR: You must fill in the searchable data text field!' );
		return;
	}

	//show the loading graphic
	$('.loader_img').show();

	//hide the previous ajax output
	//(and delay the ajax request until the anim is done)
	if( $('#ajax_output').css('display') != 'none')
		 $('#ajax_output').slideUp( 300, function() { sendAJAX(); });
	else
		sendAJAX();
}

/*Perform the AJAX request*/
function sendAJAX()
{
	//grab the form data for submission
	var formData = $('#regex_form').serialize();
	//append submit on the end
	formData += "&submit=submit";
	
	//perform the ajax request
	$.ajax( { url: '/?request=ajax', dataType: 'json', data: formData, type: 'POST', error: RequestError, success: RequestSuccess } );
}

/*Callback function on AJAX successful completion*/
function RequestSuccess(data, textStatus, XMLHttpRequest)
{
	var css_class = '';
	if( data['success'] == true )
		css_class = 'success';
	else
		css_class = 'error';
		
	var html = '<div class="msg '+css_class+'">\n'+data['message']+'\n</div><hr/>\n';
	if(data['success'] == true)
	{
		html += '<div class="output">\n';
		html += '<img src="/img/close_button.png" width="34" height="34" alt="Close" id="close_output" title="Close" />';
		html += data['regex_output'];
		html += '\n</div>\n<hr/>';
	}
	
	//hide the loading graphic
	$('.loader_img').hide();	
	
	//show the HTML
	$('#ajax_output').html(html);
	//lock in the close button callback
	$('#close_output').click( function() { $('#ajax_output').slideUp( 300 ); } );
	//show the div
	$('#ajax_output').slideDown(300);
	
	//scroll the page up to the top
	var scrollDest = $('#ajax_output').offset().top;
	$("html:not(:animated),body:not(:animated)").animate({ scrollTop: scrollDest-20}, 500 );
}

/*Callback function for when AJAX request fails.*/
function RequestError(XMLHttpRequest, textStatus, errorThrown)
{
	if( textStatus != 'parsererror')
	{
		alert( 'ERROR: Ajax request reported: '+textStatus );
		return;
	}
	
	alert( 'ERROR: A PHP error occurred:\n'+XMLHttpRequest.responseHTML);
}
