﻿(function($) {
	$.fn.ajax_refresh = function(options){
		if ( this.length > 1 ){
			this.each(function(){ $(this).ajax_refresh(options); });
			return this;
		}

		var defaults = {
			onStart: null,
			onSuccess: null,
			target: '',
			exclude: ''
		};
		var opts = $.extend({}, defaults, options);
		var obj = this;
		
		var load = function(anchor) {
			if ( anchor.length == undefined )
				anchor = $(anchor);
			if ( typeof opts.onStart == 'function' )
				opts.onStart.call(anchor);
				
			var url = anchor.attr('href').split('#')[0]+'?ajax=1';
			$.get(url, function(data){
				$(opts.target).slideUp('normal', function(){
					$(this).html('');
					$(this).append( $(data).html() );
					$(this).slideDown('normal', function(){
						if ( typeof opts.onSuccess == 'function' )
							opts.onSuccess.call(anchor);
						if ( anchor.attr('href').split('#').length > 1 )
							$.scrollTo('#'+anchor.attr('href').split('#').pop(), {duration: 1000, axis: 'xy'});
							
						if ( anchor.hasClass('contact') ){
							var msg = $('#id_msg_assunto');
							var id = anchor.attr('rel');
							if ( id )
								msg.val(msg.data('autocomplete').options.source[id]);
						}
					});
					window.location.hash = anchor.attr('href').replace(/\.php$/i,'');
				});
			});
		};
		
		$.ajax_refresh = function(anchor){
			return load(anchor);
		}
	
	
		// para cada menu encontrado
		this.initialize = function(){
			if ( opts.exclude )
				var to_exclude = ':not('+opts.exclude+')';
			else
				var to_exclude = '';
			this.find('a'+to_exclude).click(function(){
				obj.load(this);
				return false;
			});
		
			var hash = window.location.hash.substr(1);
			if ( !hash ){
				hash = window.location.pathname.replace(/.*\//,'').replace(/\.php$/i,'');
				if ( !hash ){
					hash = 'index';
				}
			}
			var link = $(this).find('a'+to_exclude+'[href='+hash+'.php]');
			if ( link.length ){
				load(link.first());
			}
		};
		this.load = function(anchor){
			if ( window.location.hash.substr(1) == $(anchor).attr('href').replace(/\.php$/i,'') ){
				if ( typeof opts.onSuccess == 'function' )
					opts.onSuccess.call(anchor);
			} else {
				load(anchor);
			}
		};
		return this.initialize();
	};
})(jQuery);
