$( document ).ready( function() {
	$( '#form' ).ajaxForm( {
		url: $( '#form' ).attr('ajaxAction'),
		type: 'post',
		dataType: 'json',
		beforeSend: function( request )
		{
			hideMessages();
			showLoader();
			return true;
		},
		success: function( response, textStatus )
		{
			hideLoader();
			showMessages( response );
			if ( response.success ) {
				$( '#form' ).resetForm();
			}
		},
		error: function( request, textStatus, errorThrown )
		{
			hideLoader();
			alert( "Sorry, an error occurred while sending the AJAX request. Please try again later." );
		}
	} );
	$( '#submit' ).preload( {
		find: '1.gif',
		replace: '2.gif'
	} );
	$( '#submit' ).hover(
		function () {
			$( this ).attr( 'src', $( this ).attr( 'src' ).replace( '1.gif', '2.gif' ) );
		},
		function () {
			$( this ).attr( 'src', $( this ).attr( 'src' ).replace( '2.gif', '1.gif' ) );
		}
	);
} );

function showMessages( data )
{
	$( '<span>' + data.message + '</span>' ).addClass( data.success ? 'success' : 'error' ).appendTo( '#form_msg' );
	
	$.each( data, function( key, value ) {
		if ( key.indexOf( 'err_' ) == 0 && value != '' )
		{
			$( '<span>' + value + '</span>' ).attr( 'id', 'form_err' ).addClass( 'error' ).css( 'padding-left', '10px' ).appendTo( $( '#' + key.substr( 4 ) ).parent().addClass( $( '#' + key.substr( 4 ) ).attr( 'tagName' ).toUpperCase() == 'TEXTAREA' ? 'alert-txt' : 'alert' ).parent() );
		}
	} );
	
	$( '#captcha' ).empty().append( data.captcha );
	$( '#security_code' ).val( '' );
	$( '#security_code_id' ).val( data.security_code_id );
}

function hideMessages()
{
	$( '#form_msg' ).empty();
	$( 'div[class*=alert]' ).each( function () {
		$( this ).removeClass( 'alert' );
	} );
	$( 'div[class*=alert-txt]' ).each( function () {
		$( this ).removeClass( 'alert-txt' );
	} );
	$( 'span[id=form_err]' ).each( function () {
		$( this ).remove();
	} );
}

function showLoader()
{
	$( '#ajax-loader' ).css( {
		'top': $( document ).scrollTop(),
		'padding-top': Math.round( ( $( window ).height() - 100 ) / 2 ) + 'px',
		'display': 'block'
	} );
}

function hideLoader()
{
	$( '#ajax-loader' ).css( 'display', 'none' );
}