/**
 * (c) Paul Uithol, 2009. Wrapper for jQuery ajax; adds data loading at a set interval, and callbacks with a specified scope.
 * 
 * Load data from an URL to the specified callback function. Allows specifying callback scope, and a regular interval at which to load data.
 * @param options {object}
 *		required:
 *			- url {string}
 *		optional:
 *			- interval {int} Request the given url at a fixed interval; in ms
 *			- cancel {bool} If the data should stop loading at the given interval, modify the original options object to include the property 'cancel'
 *			- callbackScope {object} Scope in which callbacks (success, error, complete) should be executed. Defaults to 'loadData'
 *			- success, complete, error {function} $.ajax callback functions.
 *			- all regular $.ajax options (data, dataType, cache, timeout, etc).
 *			- debug {bool} Print request info & options
 */
(function( $ ) {
	$.loadData = function( options ) {
		var dit = this;
		var args = arguments; // copy to 'args' so we can access the original arguments within closures (that have their own arguments)
		
		var params = $.extend( {}, $.loadData.defaults, options, {
			complete: function() {
				// If an inverval is specified, schedule the next call. Pass the original arguments to loadData.
				if ( params.interval )
					window.setTimeout( function() { dit.loadData.apply( dit, args ) }, params.interval );
				
				$.isFunction( options.complete ) && options.complete.apply( options.callbackScope, arguments );
			},
			success: function( data, status ) {
				$.isFunction( options.success ) && options.success.apply( options.callbackScope, arguments );
			},
			error: function( xmlHttp, status, error ) {
				params.debug && console.warn( 'ajax error: %s - $%s', status, error );
				
				if ( xmlHttp.status && ( xmlHttp.status > 300 && xmlHttp.status < 399 ) )
					window.location.reload();
					//$('body').append( xmlHttp.status );
				
				$.isFunction( options.error ) && options.error.apply( options.callbackScope, arguments );
			}
		});
		
		if ( params.callbackScope ) // if callbackScope is a large/deep object, causes heavy delays/copying in ajax setup as jQuery.extend( true, ... ) is performed on params in jQuery.ajax
			delete params.callbackScope;
		
		var d = new Date();
		params.debug && console.log( 'loadData options @ %i:%i:%i : %o', d.getHours(), ( d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes() ), ( d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds() ), params );
		
		if ( options.cancel || !params.url )
			return;
		
		$.ajax( params );
		
		return this;
	};
	
	$.loadData.defaults = {
		debug: false,
		url: null,
		cache: false,
		dataType: 'json',
		timeout: null,
		interval: null
	};
})( jQuery );

