$(document).ready( function(){

	function openLoading(){

		$('#loading').dialog({
			closeOnEscape: false,
			draggable: false,
			resizable: false,
			modal: true
		});
	}
	
	function closeLoading(){

		$('#loading').dialog('destroy');
	}
	
	// detectando se eh ajax
	if( window.location.hash.indexOf('#') >= 0 ){

		// extraindo ancora que contem endereco
		var getParametros = window.location.hash.substr( window.location.hash.indexOf('#') + 1 );
		
		if( getParametros.indexOf('/') < 0 )
			return;

		// ------ dialog -----
		openLoading();
		
		// ajax na manha
		$.ajax({
			url: getParametros,
			type: 'GET',
			dataType: 'html',
			complete: function(xhr, textStatus) {
				$('#page-content').html(xhr.responseText).ready( function(){
					closeLoading();
				});
			},
			success: function(data, textStatus, xhr) {
				//called when successful
			},
			error: function(xhr, textStatus, errorThrown) {
				//called when there is an error
			}
		});
	}

	//clique em links
	$('a').live( 'click', function(event) {

		if( $(this).attr( 'target' ) == '_blank' || $(this).parents('#ui-datepicker-div, #jquery-lightbox, .noAjax' ).length > 0 )
			return;
		
		// previne comportamento padrão
		event.preventDefault();
		
		// dialog
		openLoading();

		// armazana referencia ao objeto this
		$this = $(this);

		// ajax na manha
		$.ajax({
			url: $this.attr('href'),
			type: 'GET',
			dataType: 'html',
			complete: function(xhr, textStatus) {
				window.location.hash = $this.attr('href');
				$('#page-content').html(xhr.responseText).ready( function(){
					closeLoading();
				});
			},
			success: function(data, textStatus, xhr) {
				//called when successful
			},
			error: function(xhr, textStatus, errorThrown) {
				//called when there is an error
			}
		});
	});
	
	// submit form
	$('form').live( 'submit', function( event ) {

		if( $(this).hasClass( 'noAjax' ) )
			return;
		
		event.preventDefault();
		openLoading();
		
		$this = $(this);

		$.ajax({
			url: $this.attr('action'),
			type: 'POST',
			dataType: 'html',
			data: $this.serialize(),
			complete: function(xhr, textStatus){
				window.location.hash = $this.attr( 'action' );
				$('#page-content').html(xhr.responseText).ready( function(){
					closeLoading();
				});
			},
			success: function(data, textStatus, xhr) {
				//called when successful
			},
			error: function(xhr, textStatus, errorThrown) {
				//called when there is an error
			}
		});
	});
});