(function($) {
	$(document).ready(function() {
		$.fn.extend({
			'eviewLoad': function(targetElement, xhr) {
				// only work with anchors and forms.
				if (!($(this).is('a') || $(this).is('form'))) {
					return;
				}
				// determine target element
				if (!targetElement) {
					targetElement = $(this).parents('div.eview-link-target').eq(0);
				}
				else if (typeof targetElement != 'object') {
					targetElement = $(targetElement);
				}
				
				var sourceElement = $(this);
				var xhr = $.extend({
					success: function(data) {
						var json = this.getJSON(data);
						if (json) {
							if (json['redirect']) {
								window.location.href = json['redirect'];
								return;
							}
						}
						if ($.scrollTo) {
							if (!this.source.attr('class').match('no-scrolling')) {
								$.scrollTo( this.target, 1000 , {easing:'swing'} );
							}
						}
						this.target.replaceWith(data);
					}
				}, xhr, {
					target: targetElement,
					source: sourceElement,
					getJSON: function (data) {
						if (typeof data == 'string') {
							if (data.substring(0, 1) == '{') {
								// try parsing JSON data
								data = eval('(' + data + ')');
							}
							if (typeof data == 'object') {
								return data;
							}
						}
						return false;
					}
				});

				// set some defaults if a form is encountered.
				if ($(this).is('form')) {
					xhr.type = $(this).attr('method');
					xhr.url = $(this).attr('action') || window.location.href;
					xhr.data = $(this).serialize();
					$(this).find('input[type="submit"]').attr({'disabled' : 'disabled'});	// Disable the submit button(s)
				}

				// set some defaults if an anchor is encountered.
				if ($(this).is('a')) {
					xhr.url = $(this).attr('href');
				}
				
				// run
				$.ajax(xhr);
				return false;
			}
		});
	});
})(jQuery);
