/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                                                                 //
//                                         ___           ___                                                       //
//                                        /__/\         /  /\         _____                                        //
//                                       _\_ \:\       /  /:/_       /  /::\                                       //
//                                      /__/\ \:\     /  /:/ /\     /  /:/\:\                                      //
//                                     _\_ \:\ \:\   /  /:/ /:/_   /  /:/~/::\                                     //
//                                    /__/\ \:\ \:\ /__/:/ /:/ /\ /__/:/ /:/\:|                                    //
//                                    \  \:\ \:\/:/ \  \:\/:/ /:/ \  \:\/:/~/:/                                    //
//                                     \  \:\ \::/   \  \::/ /:/   \  \::/ /:/                                     //
//                                      \  \:\/:/     \  \:\/:/     \  \:\/:/                                      //
//                                       \  \::/       \  \::/       \  \::/                                       //
//                                        \__\/         \__\/         \__\/                                        //
//        ___           ___                         ___                                   ___           ___        //
//       /  /\         /  /\                       /__/\          ___       ___          /  /\         /__/\       //
//      /  /:/_       /  /::\                      \  \:\        /  /\     /  /\        /  /::\        \  \:\      //
//     /  /:/ /\     /  /:/\:\    ___     ___       \  \:\      /  /:/    /  /:/       /  /:/\:\        \  \:\     //
//    /  /:/ /::\   /  /:/  \:\  /__/\   /  /\  ___  \  \:\    /  /:/    /__/::\      /  /:/  \:\   _____\__\:\    //
//   /__/:/ /:/\:\ /__/:/ \__\:\ \  \:\ /  /:/ /__/\  \__\:\  /  /::\    \__\/\:\__  /__/:/ \__\:\ /__/::::::::\   //
//   \  \:\/:/~/:/ \  \:\ /  /:/  \  \:\  /:/  \  \:\ /  /:/ /__/:/\:\      \  \:\/\ \  \:\ /  /:/ \  \:\~~\~~\/   //
//    \  \::/ /:/   \  \:\  /:/    \  \:\/:/    \  \:\  /:/  \__\/  \:\      \__\::/  \  \:\  /:/   \  \:\  ~~~    //
//     \__\/ /:/     \  \:\/:/      \  \::/      \  \:\/:/        \  \:\     /__/:/    \  \:\/:/     \  \:\        //
//       /__/:/       \  \::/        \__\/        \  \::/          \__\/     \__\/      \  \::/       \  \:\       //
//       \__\/         \__\/                       \__\/                                 \__\/         \__\/       //
//                           ___           ___           ___           ___           ___                           //
//                          /  /\         /__/\         /  /\         /  /\         /__/|                          //
//                         /  /:/_        \  \:\       /  /::\       /  /:/        |  |:|                          //
//                        /  /:/ /\        \__\:\     /  /:/\:\     /  /:/         |  |:|                          //
//                       /  /:/ /::\   ___ /  /::\   /  /:/~/::\   /  /:/  ___   __|  |:|                          //
//                      /__/:/ /:/\:\ /__/\  /:/\:\ /__/:/ /:/\:\ /__/:/  /  /\ /__/\_|:|____                      //
//                      \  \:\/:/~/:/ \  \:\/:/__\/ \  \:\/:/__\/ \  \:\ /  /:/ \  \:\/:::::/                      //
//                       \  \::/ /:/   \  \::/       \  \::/       \  \:\  /:/   \  \::/~~~~                       //
//                        \__\/ /:/     \  \:\        \  \:\        \  \:\/:/     \  \:\                           //
//                          /__/:/       \  \:\        \  \:\        \  \::/       \  \:\                          //
//                          \__\/         \__\/         \__\/         \__\/         \__\/                          //
//                                                                                                                 //
//                                                                                                                 //
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                                                                 //
//                                       W e b   S o l u t i o n   S h a c k                                       //
//                                                    Matt Rabe                                                    //
//                                                       '09                                                       //
//                                                                                                                 //
//                                             www.websolutionshack.com                                            //
//                                                                                                                 //
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////
// Initial Setup
////////////////////////////////////////////////////////////////////////////////////

var AjaxTransfer = Class.create({
	initialize: function(varname)
	{
		this.self = (varname != null ? varname : 'ajax');

		this.wrapper_id = (this.wrapper_id != null ? this.wrapper_id : 'facebox_responses_wrapper');
		this.error_id = (this.error_id != null ? this.error_id : 'facebox_responses_error');
		this.success_id = (this.success_id != null ? this.success_id : 'facebox_responses_success');
		this.loading_id = (this.loading_id != null ? this.loading_id : 'facebox_responses_loading');
		this.text_id = (this.text_id != null ? this.text_id : 'facebox_responses_text');

		this.pendingTransfers = 0;
		this.error = false;
		this.success = false;
	},

	clean: function(str)
	{
		return core.clean(str);
	},
	
	cleanQuotes: function(str)
	{
		return core.cleanQuotes(str);
	},

	encode: function(str)
	{
		return encodeURI(escape(str.toString().replace(/%/g, 'wssatitagain'))).replace(/wssatitagain/g, '%25');
	},
	
	get: function(url, cb)
	{
		if (this.pendingTransfers == 0)
		{
			if (typeof(cb) != 'function')
			{
				this._get(url, null);
			}else{
				this._get(url, (typeof(cb) == 'function' ? cb : null));
			}
		}
	},

	_get: function(url, cb)
	{
		// Initiate loading lock (can't start another load)
		this.loading();

		new Ajax.Request(url,
		{
			onSuccess: this.successHandler(this.self, cb),
			onFailure: this.failureHandler(this.self, cb),
			onTimeout: this.timeoutHandler(this.self, cb),
			onComplete: this.completeHandler(this.self, cb)
		});
	},

	loading: function()
	{
		previouslyLoading = (this.pendingTransfers > 0 ? true : false);

		if (!previouslyLoading)
		{
			// Hide Error indicator, ITIS
			if ($(this.error_id))
			{
				$(this.error_id).hide();
			}

			// Hide Success indicator, ITIS
			if ($(this.success_id))
			{
				$(this.success_id).hide();
			}

			// Hide Response text, ITIS
			this.clearResponse();
			
			// Show loading indicator
			if ($(this.loading_id))
			{
				$(this.loading_id).show();
			}
		}

		this.pendingTransfers++;
		
		return previouslyLoading;
	},
	
	done: function()
	{
		if (this.pendingTransfers > 0)
		{
			this.pendingTransfers--;

			// Show Error icon, if there's an error
			if (this.error)
			{
				this.showError();
			}else{
				// Hide loading indicator
				if (this.pendingTransfers == 0 && $(this.loading_id))
				{
					$(this.loading_id).fade({from: 1, to: 0, duration: .2});
				}			
			}		
		}else{
			return false;
		}
	},
	
	addSuccess: function(success)
	{
		if ($(this.text_id))
		{
			$(this.text_id).innerHTML = success;
		}
		
		this.success = true;
	},
	
	showSuccess: function()
	{
		if (this.success && $(this.error_id))
		{
			$(this.loading_id).hide();
			$(this.success_id).show();

			// Fade out success message after X seconds
			window.setTimeout('$(\''+this.success_id+'\').fade({from: 1, to: 0, duration: 1}); $(\''+this.text_id+'\').fade({from: 1, to: 0, duration: 1});', 5000)
		}
	},
	
	addError: function(error)
	{
		if ($(this.text_id))
		{
			$(this.text_id).innerHTML = error;
		}
		
		this.error = true;
	},
	
	showError: function()
	{
		if (this.error && $(this.error_id))
		{
			$(this.loading_id).hide();
			$(this.error_id).show();
		}
	},
	
	clearResponse: function()
	{
		if ($(this.text_id))
		{
			$(this.text_id).innerHTML = '';
		}
		
		// Reset the response indicators
		this.error = false;
		this.success = false;
	},
	
	transfer: function(params, cb)
	{
		if (this.pendingTransfers == 0)
		{
			if (typeof(cb) != 'function')
			{
				this._transfer(params, null);
			}else{
				this._transfer(params, (typeof(cb) == 'function' ? cb : null));
			}
		}
	},

	_transfer: function(params, cb)
	{
		// Initiate loading lock (can't start another load)
		this.loading();

		new Ajax.Request('/ajax/ajaxtransfer.php',
		{
			parameters: params.replace(/&amp;/g, '&'),

			onSuccess: this.successHandler(this.self, cb),
			onFailure: this.failureHandler(this.self),
			onTimeout: this.timeoutHandler(this.self),
			onComplete: this.completeHandler(this.self)
		});
	},
	
	successHandler: function(self, cb)
	{
		return function(resp)
		{
			if (resp.status != "200")
			{
				eval(self).addError((resp.responseText != '' ? resp.responseText : 'Oops! We\'ve encountered an error. Please try again.'));
			}

			eval(self).done();

			if (resp.status == "200")
			{
				if (cb != null)
				{
					cb(resp.responseText);
				}
			}
		}
	},
	
	failureHandler: function(self)
	{
		return function(resp)
		{
			// No good... couldn't load a valid 2xx response
			eval(self).addError('Oops! There was a network failure. Please try again.');

			eval(self).done();
		}
	},
	
	timeoutHandler: function(self)
	{
		return function(resp)
		{
			// Timeout...
			eval(self).addError('Oops! Your request timed out. Please try again.');

			eval(self).done();
		}
	},
	
	completeHandler: function(self)
	{
		return function(resp)
		{
		}
	},
	
	callInProgress: function(xmlhttp)
	{
		switch (xmlhttp.readyState) 
		{
			case 1:
			case 2:
			case 3:
				return true;
				break;

			// Case 4 and 0
			default:
				return false;
				break;
		}
	}
	
}); // End Class AjaxTransfer

var ajax = new AjaxTransfer('ajax'); // Pass the new class its own varname so that responders can access the global variable

// Register global responders that will occur on all AJAX requests - this is done to facilitate the onTimeout state for ajax calls
Ajax.Responders.register({
	onCreate: function(request)
	{
		request['timeoutId'] = window.setTimeout
		(
			function() 
			{
				// If we have hit the timeout and the AJAX request is active, abort it and let the user know
				if (ajax.callInProgress(request.transport))
				{
					request.transport.abort();

					// Run the onTimeout method if we set one up when creating the AJAX object
					if (request.options['onTimeout'])
					{
						request.options['onTimeout'](request.transport, request.json);
					}
				}
			},
			7000 // Timeout length in milliseconds
		);
	},

	onComplete: function(request) 
	{
		// Clear the timeout, the request completed ok
		window.clearTimeout(request['timeoutId']);
	}
});

