var Hello = window.Hello || {};

/*
 * init with 
 * $(document).ready(Hello.XhrHandler.init);
 * 
 * 
 * [ { type: html, content: …, selector: …, method: … } ]
 *		content is a string with a html snippet
 *		selector is a jquery compatible css selector
 *		method is (html)
 *
 * [ { type: function, name: …, params: … } ]
 *		name is the callable name of the function (global in windows)
 *		params are optional parameters as an array
 */

Hello.XhrHandler = (function() {

	var functions = [];
	
	return new function() {
		
		var that = this;
		
		this.executeRequest = function(url, params) {
			url = Hello.XhrHandler.rewriteUrl(url);
			$.post(url, params, null, 'json')
				.success(function(json) {
					for(ix in json) {
						var item = json[ix];
						switch (item.type) {
							case 'function':
								if (item.name in functions) {
									functions[item.name].apply(window, item.params);
								} else {
									that.handleError('unknown function name ' + item.name);
								}
								break;

							case 'html':
								if (item.method.match(/^(html)$/)) {
									var nodes = $(item.selector);
									nodes[item.method](item.content);
								} else {
									that.handleError('unknown html method ' + item.method);
								}
								break;

							default:
								that.handleError('unknown type ' + item.type);
						}
					}
				}).error(function(ignored, errorMessage) {
					Hello.XhrHandler.handleError(errorMessage);
				})
			;
		};
				
		this.init = function() {
			// call this in $(document).ready

			$(Hello.XhrHandler.LINK_SELECTOR).live('click', function(e) {
				e.preventDefault();
				that.executeRequest.call(that, $(this).attr('href'), null);
			});
			$(Hello.XhrHandler.FORM_SELECTOR).live('submit', function(e) {
				e.preventDefault();
				that.executeRequest.call(that, $(this).attr('action'), $(this).serialize());
			});
		};
		
		this.register = function(name, fn) {
			functions[name] = fn;
		};
		
		// allow to overwrite this to configure:
		
		this.LINK_SELECTOR = 'a.xhr';
		this.FORM_SELECTOR = 'form.xhr';

		this.rewriteUrl = function(url) {
			// dependency to rox
			return '/xhr' + url;
		};

		this.handleError = function(message) {
			if (window.console && window.console.error) {
				window.console.error(message);
			}
		};
		
	};
	
}());

