$( 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 )
{
	if ( data.success )
	{
		$("#popup_content").html( data.message );
		$.popupdisplay( 'popup' );
	}
	else
	{
		$.each( data, function( key, value ) {
			if ( key.indexOf( 'err_' ) == 0 && value != '' )
			{
				$( '#' + key.substr( 4 ) ).parent().addClass( key.substr( 4 ) == 'terms' ? 'alert-chk' : 'alert' );
			}
		} );
	}
}

function hideMessages()
{
	$( 'div[class*=alert]' ).each( function () {
		$( this ).removeClass( 'alert' );
	} );
	$( 'div[class*=alert-chk]' ).each( function () {
		$( this ).removeClass( 'alert-chk' );
	} );
}

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' );
}

function viewPlan( link )
{
	$.ajax( {
		url: $( link ).attr( 'href' ),
		type: 'get',
		dataType: 'html',
		beforeSend: function( request )
		{
			showLoader();
			return true;
		},
		success: function( response, textStatus )
		{
			$("#popup_content").html( response );
			hideLoader();
			$.popupdisplay( 'popup' );
		},
		error: function( request, textStatus, errorThrown )
		{
			hideLoader();
			alert( "Sorry, an error occurred while sending the AJAX request. Please try again later." );
		}
	} );
	
	return false;
}